From 8d98daa1beb46fe61022727b25c9e5b75db5e630 Mon Sep 17 00:00:00 2001 From: Min Chen Date: Wed, 9 Jan 2013 16:11:23 -0800 Subject: [PATCH 01/80] Add API throttling config items and APILimitChecker Adapter interface, add api limit checking in APIServer flow. --- .../cloudstack/acl/APILimitChecker.java | 28 +++++++++++++++++++ .../org/apache/cloudstack/api/BaseCmd.java | 1 + server/src/com/cloud/api/ApiServer.java | 27 ++++++++++++++++++ .../src/com/cloud/configuration/Config.java | 6 +++- 4 files changed, 61 insertions(+), 1 deletion(-) create mode 100644 api/src/org/apache/cloudstack/acl/APILimitChecker.java diff --git a/api/src/org/apache/cloudstack/acl/APILimitChecker.java b/api/src/org/apache/cloudstack/acl/APILimitChecker.java new file mode 100644 index 00000000000..3a1db705e70 --- /dev/null +++ b/api/src/org/apache/cloudstack/acl/APILimitChecker.java @@ -0,0 +1,28 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.acl; + +import com.cloud.user.Account; +import com.cloud.utils.component.Adapter; + +/** + * APILimitChecker checks if we should block an API request based on pre-set account based api limit. + */ +public interface APILimitChecker extends Adapter { + // Interface for checking if the account is over its api limit + boolean isUnderLimit(Account account); +} diff --git a/api/src/org/apache/cloudstack/api/BaseCmd.java b/api/src/org/apache/cloudstack/api/BaseCmd.java index d964e70b84f..ae130129bb0 100644 --- a/api/src/org/apache/cloudstack/api/BaseCmd.java +++ b/api/src/org/apache/cloudstack/api/BaseCmd.java @@ -89,6 +89,7 @@ public abstract class BaseCmd { public static final int PARAM_ERROR = 431; public static final int UNSUPPORTED_ACTION_ERROR = 432; public static final int PAGE_LIMIT_EXCEED = 433; + public static final int API_LIMIT_EXCEED = 434; // Server error codes public static final int INTERNAL_ERROR = 530; diff --git a/server/src/com/cloud/api/ApiServer.java b/server/src/com/cloud/api/ApiServer.java index 56cef123e2c..2bb7fdd6e69 100755 --- a/server/src/com/cloud/api/ApiServer.java +++ b/server/src/com/cloud/api/ApiServer.java @@ -52,6 +52,7 @@ import javax.servlet.http.HttpSession; import com.cloud.utils.ReflectUtil; import org.apache.cloudstack.acl.APIAccessChecker; +import org.apache.cloudstack.acl.APILimitChecker; import org.apache.cloudstack.acl.ControlledEntity; import org.apache.cloudstack.api.*; import org.apache.cloudstack.api.command.user.account.ListAccountsCmd; @@ -141,6 +142,7 @@ public class ApiServer implements HttpRequestHandler { private static final Logger s_accessLogger = Logger.getLogger("apiserver." + ApiServer.class.getName()); public static boolean encodeApiResponse = false; + public static boolean apiThrottlingEnabled = true; public static String jsonContentType = "text/javascript"; private ApiDispatcher _dispatcher; @@ -148,6 +150,8 @@ public class ApiServer implements HttpRequestHandler { @Inject private DomainManager _domainMgr = null; @Inject private AsyncJobManager _asyncMgr = null; + @Inject(adapter = APILimitChecker.class) + protected Adapters _apiLimitCheckers; @Inject(adapter = APIAccessChecker.class) protected Adapters _apiAccessCheckers; @Inject(adapter = ApiDiscoveryService.class) @@ -217,6 +221,7 @@ public class ApiServer implements HttpRequestHandler { if (jsonType != null) { jsonContentType = jsonType; } + apiThrottlingEnabled = Boolean.valueOf(configDao.getValue(Config.ApiLimitEnabled.key())); if (apiPort != null) { ListenerThread listenerThread = new ListenerThread(this, apiPort); @@ -552,6 +557,14 @@ public class ApiServer implements HttpRequestHandler { // if userId not null, that mean that user is logged in if (userId != null) { User user = ApiDBUtils.findUserById(userId); + if (apiThrottlingEnabled){ + // go through each API limit checker + if (!isRequestAllowed(user)) { + //FIXME: more detailed message regarding when he/she can retry + s_logger.warn("The given user has reached his/her account api limit, please retry later"); + throw new ServerApiException(BaseCmd.API_LIMIT_EXCEED, "The given user has reached his/her account api limit"); + } + } if (!isCommandAvailable(user, commandName)) { s_logger.warn("The given command:" + commandName + " does not exist or it is not available for user"); throw new ServerApiException(BaseCmd.UNSUPPORTED_ACTION_ERROR, "The given command does not exist or it is not available for user"); @@ -791,6 +804,20 @@ public class ApiServer implements HttpRequestHandler { return true; } + private boolean isRequestAllowed(User user) { + Account account = ApiDBUtils.findAccountById(user.getAccountId()); + if ( _accountMgr.isRootAdmin(account.getType()) ){ + // no api throttling for root admin + return true; + } + for (APILimitChecker apiChecker : _apiLimitCheckers) { + // Fail the checking if any checker fails to verify + if (!apiChecker.isUnderLimit(account)) + return false; + } + return true; + } + private boolean isCommandAvailable(User user, String commandName) { for (APIAccessChecker apiChecker : _apiAccessCheckers) { // Fail the checking if any checker fails to verify diff --git a/server/src/com/cloud/configuration/Config.java b/server/src/com/cloud/configuration/Config.java index b91fbdd69bf..ae7651c846e 100755 --- a/server/src/com/cloud/configuration/Config.java +++ b/server/src/com/cloud/configuration/Config.java @@ -358,8 +358,12 @@ public enum Config { DetailBatchQuerySize("Advanced", ManagementServer.class, Integer.class, "detail.batch.query.size", "2000", "Default entity detail batch query size for listing", null), ConcurrentSnapshotsThresholdPerHost("Advanced", ManagementServer.class, Long.class, "concurrent.snapshots.threshold.perhost", - null, "Limits number of snapshots that can be handled by the host concurrently; default is NULL - unlimited", null); + null, "Limits number of snapshots that can be handled by the host concurrently; default is NULL - unlimited", null), + // API throttling + ApiLimitInterval("Advanced", ManagementServer.class, Long.class, "api.throttling.interval", "1", "The default time interval in seconds used to set account based api limit", null), + ApiLimitMax("Advanced", ManagementServer.class, Long.class, "api.throttling.max", "25", "The max number of API requests within api.throttling.interval duration", null), + ApiLimitEnabled("Advanced", ManagementServer.class, Boolean.class, "api.throttling.enabled", "true", "If true, api throttline feature is enabled", "true,false"); private final String _category; private final Class _componentClass; From ca578684b4295bd9056b4fd76a3962706f564a27 Mon Sep 17 00:00:00 2001 From: Hugo Trippaers Date: Thu, 10 Jan 2013 18:30:07 +0100 Subject: [PATCH 02/80] Summary: Add initial support for OpenVswitch to the KVM hypervisor Create OvsVifDriver to deal with openvswitch specifics for plugging intefaces Create a parameter to set the bridge type to use in LibvirtComputingResource. Create several functions to get bridge information from openvswitch Add a check to detect the libvirt version and throw an exception when the version is to low ( < 0.9.11 ) Fix classpath loading in Script.findScript to deal with missing path separators at the end. Add notification to the BridgeVifDriver that lswitch broadcast type is not supported. --- .../kvm/resource/BridgeVifDriver.java | 3 + .../resource/LibvirtComputingResource.java | 97 +++++++- .../hypervisor/kvm/resource/LibvirtVMDef.java | 25 ++ .../hypervisor/kvm/resource/OvsVifDriver.java | 213 ++++++++++++++++++ utils/src/com/cloud/utils/script/Script.java | 20 +- 5 files changed, 348 insertions(+), 10 deletions(-) create mode 100644 plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/BridgeVifDriver.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/BridgeVifDriver.java index e6f2f7f376a..031721e8a3d 100644 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/BridgeVifDriver.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/BridgeVifDriver.java @@ -85,6 +85,9 @@ public class BridgeVifDriver extends VifDriverBase { URI broadcastUri = nic.getBroadcastUri(); vlanId = broadcastUri.getHost(); } + else if (nic.getBroadcastType() == Networks.BroadcastDomainType.Lswitch) { + throw new InternalErrorException("Nicira NVP Logicalswitches are not supported by the BridgeVifDriver"); + } String trafficLabel = nic.getName(); if (nic.getType() == Networks.TrafficType.Guest) { if (nic.getBroadcastType() == Networks.BroadcastDomainType.Vlan diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java index b52e2d8a0b0..fade750c5f8 100755 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java @@ -362,10 +362,16 @@ public class LibvirtComputingResource extends ServerResourceBase implements private String _pingTestPath; private int _dom0MinMem; + + protected enum BridgeType { + NATIVE, OPENVSWITCH + } protected enum defineOps { UNDEFINE_VM, DEFINE_VM } + + protected BridgeType _bridgeType; private String getEndIpFromStartIp(String startIp, int numIps) { String[] tokens = startIp.split("[.]"); @@ -474,6 +480,14 @@ public class LibvirtComputingResource extends ServerResourceBase implements if (storageScriptsDir == null) { storageScriptsDir = getDefaultStorageScriptsDir(); } + + String bridgeType = (String) params.get("network.bridge.type"); + if (bridgeType == null) { + _bridgeType = BridgeType.NATIVE; + } + else { + _bridgeType = BridgeType.valueOf(bridgeType.toUpperCase()); + } params.put("domr.scripts.dir", domrScriptsDir); @@ -650,11 +664,19 @@ public class LibvirtComputingResource extends ServerResourceBase implements LibvirtConnection.initialize(_hypervisorURI); Connect conn = null; - try { - conn = LibvirtConnection.getConnection(); - } catch (LibvirtException e) { - throw new CloudRuntimeException(e.getMessage()); - } + try { + conn = LibvirtConnection.getConnection(); + + if (_bridgeType == BridgeType.OPENVSWITCH) { + if (conn.getLibVirVersion() < (9 * 1000 + 11)) { + throw new ConfigurationException( + "LibVirt version 0.9.11 required for openvswitch support, but version " + + conn.getLibVirVersion() + " detected"); + } + } + } catch (LibvirtException e) { + throw new CloudRuntimeException(e.getMessage()); + } /* Does node support HVM guest? If not, exit */ if (!IsHVMEnabled(conn)) { @@ -697,7 +719,15 @@ public class LibvirtComputingResource extends ServerResourceBase implements } } - getPifs(); + switch (_bridgeType) { + case NATIVE: + getPifs(); + break; + case OPENVSWITCH: + getOvsPifs(); + break; + } + if (_pifs.get("private") == null) { s_logger.debug("Failed to get private nic name"); throw new ConfigurationException("Failed to get private nic name"); @@ -796,6 +826,26 @@ public class LibvirtComputingResource extends ServerResourceBase implements } s_logger.debug("done looking for pifs, no more bridges"); } + + private void getOvsPifs() { + String cmdout = Script.runSimpleBashScript("ovs-vsctl list-br | sed '{:q;N;s/\\n/%/g;t q}'"); + s_logger.debug("cmdout was " + cmdout); + List bridges = Arrays.asList(cmdout.split("%")); + for (String bridge : bridges) { + s_logger.debug("looking for pif for bridge " + bridge); + //String pif = getOvsPif(bridge); + // Not really interested in the pif name at this point for ovs bridges + String pif = bridge; + if(_publicBridgeName != null && bridge.equals(_publicBridgeName)){ + _pifs.put("public", pif); + } + if (_guestBridgeName != null && bridge.equals(_guestBridgeName)) { + _pifs.put("private", pif); + } + _pifs.put(bridge, pif); + } + s_logger.debug("done looking for pifs, no more bridges"); + } private String getPif(String bridge) { String pif = Script.runSimpleBashScript("brctl show | grep " + bridge + " | awk '{print $4}'"); @@ -808,11 +858,29 @@ public class LibvirtComputingResource extends ServerResourceBase implements return pif; } + private String getOvsPif(String bridge) { + String pif = Script.runSimpleBashScript("ovs-vsctl list-ports " + bridge); + return pif; + } + private boolean checkNetwork(String networkName) { if (networkName == null) { return true; } + if (_bridgeType == BridgeType.OPENVSWITCH) { + return checkOvsNetwork(networkName); + } + else { + return checkBridgeNetwork(networkName); + } + } + + private boolean checkBridgeNetwork(String networkName) { + if (networkName == null) { + return true; + } + String name = Script.runSimpleBashScript("brctl show | grep " + networkName + " | awk '{print $4}'"); if (name == null) { @@ -821,6 +889,23 @@ public class LibvirtComputingResource extends ServerResourceBase implements return true; } } + + private boolean checkOvsNetwork(String networkName) { + s_logger.debug("Checking if network " + networkName + " exists as openvswitch bridge"); + if (networkName == null) { + return true; + } + + Script command = new Script("/bin/sh", _timeout); + command.add("-c"); + command.add("ovs-vsctl br-exists " + networkName); + String result = command.execute(null); + if ("Ok".equals(result)) { + return true; + } else { + return false; + } + } private String getVnetId(String vnetId) { return vnetId; diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtVMDef.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtVMDef.java index ba6c715e455..17f6eef0b8e 100644 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtVMDef.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtVMDef.java @@ -646,6 +646,8 @@ public class LibvirtVMDef { private String _ipAddr; private String _scriptPath; private nicModel _model; + private String _virtualPortType; + private String _virtualPortInterfaceId; public void defBridgeNet(String brName, String targetBrName, String macAddr, nicModel model) { @@ -695,6 +697,22 @@ public class LibvirtVMDef { public String getMacAddress() { return _macAddr; } + + public void setVirtualPortType(String virtualPortType) { + _virtualPortType = virtualPortType; + } + + public String getVirtualPortType() { + return _virtualPortType; + } + + public void setVirtualPortInterfaceId(String virtualPortInterfaceId) { + _virtualPortInterfaceId = virtualPortInterfaceId; + } + + public String getVirtualPortInterfaceId() { + return _virtualPortInterfaceId; + } @Override public String toString() { @@ -714,6 +732,13 @@ public class LibvirtVMDef { if (_model != null) { netBuilder.append("\n"); } + if (_virtualPortType != null) { + netBuilder.append("\n"); + if (_virtualPortInterfaceId != null) { + netBuilder.append("\n"); + } + netBuilder.append("\n"); + } netBuilder.append("\n"); return netBuilder.toString(); } diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java new file mode 100644 index 00000000000..6c3e4963ec5 --- /dev/null +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java @@ -0,0 +1,213 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package com.cloud.hypervisor.kvm.resource; + +import java.net.URI; +import java.util.Map; + +import javax.naming.ConfigurationException; + +import org.apache.log4j.Logger; +import org.libvirt.LibvirtException; + +import com.cloud.agent.api.to.NicTO; +import com.cloud.exception.InternalErrorException; +import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.InterfaceDef; +import com.cloud.network.Networks; +import com.cloud.utils.NumbersUtil; +import com.cloud.utils.net.NetUtils; +import com.cloud.utils.script.OutputInterpreter; +import com.cloud.utils.script.Script; + +public class OvsVifDriver extends VifDriverBase { + private static final Logger s_logger = Logger + .getLogger(BridgeVifDriver.class); + private int _timeout; + private String _modifyVlanPath; + + @Override + public void configure(Map params) throws ConfigurationException { + super.configure(params); + + String networkScriptsDir = (String) params.get("network.scripts.dir"); + if (networkScriptsDir == null) { + networkScriptsDir = "scripts/vm/network/vnet"; + } + + String value = (String) params.get("scripts.timeout"); + _timeout = NumbersUtil.parseInt(value, 30 * 60) * 1000; + + _modifyVlanPath = Script.findScript(networkScriptsDir, "modifyvlan.sh"); + if (_modifyVlanPath == null) { + throw new ConfigurationException("Unable to find modifyvlan.sh"); + } + + createControlNetwork(_bridges.get("linklocal")); + } + + @Override + public InterfaceDef plug(NicTO nic, String guestOsType) + throws InternalErrorException, LibvirtException { + s_logger.debug("plugging nic=" + nic); + + LibvirtVMDef.InterfaceDef intf = new LibvirtVMDef.InterfaceDef(); + intf.setVirtualPortType("openvswitch"); + + String vlanId = null; + String logicalSwitchUuid = null; + if (nic.getBroadcastType() == Networks.BroadcastDomainType.Vlan) { + URI broadcastUri = nic.getBroadcastUri(); + vlanId = broadcastUri.getHost(); + } + else if (nic.getBroadcastType() == Networks.BroadcastDomainType.Lswitch) { + logicalSwitchUuid = nic.getBroadcastUri().getSchemeSpecificPart(); + } + String trafficLabel = nic.getName(); + if (nic.getType() == Networks.TrafficType.Guest) { + if (nic.getBroadcastType() == Networks.BroadcastDomainType.Vlan + && !vlanId.equalsIgnoreCase("untagged")) { + if(trafficLabel != null && !trafficLabel.isEmpty()) { + s_logger.debug("creating a vlan dev and bridge for guest traffic per traffic label " + trafficLabel); + String brName = createVlanBr(vlanId, _pifs.get(trafficLabel)); + intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType)); + } else { + String brName = createVlanBr(vlanId, _pifs.get("private")); + intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType)); + } + } else if (nic.getBroadcastType() == Networks.BroadcastDomainType.Lswitch) { + s_logger.debug("nic " + nic + " needs to be connected to LogicalSwitch " + logicalSwitchUuid); + intf.setVirtualPortInterfaceId(nic.getUuid()); + String brName = (trafficLabel != null && !trafficLabel.isEmpty()) ? _pifs.get(trafficLabel) : _pifs.get("private"); + intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType)); + } + else { + intf.defBridgeNet(_bridges.get("guest"), null, nic.getMac(), getGuestNicModel(guestOsType)); + } + } else if (nic.getType() == Networks.TrafficType.Control) { + /* Make sure the network is still there */ + createControlNetwork(_bridges.get("linklocal")); + intf.defBridgeNet(_bridges.get("linklocal"), null, nic.getMac(), getGuestNicModel(guestOsType)); + } else if (nic.getType() == Networks.TrafficType.Public) { + if (nic.getBroadcastType() == Networks.BroadcastDomainType.Vlan + && !vlanId.equalsIgnoreCase("untagged")) { + if(trafficLabel != null && !trafficLabel.isEmpty()){ + s_logger.debug("creating a vlan dev and bridge for public traffic per traffic label " + trafficLabel); + String brName = createVlanBr(vlanId, _pifs.get(trafficLabel)); + intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType)); + } else { + String brName = createVlanBr(vlanId, _pifs.get("public")); + intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType)); + } + } else { + intf.defBridgeNet(_bridges.get("public"), null, nic.getMac(), getGuestNicModel(guestOsType)); + } + } else if (nic.getType() == Networks.TrafficType.Management) { + intf.defBridgeNet(_bridges.get("private"), null, nic.getMac(), getGuestNicModel(guestOsType)); + } else if (nic.getType() == Networks.TrafficType.Storage) { + String storageBrName = nic.getName() == null ? _bridges.get("private") + : nic.getName(); + intf.defBridgeNet(storageBrName, null, nic.getMac(), getGuestNicModel(guestOsType)); + } + return intf; + } + + @Override + public void unplug(InterfaceDef iface) { + // Libvirt apparently takes care of this, see BridgeVifDriver unplug + } + + private String setVnetBrName(String pifName, String vnetId) { + String brName = "br" + pifName + "-"+ vnetId; + String oldStyleBrName = "cloudVirBr" + vnetId; + + if (isBridgeExists(oldStyleBrName)) { + s_logger.info("Using old style bridge name for vlan " + vnetId + " because existing bridge " + oldStyleBrName + " was found"); + brName = oldStyleBrName; + } + + return brName; + } + + private String createVlanBr(String vlanId, String nic) + throws InternalErrorException { + String brName = setVnetBrName(nic, vlanId); + createVnet(vlanId, nic, brName); + return brName; + } + + private void createVnet(String vnetId, String pif, String brName) + throws InternalErrorException { + final Script command = new Script(_modifyVlanPath, _timeout, s_logger); + command.add("-v", vnetId); + command.add("-p", pif); + command.add("-b", brName); + command.add("-o", "add"); + + final String result = command.execute(); + if (result != null) { + throw new InternalErrorException("Failed to create vnet " + vnetId + + ": " + result); + } + } + + private void deleteExitingLinkLocalRoutTable(String linkLocalBr) { + Script command = new Script("/bin/bash", _timeout); + command.add("-c"); + command.add("ip route | grep " + NetUtils.getLinkLocalCIDR()); + OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser(); + String result = command.execute(parser); + boolean foundLinkLocalBr = false; + if (result == null && parser.getLines() != null) { + String[] lines = parser.getLines().split("\\n"); + for (String line : lines) { + String[] tokens = line.split(" "); + if (!tokens[2].equalsIgnoreCase(linkLocalBr)) { + Script.runSimpleBashScript("ip route del " + NetUtils.getLinkLocalCIDR()); + } else { + foundLinkLocalBr = true; + } + } + } + if (!foundLinkLocalBr) { + Script.runSimpleBashScript("ifconfig " + linkLocalBr + " 169.254.0.1;" + "ip route add " + + NetUtils.getLinkLocalCIDR() + " dev " + linkLocalBr + " src " + NetUtils.getLinkLocalGateway()); + } + } + + private void createControlNetwork(String privBrName) { + deleteExitingLinkLocalRoutTable(privBrName); + if (!isBridgeExists(privBrName)) { + Script.runSimpleBashScript("ovs-vsctl add-br " + privBrName + "; ifconfig " + privBrName + " up; ifconfig " + + privBrName + " 169.254.0.1", _timeout); + } + + } + + private boolean isBridgeExists(String bridgeName) { + Script command = new Script("/bin/sh", _timeout); + command.add("-c"); + command.add("ovs-vsctl br-exists " + bridgeName); + String result = command.execute(null); + if ("Ok".equals(result)) { + return true; + } else { + return false; + } + } +} diff --git a/utils/src/com/cloud/utils/script/Script.java b/utils/src/com/cloud/utils/script/Script.java index 1444f83f425..d82d1d00957 100755 --- a/utils/src/com/cloud/utils/script/Script.java +++ b/utils/src/com/cloud/utils/script/Script.java @@ -195,7 +195,7 @@ public class Script implements Callable { } Task task = null; - if (interpreter.drain()) { + if (interpreter != null && interpreter.drain()) { task = new Task(interpreter, ir); s_executors.execute(task); } @@ -204,8 +204,13 @@ public class Script implements Callable { try { if (_process.waitFor() == 0) { _logger.debug("Execution is successful."); - - return interpreter.drain() ? task.getResult() : interpreter.interpret(ir); + if (interpreter != null) { + return interpreter.drain() ? task.getResult() : interpreter.interpret(ir); + } + else { + // null return is ok apparently + return (_process.exitValue() == 0) ? "Ok" : "Failed, exit code " + _process.exitValue(); + } } else { break; } @@ -239,7 +244,14 @@ public class Script implements Callable { BufferedReader reader = new BufferedReader(new InputStreamReader(_process.getInputStream()), 128); - String error = interpreter.processError(reader); + String error; + if (interpreter != null) { + error = interpreter.processError(reader); + } + else { + error = "Non zero exit code : " + _process.exitValue(); + } + if (_logger.isDebugEnabled()) { _logger.debug(error); } From d900345a20acab8cc7f6759425b27d1b28d935f7 Mon Sep 17 00:00:00 2001 From: Min Chen Date: Thu, 10 Jan 2013 17:47:48 -0800 Subject: [PATCH 03/80] Ehcache implementation of APi Rate limit plugin. --- .../api-limit_commands.properties.in | 24 ++ plugins/api/rate-limit/pom.xml | 29 +++ .../user/ratelimit/GetApiLimitCmd.java | 87 ++++++++ .../admin/ratelimit/ResetApiLimitCmd.java | 94 ++++++++ .../api/response/ApiLimitResponse.java | 82 +++++++ .../ratelimit/ApiRateLimitService.java | 40 ++++ .../ratelimit/ApiRateLimitServiceImpl.java | 172 ++++++++++++++ .../ratelimit/EhcacheLimitStore.java | 99 +++++++++ .../cloudstack/ratelimit/LimitStore.java | 51 +++++ .../cloudstack/ratelimit/StoreEntry.java | 33 +++ .../cloudstack/ratelimit/StoreEntryImpl.java | 64 ++++++ .../ratelimit/ApiRateLimitTest.java | 209 ++++++++++++++++++ plugins/pom.xml | 1 + 13 files changed, 985 insertions(+) create mode 100644 client/tomcatconf/api-limit_commands.properties.in create mode 100644 plugins/api/rate-limit/pom.xml create mode 100644 plugins/api/rate-limit/src/org/apache/cloudstack/api/command/user/ratelimit/GetApiLimitCmd.java create mode 100644 plugins/api/rate-limit/src/org/apache/cloudstack/api/commands/admin/ratelimit/ResetApiLimitCmd.java create mode 100644 plugins/api/rate-limit/src/org/apache/cloudstack/api/response/ApiLimitResponse.java create mode 100644 plugins/api/rate-limit/src/org/apache/cloudstack/ratelimit/ApiRateLimitService.java create mode 100644 plugins/api/rate-limit/src/org/apache/cloudstack/ratelimit/ApiRateLimitServiceImpl.java create mode 100644 plugins/api/rate-limit/src/org/apache/cloudstack/ratelimit/EhcacheLimitStore.java create mode 100644 plugins/api/rate-limit/src/org/apache/cloudstack/ratelimit/LimitStore.java create mode 100644 plugins/api/rate-limit/src/org/apache/cloudstack/ratelimit/StoreEntry.java create mode 100644 plugins/api/rate-limit/src/org/apache/cloudstack/ratelimit/StoreEntryImpl.java create mode 100644 plugins/api/rate-limit/test/org/apache/cloudstack/ratelimit/ApiRateLimitTest.java diff --git a/client/tomcatconf/api-limit_commands.properties.in b/client/tomcatconf/api-limit_commands.properties.in new file mode 100644 index 00000000000..fcb963ac867 --- /dev/null +++ b/client/tomcatconf/api-limit_commands.properties.in @@ -0,0 +1,24 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +# bitmap of permissions at the end of each classname, 1 = ADMIN, 2 = +# RESOURCE_DOMAIN_ADMIN, 4 = DOMAIN_ADMIN, 8 = USER +# Please standardize naming conventions to camel-case (even for acronyms). + +# CloudStack API Rate Limit service command +getApiLimit=15 +resetApiLimit=1 diff --git a/plugins/api/rate-limit/pom.xml b/plugins/api/rate-limit/pom.xml new file mode 100644 index 00000000000..416c901cf8a --- /dev/null +++ b/plugins/api/rate-limit/pom.xml @@ -0,0 +1,29 @@ + + + 4.0.0 + cloud-plugin-api-limit-account-based + Apache CloudStack Plugin - API Rate Limit + + org.apache.cloudstack + cloudstack-plugins + 4.1.0-SNAPSHOT + ../../pom.xml + + diff --git a/plugins/api/rate-limit/src/org/apache/cloudstack/api/command/user/ratelimit/GetApiLimitCmd.java b/plugins/api/rate-limit/src/org/apache/cloudstack/api/command/user/ratelimit/GetApiLimitCmd.java new file mode 100644 index 00000000000..3f9e4eb4503 --- /dev/null +++ b/plugins/api/rate-limit/src/org/apache/cloudstack/api/command/user/ratelimit/GetApiLimitCmd.java @@ -0,0 +1,87 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.api.command.user.ratelimit; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.cloudstack.api.ACL; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.PlugService; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.BaseCmd.CommandType; +import org.apache.cloudstack.api.commands.admin.ratelimit.ResetApiLimitCmd; +import org.apache.cloudstack.api.response.AccountResponse; +import org.apache.cloudstack.api.response.ApiLimitResponse; +import org.apache.cloudstack.api.response.PhysicalNetworkResponse; +import org.apache.log4j.Logger; + +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.ratelimit.ApiRateLimitService; +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.exception.ResourceAllocationException; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.user.Account; +import com.cloud.user.UserContext; +import com.cloud.utils.exception.CloudRuntimeException; + +@APICommand(name = "getApiLimit", responseObject=ApiLimitResponse.class, description="Get API limit count for the caller") +public class GetApiLimitCmd extends BaseListCmd { + private static final Logger s_logger = Logger.getLogger(GetApiLimitCmd.class.getName()); + + private static final String s_name = "getapilimitresponse"; + + @PlugService + ApiRateLimitService _apiLimitService; + + + + + ///////////////////////////////////////////////////// + /////////////// API Implementation/////////////////// + ///////////////////////////////////////////////////// + + @Override + public String getCommandName() { + return s_name; + } + + @Override + public long getEntityOwnerId() { + Account account = UserContext.current().getCaller(); + if (account != null) { + return account.getId(); + } + + return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked + } + + @Override + public void execute(){ + ApiLimitResponse response = _apiLimitService.searchApiLimit(this); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } +} + + diff --git a/plugins/api/rate-limit/src/org/apache/cloudstack/api/commands/admin/ratelimit/ResetApiLimitCmd.java b/plugins/api/rate-limit/src/org/apache/cloudstack/api/commands/admin/ratelimit/ResetApiLimitCmd.java new file mode 100644 index 00000000000..8029ab3707a --- /dev/null +++ b/plugins/api/rate-limit/src/org/apache/cloudstack/api/commands/admin/ratelimit/ResetApiLimitCmd.java @@ -0,0 +1,94 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.api.commands.admin.ratelimit; + +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.AccountResponse; +import org.apache.cloudstack.api.response.ApiLimitResponse; +import org.apache.cloudstack.api.response.SuccessResponse; +import org.apache.log4j.Logger; + +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.ratelimit.ApiRateLimitService; + +import com.cloud.user.Account; +import com.cloud.user.UserContext; + +@APICommand(name = "resetApiLimit", responseObject=ApiLimitResponse.class, description="Reset api count") +public class ResetApiLimitCmd extends BaseCmd { + private static final Logger s_logger = Logger.getLogger(ResetApiLimitCmd.class.getName()); + + private static final String s_name = "resetapilimitresponse"; + + @PlugService + ApiRateLimitService _apiLimitService; + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @ACL + @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.UUID, entityType=AccountResponse.class, + description="the ID of the acount whose limit to be reset") + private Long accountId; + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + + public Long getAccountId() { + return accountId; + } + + + public void setAccountId(Long accountId) { + this.accountId = accountId; + } + + + ///////////////////////////////////////////////////// + /////////////// API Implementation/////////////////// + ///////////////////////////////////////////////////// + + + @Override + public String getCommandName() { + return s_name; + } + + @Override + public long getEntityOwnerId() { + Account account = UserContext.current().getCaller(); + if (account != null) { + return account.getId(); + } + + return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked + } + + @Override + public void execute(){ + boolean result = _apiLimitService.resetApiLimit(this); + if (result) { + SuccessResponse response = new SuccessResponse(getCommandName()); + this.setResponseObject(response); + } else { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to reset api limit counter"); + } + } +} diff --git a/plugins/api/rate-limit/src/org/apache/cloudstack/api/response/ApiLimitResponse.java b/plugins/api/rate-limit/src/org/apache/cloudstack/api/response/ApiLimitResponse.java new file mode 100644 index 00000000000..245e8f15d8a --- /dev/null +++ b/plugins/api/rate-limit/src/org/apache/cloudstack/api/response/ApiLimitResponse.java @@ -0,0 +1,82 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.api.response; + +import org.apache.cloudstack.api.ApiConstants; +import com.cloud.serializer.Param; +import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; + + +public class ApiLimitResponse extends BaseResponse { + @SerializedName(ApiConstants.ACCOUNT_ID) @Param(description="the account uuid of the api remaining count") + private String accountId; + + @SerializedName(ApiConstants.ACCOUNT) @Param(description="the account name of the api remaining count") + private String accountName; + + @SerializedName("apiIssued") @Param(description="number of api already issued") + private int apiIssued; + + @SerializedName("apiAllowed") @Param(description="currently allowed number of apis") + private int apiAllowed; + + @SerializedName("expireAfter") @Param(description="seconds left to reset counters") + private long expireAfter; + + public void setAccountId(String accountId) { + this.accountId = accountId; + } + + public void setAccountName(String accountName) { + this.accountName = accountName; + } + + public void setApiIssued(int apiIssued) { + this.apiIssued = apiIssued; + } + + public void setApiAllowed(int apiAllowed) { + this.apiAllowed = apiAllowed; + } + + public void setExpireAfter(long duration) { + this.expireAfter = duration; + } + + public String getAccountId() { + return accountId; + } + + public String getAccountName() { + return accountName; + } + + public int getApiIssued() { + return apiIssued; + } + + public int getApiAllowed() { + return apiAllowed; + } + + public long getExpireAfter() { + return expireAfter; + } + + +} diff --git a/plugins/api/rate-limit/src/org/apache/cloudstack/ratelimit/ApiRateLimitService.java b/plugins/api/rate-limit/src/org/apache/cloudstack/ratelimit/ApiRateLimitService.java new file mode 100644 index 00000000000..e7ba9d45fc3 --- /dev/null +++ b/plugins/api/rate-limit/src/org/apache/cloudstack/ratelimit/ApiRateLimitService.java @@ -0,0 +1,40 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.ratelimit; + +import org.apache.cloudstack.api.command.user.ratelimit.GetApiLimitCmd; +import org.apache.cloudstack.api.commands.admin.ratelimit.ResetApiLimitCmd; +import org.apache.cloudstack.api.response.ApiLimitResponse; +import org.apache.cloudstack.api.response.ListResponse; + +import com.cloud.utils.component.PluggableService; + +/** + * Provide API rate limit service + * @author minc + * + */ +public interface ApiRateLimitService extends PluggableService{ + + public ApiLimitResponse searchApiLimit(GetApiLimitCmd cmd); + + public boolean resetApiLimit(ResetApiLimitCmd cmd); + + public void setTimeToLive(int timeToLive); + + public void setMaxAllowed(int max); +} diff --git a/plugins/api/rate-limit/src/org/apache/cloudstack/ratelimit/ApiRateLimitServiceImpl.java b/plugins/api/rate-limit/src/org/apache/cloudstack/ratelimit/ApiRateLimitServiceImpl.java new file mode 100644 index 00000000000..e14f65d383e --- /dev/null +++ b/plugins/api/rate-limit/src/org/apache/cloudstack/ratelimit/ApiRateLimitServiceImpl.java @@ -0,0 +1,172 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.ratelimit; + +import java.util.Map; +import javax.ejb.Local; +import javax.naming.ConfigurationException; + +import net.sf.ehcache.Cache; +import net.sf.ehcache.CacheManager; + +import org.apache.log4j.Logger; + +import com.cloud.configuration.Config; +import com.cloud.configuration.dao.ConfigurationDao; +import org.apache.cloudstack.acl.APILimitChecker; +import org.apache.cloudstack.api.command.user.ratelimit.GetApiLimitCmd; +import org.apache.cloudstack.api.commands.admin.ratelimit.ResetApiLimitCmd; +import org.apache.cloudstack.api.response.ApiLimitResponse; +import com.cloud.network.element.NetworkElement; +import com.cloud.user.Account; +import com.cloud.user.UserContext; +import com.cloud.utils.component.AdapterBase; +import com.cloud.utils.component.Inject; + +@Local(value = NetworkElement.class) +public class ApiRateLimitServiceImpl extends AdapterBase implements APILimitChecker, ApiRateLimitService { + private static final Logger s_logger = Logger.getLogger(ApiRateLimitServiceImpl.class); + + /** + * Fixed time duration where api rate limit is set, in seconds + */ + private int timeToLive = 1; + + /** + * Max number of api requests during timeToLive duration. + */ + private int maxAllowed = 30; + + @Inject + ConfigurationDao _configDao; + + private LimitStore _store; + + + @Override + public boolean configure(String name, Map params) throws ConfigurationException { + super.configure(name, params); + // get global configured duration and max values + String duration = _configDao.getValue(Config.ApiLimitInterval.key()); + if (duration != null ){ + timeToLive = Integer.parseInt(duration); + } + String maxReqs = _configDao.getValue(Config.ApiLimitMax.key()); + if ( maxReqs != null){ + maxAllowed = Integer.parseInt(maxReqs); + } + // create limit store + EhcacheLimitStore cacheStore = new EhcacheLimitStore(); + int maxElements = 10000; //TODO: what should be the proper number here? + CacheManager cm = CacheManager.create(); + Cache cache = new Cache("api-limit-cache", maxElements, true, false, timeToLive, timeToLive); + cm.addCache(cache); + s_logger.info("Limit Cache created: " + cache.toString()); + cacheStore.setCache(cache); + _store = cacheStore; + + return true; + + } + + + + @Override + public ApiLimitResponse searchApiLimit(GetApiLimitCmd cmd) { + Account caller = UserContext.current().getCaller(); + ApiLimitResponse response = new ApiLimitResponse(); + response.setAccountId(caller.getUuid()); + response.setAccountName(caller.getAccountName()); + StoreEntry entry = _store.get(caller.getId()); + if (entry == null) { + + /* Populate the entry, thus unlocking any underlying mutex */ + entry = _store.create(caller.getId(), timeToLive); + response.setApiIssued(0); + response.setApiAllowed(maxAllowed); + response.setExpireAfter(timeToLive); + } + else{ + response.setApiIssued(entry.getCounter()); + response.setApiAllowed(maxAllowed - entry.getCounter()); + response.setExpireAfter(entry.getExpireDuration()); + } + + return response; + } + + + + @Override + public boolean resetApiLimit(ResetApiLimitCmd cmd) { + if ( cmd.getAccountId() != null ){ + _store.create(cmd.getAccountId(), timeToLive); + } + else{ + _store.resetCounters(); + } + return true; + } + + + + @Override + public boolean isUnderLimit(Account account) { + + Long accountId = account.getId(); + StoreEntry entry = _store.get(accountId); + + if (entry == null) { + + /* Populate the entry, thus unlocking any underlying mutex */ + entry = _store.create(accountId, timeToLive); + } + + /* Increment the client count and see whether we have hit the maximum allowed clients yet. */ + int current = entry.incrementAndGet(); + + if (current <= maxAllowed) { + return true; + } else { + return false; + } + } + + + + @Override + public String[] getPropertiesFiles() { + return new String[] { "api-limit_commands.properties" }; + } + + + + @Override + public void setTimeToLive(int timeToLive) { + this.timeToLive = timeToLive; + } + + + + @Override + public void setMaxAllowed(int max) { + this.maxAllowed = max; + + } + + +} diff --git a/plugins/api/rate-limit/src/org/apache/cloudstack/ratelimit/EhcacheLimitStore.java b/plugins/api/rate-limit/src/org/apache/cloudstack/ratelimit/EhcacheLimitStore.java new file mode 100644 index 00000000000..659cf81b0e6 --- /dev/null +++ b/plugins/api/rate-limit/src/org/apache/cloudstack/ratelimit/EhcacheLimitStore.java @@ -0,0 +1,99 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.ratelimit; + +import net.sf.ehcache.Ehcache; +import net.sf.ehcache.Element; +import net.sf.ehcache.constructs.blocking.BlockingCache; +import net.sf.ehcache.constructs.blocking.LockTimeoutException; + +/** + * A Limit store implementation using Ehcache. + * @author minc + * + */ +public class EhcacheLimitStore implements LimitStore { + + + private BlockingCache cache; + + + public void setCache(Ehcache cache) { + BlockingCache ref; + + if (!(cache instanceof BlockingCache)) { + ref = new BlockingCache(cache); + cache.getCacheManager().replaceCacheWithDecoratedCache(cache, new BlockingCache(cache)); + } else { + ref = (BlockingCache) cache; + } + + this.cache = ref; + } + + + @Override + public StoreEntry create(Long key, int timeToLive) { + StoreEntryImpl result = new StoreEntryImpl(timeToLive); + Element element = new Element(key, result); + element.setTimeToLive(timeToLive); + cache.put(element); + return result; + } + + @Override + public StoreEntry get(Long key) { + + Element entry = null; + + try { + + /* This may block. */ + entry = cache.get(key); + } catch (LockTimeoutException e) { + throw new RuntimeException(); + } catch (RuntimeException e) { + + /* Release the lock that may have been acquired. */ + cache.put(new Element(key, null)); + } + + StoreEntry result = null; + + if (entry != null) { + + /* + * We don't need to check isExpired() on the result, since ehcache takes care of expiring entries for us. + * c.f. the get(Key) implementation in this class. + */ + result = (StoreEntry) entry.getObjectValue(); + } + + return result; + } + + + + @Override + public void resetCounters() { + cache.removeAll(); + + } + + + +} diff --git a/plugins/api/rate-limit/src/org/apache/cloudstack/ratelimit/LimitStore.java b/plugins/api/rate-limit/src/org/apache/cloudstack/ratelimit/LimitStore.java new file mode 100644 index 00000000000..a5e086b3029 --- /dev/null +++ b/plugins/api/rate-limit/src/org/apache/cloudstack/ratelimit/LimitStore.java @@ -0,0 +1,51 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.ratelimit; + +import com.cloud.user.Account; + +/** + * Interface to define how an api limit store should work. + * @author minc + * + */ +public interface LimitStore { + + /** + * Returns a store entry for the given account. A value of null means that there is no + * such entry and the calling client must call create to avoid + * other clients potentially being blocked without any hope of progressing. A non-null + * entry means that it has not expired and can be used to determine whether the current client should be allowed to + * proceed with the rate-limited action or not. + * + */ + StoreEntry get(Long account); + + /** + * Creates a new store entry + * + * @param account + * the user account, key to the store + * @param timeToLiveInSecs + * the positive time-to-live in seconds + * @return a non-null entry + */ + StoreEntry create(Long account, int timeToLiveInSecs); + + void resetCounters(); + +} diff --git a/plugins/api/rate-limit/src/org/apache/cloudstack/ratelimit/StoreEntry.java b/plugins/api/rate-limit/src/org/apache/cloudstack/ratelimit/StoreEntry.java new file mode 100644 index 00000000000..76e8a2d9281 --- /dev/null +++ b/plugins/api/rate-limit/src/org/apache/cloudstack/ratelimit/StoreEntry.java @@ -0,0 +1,33 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.ratelimit; + +/** + * Interface for each entry in LimitStore. + * @author minc + * + */ +public interface StoreEntry { + + int getCounter(); + + int incrementAndGet(); + + boolean isExpired(); + + long getExpireDuration(); /* seconds to reset counter */ +} diff --git a/plugins/api/rate-limit/src/org/apache/cloudstack/ratelimit/StoreEntryImpl.java b/plugins/api/rate-limit/src/org/apache/cloudstack/ratelimit/StoreEntryImpl.java new file mode 100644 index 00000000000..40965d9da8e --- /dev/null +++ b/plugins/api/rate-limit/src/org/apache/cloudstack/ratelimit/StoreEntryImpl.java @@ -0,0 +1,64 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.ratelimit; + +import java.util.concurrent.atomic.AtomicInteger; + +/** + * Implementation of limit store entry. + * @author minc + * + */ +public class StoreEntryImpl implements StoreEntry { + + private final long expiry; + + private final AtomicInteger counter; + + StoreEntryImpl(int timeToLive) { + this.expiry = System.currentTimeMillis() + timeToLive * 1000; + this.counter = new AtomicInteger(0); + } + + + @Override + public boolean isExpired() { + return System.currentTimeMillis() > expiry; + } + + + + @Override + public long getExpireDuration() { + if ( isExpired() ) + return 0; // already expired + else { + return (expiry - System.currentTimeMillis()) * 1000; + } + } + + + @Override + public int incrementAndGet() { + return this.counter.incrementAndGet(); + } + + @Override + public int getCounter(){ + return this.counter.get(); + } +} diff --git a/plugins/api/rate-limit/test/org/apache/cloudstack/ratelimit/ApiRateLimitTest.java b/plugins/api/rate-limit/test/org/apache/cloudstack/ratelimit/ApiRateLimitTest.java new file mode 100644 index 00000000000..0e2080ab2f1 --- /dev/null +++ b/plugins/api/rate-limit/test/org/apache/cloudstack/ratelimit/ApiRateLimitTest.java @@ -0,0 +1,209 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.ratelimit; + +import java.util.Collections; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import javax.naming.ConfigurationException; + +import org.apache.cloudstack.api.command.user.ratelimit.GetApiLimitCmd; +import org.apache.cloudstack.api.commands.admin.ratelimit.ResetApiLimitCmd; +import org.apache.cloudstack.api.response.ApiLimitResponse; +import org.apache.cloudstack.ratelimit.ApiRateLimitServiceImpl; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import com.cloud.configuration.Config; +import com.cloud.configuration.dao.ConfigurationDao; +import com.cloud.user.Account; +import com.cloud.user.AccountVO; +import com.cloud.user.UserContext; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; + +public class ApiRateLimitTest { + + static ApiRateLimitServiceImpl _limitService = new ApiRateLimitServiceImpl(); + static ConfigurationDao _configDao = mock(ConfigurationDao.class); + private static long acctIdSeq = 0L; + + @BeforeClass + public static void setUp() throws ConfigurationException { + _limitService._configDao = _configDao; + + // No global configuration set, will set in each test case + when(_configDao.getValue(Config.ApiLimitInterval.key())).thenReturn(null); + when(_configDao.getValue(Config.ApiLimitMax.key())).thenReturn(null); + + _limitService.configure("ApiRateLimitTest", Collections. emptyMap()); + } + + + private Account createFakeAccount(){ + return new AccountVO(acctIdSeq++); + } + + @Test + public void sequentialApiAccess() { + int allowedRequests = 1; + _limitService.setMaxAllowed(allowedRequests); + _limitService.setTimeToLive(1); + + Account key = createFakeAccount(); + assertTrue("Allow for the first request", _limitService.isUnderLimit(key)); + + assertFalse("Second request should be blocked, since we assume that the two api " + + " accesses take less than a second to perform", _limitService.isUnderLimit(key)); + } + + @Test + public void canDoReasonableNumberOfApiAccessPerSecond() throws Exception { + int allowedRequests = 50000; + _limitService.setMaxAllowed(allowedRequests); + _limitService.setTimeToLive(1); + + Account key = createFakeAccount(); + + for (int i = 0; i < allowedRequests; i++) { + assertTrue("We should allow " + allowedRequests + " requests per second", _limitService.isUnderLimit(key)); + } + + + assertFalse("We should block >" + allowedRequests + " requests per second", _limitService.isUnderLimit(key)); + } + + @Test + public void multipleClientsCanAccessWithoutBlocking() throws Exception { + int allowedRequests = 200; + _limitService.setMaxAllowed(allowedRequests); + _limitService.setTimeToLive(1); + + + final Account key = createFakeAccount(); + + int clientCount = allowedRequests; + Runnable[] clients = new Runnable[clientCount]; + final boolean[] isUsable = new boolean[clientCount]; + + final CountDownLatch startGate = new CountDownLatch(1); + + final CountDownLatch endGate = new CountDownLatch(clientCount); + + + for (int i = 0; i < isUsable.length; ++i) { + final int j = i; + clients[j] = new Runnable() { + + /** + * {@inheritDoc} + */ + @Override + public void run() { + try { + startGate.await(); + + isUsable[j] = _limitService.isUnderLimit(key); + + } catch (InterruptedException e) { + e.printStackTrace(); + } finally { + endGate.countDown(); + } + } + }; + } + + ExecutorService executor = Executors.newFixedThreadPool(clientCount); + + for (Runnable runnable : clients) { + executor.execute(runnable); + } + + startGate.countDown(); + + endGate.await(); + + for (boolean b : isUsable) { + assertTrue("Concurrent client request should be allowed within limit", b); + } + } + + @Test + public void expiryOfCounterIsSupported() throws Exception { + int allowedRequests = 1; + _limitService.setMaxAllowed(allowedRequests); + _limitService.setTimeToLive(1); + + Account key = this.createFakeAccount(); + + assertTrue("The first request should be allowed", _limitService.isUnderLimit(key)); + + // Allow the token to expire + Thread.sleep(1001); + + assertTrue("Another request after interval should be allowed as well", _limitService.isUnderLimit(key)); + } + + @Test + public void verifyResetCounters() throws Exception { + int allowedRequests = 1; + _limitService.setMaxAllowed(allowedRequests); + _limitService.setTimeToLive(1); + + Account key = this.createFakeAccount(); + + assertTrue("The first request should be allowed", _limitService.isUnderLimit(key)); + + assertFalse("Another request should be blocked", _limitService.isUnderLimit(key)); + + ResetApiLimitCmd cmd = new ResetApiLimitCmd(); + cmd.setAccountId(key.getId()); + + _limitService.resetApiLimit(cmd); + + assertTrue("Another request should be allowed after reset counter", _limitService.isUnderLimit(key)); + } + + /* Disable this since I cannot mock Static method UserContext.current() + @Test + public void verifySearchCounter() throws Exception { + int allowedRequests = 10; + _limitService.setMaxAllowed(allowedRequests); + _limitService.setTimeToLive(1); + + Account key = this.createFakeAccount(); + + for ( int i = 0; i < 5; i++ ){ + assertTrue("Issued 5 requests", _limitService.isUnderLimit(key)); + } + + GetApiLimitCmd cmd = new GetApiLimitCmd(); + UserContext ctx = mock(UserContext.class); + when(UserContext.current().getCaller()).thenReturn(key); + ApiLimitResponse response = _limitService.searchApiLimit(cmd); + assertEquals("apiIssued is incorrect", 5, response.getApiIssued()); + assertEquals("apiAllowed is incorrect", 5, response.getApiAllowed()); + assertTrue("expiredAfter is incorrect", response.getExpireAfter() < 1); + + } + */ +} diff --git a/plugins/pom.xml b/plugins/pom.xml index a42ae2967b1..7bb60a990fb 100644 --- a/plugins/pom.xml +++ b/plugins/pom.xml @@ -32,6 +32,7 @@ test + api/rate-limit api/discovery acl/static-role-based deployment-planners/user-concentrated-pod From 9adf2771825db8b8e102844db6ad638351e0b33e Mon Sep 17 00:00:00 2001 From: Hugo Trippaers Date: Fri, 11 Jan 2013 17:04:32 +0100 Subject: [PATCH 04/80] Summary: Add vlan configuration to the network inteface definition Add xml piece for defining vlans Set vlan tag in the libvirt definition for the network inteface --- .../hypervisor/kvm/resource/LibvirtVMDef.java | 14 ++++++- .../hypervisor/kvm/resource/OvsVifDriver.java | 38 ++++--------------- 2 files changed, 21 insertions(+), 31 deletions(-) diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtVMDef.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtVMDef.java index 17f6eef0b8e..df277780aa3 100644 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtVMDef.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtVMDef.java @@ -648,6 +648,7 @@ public class LibvirtVMDef { private nicModel _model; private String _virtualPortType; private String _virtualPortInterfaceId; + private int _vlanTag = -1; public void defBridgeNet(String brName, String targetBrName, String macAddr, nicModel model) { @@ -713,7 +714,15 @@ public class LibvirtVMDef { public String getVirtualPortInterfaceId() { return _virtualPortInterfaceId; } - + + public void setVlanTag(int vlanTag) { + _vlanTag = vlanTag; + } + + public int getVlanTag() { + return _vlanTag; + } + @Override public String toString() { StringBuilder netBuilder = new StringBuilder(); @@ -739,6 +748,9 @@ public class LibvirtVMDef { } netBuilder.append("\n"); } + if (_vlanTag != -1) { + netBuilder.append("\n\n"); + } netBuilder.append("\n"); return netBuilder.toString(); } diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java index 6c3e4963ec5..52fc29e5387 100644 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java @@ -84,11 +84,11 @@ public class OvsVifDriver extends VifDriverBase { && !vlanId.equalsIgnoreCase("untagged")) { if(trafficLabel != null && !trafficLabel.isEmpty()) { s_logger.debug("creating a vlan dev and bridge for guest traffic per traffic label " + trafficLabel); - String brName = createVlanBr(vlanId, _pifs.get(trafficLabel)); - intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType)); + intf.defBridgeNet(_pifs.get(trafficLabel), null, nic.getMac(), getGuestNicModel(guestOsType)); + intf.setVlanTag(Integer.parseInt(vlanId)); } else { - String brName = createVlanBr(vlanId, _pifs.get("private")); - intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType)); + intf.defBridgeNet(_pifs.get("private"), null, nic.getMac(), getGuestNicModel(guestOsType)); + intf.setVlanTag(Integer.parseInt(vlanId)); } } else if (nic.getBroadcastType() == Networks.BroadcastDomainType.Lswitch) { s_logger.debug("nic " + nic + " needs to be connected to LogicalSwitch " + logicalSwitchUuid); @@ -108,11 +108,11 @@ public class OvsVifDriver extends VifDriverBase { && !vlanId.equalsIgnoreCase("untagged")) { if(trafficLabel != null && !trafficLabel.isEmpty()){ s_logger.debug("creating a vlan dev and bridge for public traffic per traffic label " + trafficLabel); - String brName = createVlanBr(vlanId, _pifs.get(trafficLabel)); - intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType)); + intf.defBridgeNet(_pifs.get(trafficLabel), null, nic.getMac(), getGuestNicModel(guestOsType)); + intf.setVlanTag(Integer.parseInt(vlanId)); } else { - String brName = createVlanBr(vlanId, _pifs.get("public")); - intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType)); + intf.defBridgeNet(_pifs.get("public"), null, nic.getMac(), getGuestNicModel(guestOsType)); + intf.setVlanTag(Integer.parseInt(vlanId)); } } else { intf.defBridgeNet(_bridges.get("public"), null, nic.getMac(), getGuestNicModel(guestOsType)); @@ -143,28 +143,6 @@ public class OvsVifDriver extends VifDriverBase { return brName; } - - private String createVlanBr(String vlanId, String nic) - throws InternalErrorException { - String brName = setVnetBrName(nic, vlanId); - createVnet(vlanId, nic, brName); - return brName; - } - - private void createVnet(String vnetId, String pif, String brName) - throws InternalErrorException { - final Script command = new Script(_modifyVlanPath, _timeout, s_logger); - command.add("-v", vnetId); - command.add("-p", pif); - command.add("-b", brName); - command.add("-o", "add"); - - final String result = command.execute(); - if (result != null) { - throw new InternalErrorException("Failed to create vnet " + vnetId - + ": " + result); - } - } private void deleteExitingLinkLocalRoutTable(String linkLocalBr) { Script command = new Script("/bin/bash", _timeout); From c9c40d066ec0039aee3dcb91e6494082efadefe9 Mon Sep 17 00:00:00 2001 From: Hugo Trippaers Date: Thu, 10 Jan 2013 18:30:07 +0100 Subject: [PATCH 05/80] Summary: Add initial support for OpenVswitch to the KVM hypervisor Create OvsVifDriver to deal with openvswitch specifics for plugging intefaces Create a parameter to set the bridge type to use in LibvirtComputingResource. Create several functions to get bridge information from openvswitch Add a check to detect the libvirt version and throw an exception when the version is to low ( < 0.9.11 ) Fix classpath loading in Script.findScript to deal with missing path separators at the end. Add notification to the BridgeVifDriver that lswitch broadcast type is not supported. --- .../kvm/resource/BridgeVifDriver.java | 3 + .../resource/LibvirtComputingResource.java | 97 +++++++- .../hypervisor/kvm/resource/LibvirtVMDef.java | 25 ++ .../hypervisor/kvm/resource/OvsVifDriver.java | 213 ++++++++++++++++++ utils/src/com/cloud/utils/script/Script.java | 20 +- 5 files changed, 348 insertions(+), 10 deletions(-) create mode 100644 plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/BridgeVifDriver.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/BridgeVifDriver.java index e6f2f7f376a..031721e8a3d 100644 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/BridgeVifDriver.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/BridgeVifDriver.java @@ -85,6 +85,9 @@ public class BridgeVifDriver extends VifDriverBase { URI broadcastUri = nic.getBroadcastUri(); vlanId = broadcastUri.getHost(); } + else if (nic.getBroadcastType() == Networks.BroadcastDomainType.Lswitch) { + throw new InternalErrorException("Nicira NVP Logicalswitches are not supported by the BridgeVifDriver"); + } String trafficLabel = nic.getName(); if (nic.getType() == Networks.TrafficType.Guest) { if (nic.getBroadcastType() == Networks.BroadcastDomainType.Vlan diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java index b52e2d8a0b0..fade750c5f8 100755 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java @@ -362,10 +362,16 @@ public class LibvirtComputingResource extends ServerResourceBase implements private String _pingTestPath; private int _dom0MinMem; + + protected enum BridgeType { + NATIVE, OPENVSWITCH + } protected enum defineOps { UNDEFINE_VM, DEFINE_VM } + + protected BridgeType _bridgeType; private String getEndIpFromStartIp(String startIp, int numIps) { String[] tokens = startIp.split("[.]"); @@ -474,6 +480,14 @@ public class LibvirtComputingResource extends ServerResourceBase implements if (storageScriptsDir == null) { storageScriptsDir = getDefaultStorageScriptsDir(); } + + String bridgeType = (String) params.get("network.bridge.type"); + if (bridgeType == null) { + _bridgeType = BridgeType.NATIVE; + } + else { + _bridgeType = BridgeType.valueOf(bridgeType.toUpperCase()); + } params.put("domr.scripts.dir", domrScriptsDir); @@ -650,11 +664,19 @@ public class LibvirtComputingResource extends ServerResourceBase implements LibvirtConnection.initialize(_hypervisorURI); Connect conn = null; - try { - conn = LibvirtConnection.getConnection(); - } catch (LibvirtException e) { - throw new CloudRuntimeException(e.getMessage()); - } + try { + conn = LibvirtConnection.getConnection(); + + if (_bridgeType == BridgeType.OPENVSWITCH) { + if (conn.getLibVirVersion() < (9 * 1000 + 11)) { + throw new ConfigurationException( + "LibVirt version 0.9.11 required for openvswitch support, but version " + + conn.getLibVirVersion() + " detected"); + } + } + } catch (LibvirtException e) { + throw new CloudRuntimeException(e.getMessage()); + } /* Does node support HVM guest? If not, exit */ if (!IsHVMEnabled(conn)) { @@ -697,7 +719,15 @@ public class LibvirtComputingResource extends ServerResourceBase implements } } - getPifs(); + switch (_bridgeType) { + case NATIVE: + getPifs(); + break; + case OPENVSWITCH: + getOvsPifs(); + break; + } + if (_pifs.get("private") == null) { s_logger.debug("Failed to get private nic name"); throw new ConfigurationException("Failed to get private nic name"); @@ -796,6 +826,26 @@ public class LibvirtComputingResource extends ServerResourceBase implements } s_logger.debug("done looking for pifs, no more bridges"); } + + private void getOvsPifs() { + String cmdout = Script.runSimpleBashScript("ovs-vsctl list-br | sed '{:q;N;s/\\n/%/g;t q}'"); + s_logger.debug("cmdout was " + cmdout); + List bridges = Arrays.asList(cmdout.split("%")); + for (String bridge : bridges) { + s_logger.debug("looking for pif for bridge " + bridge); + //String pif = getOvsPif(bridge); + // Not really interested in the pif name at this point for ovs bridges + String pif = bridge; + if(_publicBridgeName != null && bridge.equals(_publicBridgeName)){ + _pifs.put("public", pif); + } + if (_guestBridgeName != null && bridge.equals(_guestBridgeName)) { + _pifs.put("private", pif); + } + _pifs.put(bridge, pif); + } + s_logger.debug("done looking for pifs, no more bridges"); + } private String getPif(String bridge) { String pif = Script.runSimpleBashScript("brctl show | grep " + bridge + " | awk '{print $4}'"); @@ -808,11 +858,29 @@ public class LibvirtComputingResource extends ServerResourceBase implements return pif; } + private String getOvsPif(String bridge) { + String pif = Script.runSimpleBashScript("ovs-vsctl list-ports " + bridge); + return pif; + } + private boolean checkNetwork(String networkName) { if (networkName == null) { return true; } + if (_bridgeType == BridgeType.OPENVSWITCH) { + return checkOvsNetwork(networkName); + } + else { + return checkBridgeNetwork(networkName); + } + } + + private boolean checkBridgeNetwork(String networkName) { + if (networkName == null) { + return true; + } + String name = Script.runSimpleBashScript("brctl show | grep " + networkName + " | awk '{print $4}'"); if (name == null) { @@ -821,6 +889,23 @@ public class LibvirtComputingResource extends ServerResourceBase implements return true; } } + + private boolean checkOvsNetwork(String networkName) { + s_logger.debug("Checking if network " + networkName + " exists as openvswitch bridge"); + if (networkName == null) { + return true; + } + + Script command = new Script("/bin/sh", _timeout); + command.add("-c"); + command.add("ovs-vsctl br-exists " + networkName); + String result = command.execute(null); + if ("Ok".equals(result)) { + return true; + } else { + return false; + } + } private String getVnetId(String vnetId) { return vnetId; diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtVMDef.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtVMDef.java index ba6c715e455..17f6eef0b8e 100644 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtVMDef.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtVMDef.java @@ -646,6 +646,8 @@ public class LibvirtVMDef { private String _ipAddr; private String _scriptPath; private nicModel _model; + private String _virtualPortType; + private String _virtualPortInterfaceId; public void defBridgeNet(String brName, String targetBrName, String macAddr, nicModel model) { @@ -695,6 +697,22 @@ public class LibvirtVMDef { public String getMacAddress() { return _macAddr; } + + public void setVirtualPortType(String virtualPortType) { + _virtualPortType = virtualPortType; + } + + public String getVirtualPortType() { + return _virtualPortType; + } + + public void setVirtualPortInterfaceId(String virtualPortInterfaceId) { + _virtualPortInterfaceId = virtualPortInterfaceId; + } + + public String getVirtualPortInterfaceId() { + return _virtualPortInterfaceId; + } @Override public String toString() { @@ -714,6 +732,13 @@ public class LibvirtVMDef { if (_model != null) { netBuilder.append("\n"); } + if (_virtualPortType != null) { + netBuilder.append("\n"); + if (_virtualPortInterfaceId != null) { + netBuilder.append("\n"); + } + netBuilder.append("\n"); + } netBuilder.append("\n"); return netBuilder.toString(); } diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java new file mode 100644 index 00000000000..6c3e4963ec5 --- /dev/null +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java @@ -0,0 +1,213 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package com.cloud.hypervisor.kvm.resource; + +import java.net.URI; +import java.util.Map; + +import javax.naming.ConfigurationException; + +import org.apache.log4j.Logger; +import org.libvirt.LibvirtException; + +import com.cloud.agent.api.to.NicTO; +import com.cloud.exception.InternalErrorException; +import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.InterfaceDef; +import com.cloud.network.Networks; +import com.cloud.utils.NumbersUtil; +import com.cloud.utils.net.NetUtils; +import com.cloud.utils.script.OutputInterpreter; +import com.cloud.utils.script.Script; + +public class OvsVifDriver extends VifDriverBase { + private static final Logger s_logger = Logger + .getLogger(BridgeVifDriver.class); + private int _timeout; + private String _modifyVlanPath; + + @Override + public void configure(Map params) throws ConfigurationException { + super.configure(params); + + String networkScriptsDir = (String) params.get("network.scripts.dir"); + if (networkScriptsDir == null) { + networkScriptsDir = "scripts/vm/network/vnet"; + } + + String value = (String) params.get("scripts.timeout"); + _timeout = NumbersUtil.parseInt(value, 30 * 60) * 1000; + + _modifyVlanPath = Script.findScript(networkScriptsDir, "modifyvlan.sh"); + if (_modifyVlanPath == null) { + throw new ConfigurationException("Unable to find modifyvlan.sh"); + } + + createControlNetwork(_bridges.get("linklocal")); + } + + @Override + public InterfaceDef plug(NicTO nic, String guestOsType) + throws InternalErrorException, LibvirtException { + s_logger.debug("plugging nic=" + nic); + + LibvirtVMDef.InterfaceDef intf = new LibvirtVMDef.InterfaceDef(); + intf.setVirtualPortType("openvswitch"); + + String vlanId = null; + String logicalSwitchUuid = null; + if (nic.getBroadcastType() == Networks.BroadcastDomainType.Vlan) { + URI broadcastUri = nic.getBroadcastUri(); + vlanId = broadcastUri.getHost(); + } + else if (nic.getBroadcastType() == Networks.BroadcastDomainType.Lswitch) { + logicalSwitchUuid = nic.getBroadcastUri().getSchemeSpecificPart(); + } + String trafficLabel = nic.getName(); + if (nic.getType() == Networks.TrafficType.Guest) { + if (nic.getBroadcastType() == Networks.BroadcastDomainType.Vlan + && !vlanId.equalsIgnoreCase("untagged")) { + if(trafficLabel != null && !trafficLabel.isEmpty()) { + s_logger.debug("creating a vlan dev and bridge for guest traffic per traffic label " + trafficLabel); + String brName = createVlanBr(vlanId, _pifs.get(trafficLabel)); + intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType)); + } else { + String brName = createVlanBr(vlanId, _pifs.get("private")); + intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType)); + } + } else if (nic.getBroadcastType() == Networks.BroadcastDomainType.Lswitch) { + s_logger.debug("nic " + nic + " needs to be connected to LogicalSwitch " + logicalSwitchUuid); + intf.setVirtualPortInterfaceId(nic.getUuid()); + String brName = (trafficLabel != null && !trafficLabel.isEmpty()) ? _pifs.get(trafficLabel) : _pifs.get("private"); + intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType)); + } + else { + intf.defBridgeNet(_bridges.get("guest"), null, nic.getMac(), getGuestNicModel(guestOsType)); + } + } else if (nic.getType() == Networks.TrafficType.Control) { + /* Make sure the network is still there */ + createControlNetwork(_bridges.get("linklocal")); + intf.defBridgeNet(_bridges.get("linklocal"), null, nic.getMac(), getGuestNicModel(guestOsType)); + } else if (nic.getType() == Networks.TrafficType.Public) { + if (nic.getBroadcastType() == Networks.BroadcastDomainType.Vlan + && !vlanId.equalsIgnoreCase("untagged")) { + if(trafficLabel != null && !trafficLabel.isEmpty()){ + s_logger.debug("creating a vlan dev and bridge for public traffic per traffic label " + trafficLabel); + String brName = createVlanBr(vlanId, _pifs.get(trafficLabel)); + intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType)); + } else { + String brName = createVlanBr(vlanId, _pifs.get("public")); + intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType)); + } + } else { + intf.defBridgeNet(_bridges.get("public"), null, nic.getMac(), getGuestNicModel(guestOsType)); + } + } else if (nic.getType() == Networks.TrafficType.Management) { + intf.defBridgeNet(_bridges.get("private"), null, nic.getMac(), getGuestNicModel(guestOsType)); + } else if (nic.getType() == Networks.TrafficType.Storage) { + String storageBrName = nic.getName() == null ? _bridges.get("private") + : nic.getName(); + intf.defBridgeNet(storageBrName, null, nic.getMac(), getGuestNicModel(guestOsType)); + } + return intf; + } + + @Override + public void unplug(InterfaceDef iface) { + // Libvirt apparently takes care of this, see BridgeVifDriver unplug + } + + private String setVnetBrName(String pifName, String vnetId) { + String brName = "br" + pifName + "-"+ vnetId; + String oldStyleBrName = "cloudVirBr" + vnetId; + + if (isBridgeExists(oldStyleBrName)) { + s_logger.info("Using old style bridge name for vlan " + vnetId + " because existing bridge " + oldStyleBrName + " was found"); + brName = oldStyleBrName; + } + + return brName; + } + + private String createVlanBr(String vlanId, String nic) + throws InternalErrorException { + String brName = setVnetBrName(nic, vlanId); + createVnet(vlanId, nic, brName); + return brName; + } + + private void createVnet(String vnetId, String pif, String brName) + throws InternalErrorException { + final Script command = new Script(_modifyVlanPath, _timeout, s_logger); + command.add("-v", vnetId); + command.add("-p", pif); + command.add("-b", brName); + command.add("-o", "add"); + + final String result = command.execute(); + if (result != null) { + throw new InternalErrorException("Failed to create vnet " + vnetId + + ": " + result); + } + } + + private void deleteExitingLinkLocalRoutTable(String linkLocalBr) { + Script command = new Script("/bin/bash", _timeout); + command.add("-c"); + command.add("ip route | grep " + NetUtils.getLinkLocalCIDR()); + OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser(); + String result = command.execute(parser); + boolean foundLinkLocalBr = false; + if (result == null && parser.getLines() != null) { + String[] lines = parser.getLines().split("\\n"); + for (String line : lines) { + String[] tokens = line.split(" "); + if (!tokens[2].equalsIgnoreCase(linkLocalBr)) { + Script.runSimpleBashScript("ip route del " + NetUtils.getLinkLocalCIDR()); + } else { + foundLinkLocalBr = true; + } + } + } + if (!foundLinkLocalBr) { + Script.runSimpleBashScript("ifconfig " + linkLocalBr + " 169.254.0.1;" + "ip route add " + + NetUtils.getLinkLocalCIDR() + " dev " + linkLocalBr + " src " + NetUtils.getLinkLocalGateway()); + } + } + + private void createControlNetwork(String privBrName) { + deleteExitingLinkLocalRoutTable(privBrName); + if (!isBridgeExists(privBrName)) { + Script.runSimpleBashScript("ovs-vsctl add-br " + privBrName + "; ifconfig " + privBrName + " up; ifconfig " + + privBrName + " 169.254.0.1", _timeout); + } + + } + + private boolean isBridgeExists(String bridgeName) { + Script command = new Script("/bin/sh", _timeout); + command.add("-c"); + command.add("ovs-vsctl br-exists " + bridgeName); + String result = command.execute(null); + if ("Ok".equals(result)) { + return true; + } else { + return false; + } + } +} diff --git a/utils/src/com/cloud/utils/script/Script.java b/utils/src/com/cloud/utils/script/Script.java index 1444f83f425..d82d1d00957 100755 --- a/utils/src/com/cloud/utils/script/Script.java +++ b/utils/src/com/cloud/utils/script/Script.java @@ -195,7 +195,7 @@ public class Script implements Callable { } Task task = null; - if (interpreter.drain()) { + if (interpreter != null && interpreter.drain()) { task = new Task(interpreter, ir); s_executors.execute(task); } @@ -204,8 +204,13 @@ public class Script implements Callable { try { if (_process.waitFor() == 0) { _logger.debug("Execution is successful."); - - return interpreter.drain() ? task.getResult() : interpreter.interpret(ir); + if (interpreter != null) { + return interpreter.drain() ? task.getResult() : interpreter.interpret(ir); + } + else { + // null return is ok apparently + return (_process.exitValue() == 0) ? "Ok" : "Failed, exit code " + _process.exitValue(); + } } else { break; } @@ -239,7 +244,14 @@ public class Script implements Callable { BufferedReader reader = new BufferedReader(new InputStreamReader(_process.getInputStream()), 128); - String error = interpreter.processError(reader); + String error; + if (interpreter != null) { + error = interpreter.processError(reader); + } + else { + error = "Non zero exit code : " + _process.exitValue(); + } + if (_logger.isDebugEnabled()) { _logger.debug(error); } From c6916ff4e06a2b7d5c53b9ed48828a0eff400895 Mon Sep 17 00:00:00 2001 From: Hugo Trippaers Date: Fri, 11 Jan 2013 17:04:32 +0100 Subject: [PATCH 06/80] Summary: Add vlan configuration to the network inteface definition Add xml piece for defining vlans Set vlan tag in the libvirt definition for the network inteface --- .../hypervisor/kvm/resource/LibvirtVMDef.java | 14 ++++++- .../hypervisor/kvm/resource/OvsVifDriver.java | 38 ++++--------------- 2 files changed, 21 insertions(+), 31 deletions(-) diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtVMDef.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtVMDef.java index 17f6eef0b8e..df277780aa3 100644 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtVMDef.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtVMDef.java @@ -648,6 +648,7 @@ public class LibvirtVMDef { private nicModel _model; private String _virtualPortType; private String _virtualPortInterfaceId; + private int _vlanTag = -1; public void defBridgeNet(String brName, String targetBrName, String macAddr, nicModel model) { @@ -713,7 +714,15 @@ public class LibvirtVMDef { public String getVirtualPortInterfaceId() { return _virtualPortInterfaceId; } - + + public void setVlanTag(int vlanTag) { + _vlanTag = vlanTag; + } + + public int getVlanTag() { + return _vlanTag; + } + @Override public String toString() { StringBuilder netBuilder = new StringBuilder(); @@ -739,6 +748,9 @@ public class LibvirtVMDef { } netBuilder.append("\n"); } + if (_vlanTag != -1) { + netBuilder.append("\n\n"); + } netBuilder.append("\n"); return netBuilder.toString(); } diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java index 6c3e4963ec5..52fc29e5387 100644 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java @@ -84,11 +84,11 @@ public class OvsVifDriver extends VifDriverBase { && !vlanId.equalsIgnoreCase("untagged")) { if(trafficLabel != null && !trafficLabel.isEmpty()) { s_logger.debug("creating a vlan dev and bridge for guest traffic per traffic label " + trafficLabel); - String brName = createVlanBr(vlanId, _pifs.get(trafficLabel)); - intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType)); + intf.defBridgeNet(_pifs.get(trafficLabel), null, nic.getMac(), getGuestNicModel(guestOsType)); + intf.setVlanTag(Integer.parseInt(vlanId)); } else { - String brName = createVlanBr(vlanId, _pifs.get("private")); - intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType)); + intf.defBridgeNet(_pifs.get("private"), null, nic.getMac(), getGuestNicModel(guestOsType)); + intf.setVlanTag(Integer.parseInt(vlanId)); } } else if (nic.getBroadcastType() == Networks.BroadcastDomainType.Lswitch) { s_logger.debug("nic " + nic + " needs to be connected to LogicalSwitch " + logicalSwitchUuid); @@ -108,11 +108,11 @@ public class OvsVifDriver extends VifDriverBase { && !vlanId.equalsIgnoreCase("untagged")) { if(trafficLabel != null && !trafficLabel.isEmpty()){ s_logger.debug("creating a vlan dev and bridge for public traffic per traffic label " + trafficLabel); - String brName = createVlanBr(vlanId, _pifs.get(trafficLabel)); - intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType)); + intf.defBridgeNet(_pifs.get(trafficLabel), null, nic.getMac(), getGuestNicModel(guestOsType)); + intf.setVlanTag(Integer.parseInt(vlanId)); } else { - String brName = createVlanBr(vlanId, _pifs.get("public")); - intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType)); + intf.defBridgeNet(_pifs.get("public"), null, nic.getMac(), getGuestNicModel(guestOsType)); + intf.setVlanTag(Integer.parseInt(vlanId)); } } else { intf.defBridgeNet(_bridges.get("public"), null, nic.getMac(), getGuestNicModel(guestOsType)); @@ -143,28 +143,6 @@ public class OvsVifDriver extends VifDriverBase { return brName; } - - private String createVlanBr(String vlanId, String nic) - throws InternalErrorException { - String brName = setVnetBrName(nic, vlanId); - createVnet(vlanId, nic, brName); - return brName; - } - - private void createVnet(String vnetId, String pif, String brName) - throws InternalErrorException { - final Script command = new Script(_modifyVlanPath, _timeout, s_logger); - command.add("-v", vnetId); - command.add("-p", pif); - command.add("-b", brName); - command.add("-o", "add"); - - final String result = command.execute(); - if (result != null) { - throw new InternalErrorException("Failed to create vnet " + vnetId - + ": " + result); - } - } private void deleteExitingLinkLocalRoutTable(String linkLocalBr) { Script command = new Script("/bin/bash", _timeout); From 4764f98866125972afc3a53d3f5f8ff7f7485b3a Mon Sep 17 00:00:00 2001 From: Hugo Trippaers Date: Mon, 14 Jan 2013 16:16:19 +0100 Subject: [PATCH 07/80] Summary: Fix logic error Should if "if the username is not cloud AND developer is not true, then report an error" --- server/src/com/cloud/server/ConfigurationServerImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/src/com/cloud/server/ConfigurationServerImpl.java b/server/src/com/cloud/server/ConfigurationServerImpl.java index b25c63f6d7f..7e5f42445d5 100755 --- a/server/src/com/cloud/server/ConfigurationServerImpl.java +++ b/server/src/com/cloud/server/ConfigurationServerImpl.java @@ -549,7 +549,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { String username = System.getProperty("user.name"); Boolean devel = Boolean.valueOf(_configDao.getValue("developer")); - if (!username.equalsIgnoreCase("cloud") || !devel) { + if (!username.equalsIgnoreCase("cloud") && !devel) { s_logger.warn("Systemvm keypairs could not be set. Management server should be run as cloud user, or in development mode."); return; } From 8738fee7894cc7f805b0f8beca30a5aa491f956b Mon Sep 17 00:00:00 2001 From: Hugo Trippaers Date: Mon, 14 Jan 2013 17:09:49 +0100 Subject: [PATCH 08/80] Summary: small fix causing trouble when shutting down virtual machines --- .../cloud/hypervisor/kvm/storage/KVMStoragePoolManager.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/storage/KVMStoragePoolManager.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/storage/KVMStoragePoolManager.java index ac611275e5a..1af2ed22c27 100644 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/storage/KVMStoragePoolManager.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/storage/KVMStoragePoolManager.java @@ -38,6 +38,10 @@ public class KVMStoragePoolManager { private final Map _storageMapper = new HashMap(); private StorageAdaptor getStorageAdaptor(StoragePoolType type) { + // type can be null: LibVirtComputingResource:3238 + if (type == null) { + return _storageMapper.get("libvirt"); + } StorageAdaptor adaptor = _storageMapper.get(type.toString()); if (adaptor == null) { // LibvirtStorageAdaptor is selected by default From 32c5fed1fb9f78aeb1ed36d9c801cfb4d26296d0 Mon Sep 17 00:00:00 2001 From: Hugo Trippaers Date: Mon, 14 Jan 2013 17:17:06 +0100 Subject: [PATCH 09/80] Summary: copy/paste error --- .../kvm/src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java index 52fc29e5387..4565e2878be 100644 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java @@ -37,7 +37,7 @@ import com.cloud.utils.script.Script; public class OvsVifDriver extends VifDriverBase { private static final Logger s_logger = Logger - .getLogger(BridgeVifDriver.class); + .getLogger(OvsVifDriver.class); private int _timeout; private String _modifyVlanPath; From 11fd1216edf62766be8c99e07ed421341377c74e Mon Sep 17 00:00:00 2001 From: Hugo Trippaers Date: Mon, 14 Jan 2013 18:43:15 +0100 Subject: [PATCH 10/80] Summary: Polish and shine Document the used options in agent.properties Default the bridge driver to something sensible based on the configuration of the bridge type. --- agent/conf/agent.properties | 11 +++++++++++ .../kvm/resource/LibvirtComputingResource.java | 10 ++++++++-- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/agent/conf/agent.properties b/agent/conf/agent.properties index 27572b53653..74cfd1c21d6 100644 --- a/agent/conf/agent.properties +++ b/agent/conf/agent.properties @@ -69,3 +69,14 @@ domr.scripts.dir=scripts/network/domr/kvm # set the vm migrate speed, by default, it will try to guess the speed of the guest network # In MegaBytes per second #vm.migrate.speed=0 + +# set the type of bridge used on the hypervisor, this defines what commands the resource +# will use to setup networking. Currently supported NATIVE, OPENVSWITCH +#network.bridge.type=native + +# set the driver used to plug and unplug nics from the bridges +# a sensible default will be selected based on the network.bridge.type but can +# be overridden here. +# native = com.cloud.hypervisor.kvm.resource.BridgeVifDriver +# openvswitch = com.cloud.hypervisor.kvm.resource.OvsBridgeDriver +#libvirt.vif.driver=com.cloud.hypervisor.kvm.resource.BridgeVifDriver \ No newline at end of file diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java index fade750c5f8..1474d114619 100755 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java @@ -786,8 +786,14 @@ public class LibvirtComputingResource extends ServerResourceBase implements // Load the vif driver String vifDriverName = (String) params.get("libvirt.vif.driver"); if (vifDriverName == null) { - s_logger.info("No libvirt.vif.driver specififed. Defaults to BridgeVifDriver."); - vifDriverName = "com.cloud.hypervisor.kvm.resource.BridgeVifDriver"; + if (_bridgeType == BridgeType.OPENVSWITCH) { + s_logger.info("No libvirt.vif.driver specififed. Defaults to OvsVifDriver."); + vifDriverName = "com.cloud.hypervisor.kvm.resource.OvsVifDriver"; + } + else { + s_logger.info("No libvirt.vif.driver specififed. Defaults to BridgeVifDriver."); + vifDriverName = "com.cloud.hypervisor.kvm.resource.BridgeVifDriver"; + } } params.put("libvirt.computing.resource", (Object) this); From 4d0c850dc82509d66dc88eed05586ee06f682393 Mon Sep 17 00:00:00 2001 From: Min Chen Date: Mon, 14 Jan 2013 17:13:18 -0800 Subject: [PATCH 11/80] Fix plugin component configuration. --- .../cloudstack/acl/APILimitChecker.java | 4 +- client/pom.xml | 5 ++ client/tomcatconf/components.xml.in | 8 ++ .../admin/ratelimit/ResetApiLimitCmd.java | 2 +- .../user/ratelimit/GetApiLimitCmd.java | 2 +- .../ratelimit/ApiRateLimitService.java | 2 +- .../ratelimit/ApiRateLimitServiceImpl.java | 75 +++++++++++-------- .../cloudstack/ratelimit/StoreEntryImpl.java | 2 +- .../ratelimit/ApiRateLimitTest.java | 41 +++++----- server/src/com/cloud/api/ApiServer.java | 20 ++--- .../src/com/cloud/configuration/Config.java | 4 +- server/test/com/cloud/api/ListPerfTest.java | 54 +++++++++++++ setup/db/db/schema-40to410.sql | 2 + 13 files changed, 150 insertions(+), 71 deletions(-) rename plugins/api/rate-limit/src/org/apache/cloudstack/api/{commands => command}/admin/ratelimit/ResetApiLimitCmd.java (98%) diff --git a/api/src/org/apache/cloudstack/acl/APILimitChecker.java b/api/src/org/apache/cloudstack/acl/APILimitChecker.java index 3a1db705e70..110742c059d 100644 --- a/api/src/org/apache/cloudstack/acl/APILimitChecker.java +++ b/api/src/org/apache/cloudstack/acl/APILimitChecker.java @@ -16,6 +16,8 @@ // under the License. package org.apache.cloudstack.acl; +import org.apache.cloudstack.api.ServerApiException; + import com.cloud.user.Account; import com.cloud.utils.component.Adapter; @@ -24,5 +26,5 @@ import com.cloud.utils.component.Adapter; */ public interface APILimitChecker extends Adapter { // Interface for checking if the account is over its api limit - boolean isUnderLimit(Account account); + void checkLimit(Account account) throws ServerApiException; } diff --git a/client/pom.xml b/client/pom.xml index 1bbae1f7d08..7ebe50c48f9 100644 --- a/client/pom.xml +++ b/client/pom.xml @@ -30,6 +30,11 @@ cloud-plugin-acl-static-role-based ${project.version} + + org.apache.cloudstack + cloud-plugin-api-limit-account-based + ${project.version} + org.apache.cloudstack cloud-plugin-api-discovery diff --git a/client/tomcatconf/components.xml.in b/client/tomcatconf/components.xml.in index bb39839c820..dcff94a77e0 100755 --- a/client/tomcatconf/components.xml.in +++ b/client/tomcatconf/components.xml.in @@ -56,6 +56,9 @@ under the License. + + + @@ -180,6 +183,11 @@ under the License. + + 1 + 25 + 50000 + diff --git a/plugins/api/rate-limit/src/org/apache/cloudstack/api/commands/admin/ratelimit/ResetApiLimitCmd.java b/plugins/api/rate-limit/src/org/apache/cloudstack/api/command/admin/ratelimit/ResetApiLimitCmd.java similarity index 98% rename from plugins/api/rate-limit/src/org/apache/cloudstack/api/commands/admin/ratelimit/ResetApiLimitCmd.java rename to plugins/api/rate-limit/src/org/apache/cloudstack/api/command/admin/ratelimit/ResetApiLimitCmd.java index 8029ab3707a..3c612faf302 100644 --- a/plugins/api/rate-limit/src/org/apache/cloudstack/api/commands/admin/ratelimit/ResetApiLimitCmd.java +++ b/plugins/api/rate-limit/src/org/apache/cloudstack/api/command/admin/ratelimit/ResetApiLimitCmd.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package org.apache.cloudstack.api.commands.admin.ratelimit; +package org.apache.cloudstack.api.command.admin.ratelimit; import org.apache.cloudstack.api.*; import org.apache.cloudstack.api.response.AccountResponse; diff --git a/plugins/api/rate-limit/src/org/apache/cloudstack/api/command/user/ratelimit/GetApiLimitCmd.java b/plugins/api/rate-limit/src/org/apache/cloudstack/api/command/user/ratelimit/GetApiLimitCmd.java index 3f9e4eb4503..0397fa8ab54 100644 --- a/plugins/api/rate-limit/src/org/apache/cloudstack/api/command/user/ratelimit/GetApiLimitCmd.java +++ b/plugins/api/rate-limit/src/org/apache/cloudstack/api/command/user/ratelimit/GetApiLimitCmd.java @@ -27,7 +27,7 @@ import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.PlugService; import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.BaseCmd.CommandType; -import org.apache.cloudstack.api.commands.admin.ratelimit.ResetApiLimitCmd; +import org.apache.cloudstack.api.command.admin.ratelimit.ResetApiLimitCmd; import org.apache.cloudstack.api.response.AccountResponse; import org.apache.cloudstack.api.response.ApiLimitResponse; import org.apache.cloudstack.api.response.PhysicalNetworkResponse; diff --git a/plugins/api/rate-limit/src/org/apache/cloudstack/ratelimit/ApiRateLimitService.java b/plugins/api/rate-limit/src/org/apache/cloudstack/ratelimit/ApiRateLimitService.java index e7ba9d45fc3..8c9d49b007f 100644 --- a/plugins/api/rate-limit/src/org/apache/cloudstack/ratelimit/ApiRateLimitService.java +++ b/plugins/api/rate-limit/src/org/apache/cloudstack/ratelimit/ApiRateLimitService.java @@ -16,8 +16,8 @@ // under the License. package org.apache.cloudstack.ratelimit; +import org.apache.cloudstack.api.command.admin.ratelimit.ResetApiLimitCmd; import org.apache.cloudstack.api.command.user.ratelimit.GetApiLimitCmd; -import org.apache.cloudstack.api.commands.admin.ratelimit.ResetApiLimitCmd; import org.apache.cloudstack.api.response.ApiLimitResponse; import org.apache.cloudstack.api.response.ListResponse; diff --git a/plugins/api/rate-limit/src/org/apache/cloudstack/ratelimit/ApiRateLimitServiceImpl.java b/plugins/api/rate-limit/src/org/apache/cloudstack/ratelimit/ApiRateLimitServiceImpl.java index e14f65d383e..00f39af1e1e 100644 --- a/plugins/api/rate-limit/src/org/apache/cloudstack/ratelimit/ApiRateLimitServiceImpl.java +++ b/plugins/api/rate-limit/src/org/apache/cloudstack/ratelimit/ApiRateLimitServiceImpl.java @@ -25,19 +25,18 @@ import net.sf.ehcache.CacheManager; import org.apache.log4j.Logger; -import com.cloud.configuration.Config; -import com.cloud.configuration.dao.ConfigurationDao; import org.apache.cloudstack.acl.APILimitChecker; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.command.admin.ratelimit.ResetApiLimitCmd; import org.apache.cloudstack.api.command.user.ratelimit.GetApiLimitCmd; -import org.apache.cloudstack.api.commands.admin.ratelimit.ResetApiLimitCmd; import org.apache.cloudstack.api.response.ApiLimitResponse; -import com.cloud.network.element.NetworkElement; import com.cloud.user.Account; import com.cloud.user.UserContext; +import com.cloud.utils.PropertiesUtil; import com.cloud.utils.component.AdapterBase; -import com.cloud.utils.component.Inject; -@Local(value = NetworkElement.class) +@Local(value = APILimitChecker.class) public class ApiRateLimitServiceImpl extends AdapterBase implements APILimitChecker, ApiRateLimitService { private static final Logger s_logger = Logger.getLogger(ApiRateLimitServiceImpl.class); @@ -51,33 +50,40 @@ public class ApiRateLimitServiceImpl extends AdapterBase implements APILimitChec */ private int maxAllowed = 30; - @Inject - ConfigurationDao _configDao; - - private LimitStore _store; + private LimitStore _store = null; @Override public boolean configure(String name, Map params) throws ConfigurationException { super.configure(name, params); - // get global configured duration and max values - String duration = _configDao.getValue(Config.ApiLimitInterval.key()); - if (duration != null ){ - timeToLive = Integer.parseInt(duration); + + if (_store == null) { + // not configured yet, note that since this class is both adapter + // and pluggableService, so this method + // may be invoked twice in ComponentLocator. + // get global configured duration and max values + Object duration = params.get("api.throttling.interval"); + if (duration != null) { + timeToLive = Integer.parseInt((String) duration); + } + Object maxReqs = params.get("api.throttling.max"); + if (maxReqs != null) { + maxAllowed = Integer.parseInt((String) maxReqs); + } + // create limit store + EhcacheLimitStore cacheStore = new EhcacheLimitStore(); + int maxElements = 10000; + Object cachesize = params.get("api.throttling.cachesize"); + if ( cachesize != null ){ + maxElements = Integer.parseInt((String)cachesize); + } + CacheManager cm = CacheManager.create(); + Cache cache = new Cache("api-limit-cache", maxElements, false, false, timeToLive, timeToLive); + cm.addCache(cache); + s_logger.info("Limit Cache created: " + cache.toString()); + cacheStore.setCache(cache); + _store = cacheStore; } - String maxReqs = _configDao.getValue(Config.ApiLimitMax.key()); - if ( maxReqs != null){ - maxAllowed = Integer.parseInt(maxReqs); - } - // create limit store - EhcacheLimitStore cacheStore = new EhcacheLimitStore(); - int maxElements = 10000; //TODO: what should be the proper number here? - CacheManager cm = CacheManager.create(); - Cache cache = new Cache("api-limit-cache", maxElements, true, false, timeToLive, timeToLive); - cm.addCache(cache); - s_logger.info("Limit Cache created: " + cache.toString()); - cacheStore.setCache(cache); - _store = cacheStore; return true; @@ -123,9 +129,8 @@ public class ApiRateLimitServiceImpl extends AdapterBase implements APILimitChec } - @Override - public boolean isUnderLimit(Account account) { + public void checkLimit(Account account) throws ServerApiException { Long accountId = account.getId(); StoreEntry entry = _store.get(accountId); @@ -140,17 +145,21 @@ public class ApiRateLimitServiceImpl extends AdapterBase implements APILimitChec int current = entry.incrementAndGet(); if (current <= maxAllowed) { - return true; + return; } else { - return false; + long expireAfter = entry.getExpireDuration(); + s_logger.warn("The given user has reached his/her account api limit, please retry after " + expireAfter + " ms."); + throw new ServerApiException(BaseCmd.API_LIMIT_EXCEED, "The given user has reached his/her account api limit, please retry after " + + expireAfter + " ms."); } } @Override - public String[] getPropertiesFiles() { - return new String[] { "api-limit_commands.properties" }; + public Map getProperties() { + return PropertiesUtil.processConfigFile(new String[] + { "api-limit_commands.properties" }); } diff --git a/plugins/api/rate-limit/src/org/apache/cloudstack/ratelimit/StoreEntryImpl.java b/plugins/api/rate-limit/src/org/apache/cloudstack/ratelimit/StoreEntryImpl.java index 40965d9da8e..e8143e52370 100644 --- a/plugins/api/rate-limit/src/org/apache/cloudstack/ratelimit/StoreEntryImpl.java +++ b/plugins/api/rate-limit/src/org/apache/cloudstack/ratelimit/StoreEntryImpl.java @@ -47,7 +47,7 @@ public class StoreEntryImpl implements StoreEntry { if ( isExpired() ) return 0; // already expired else { - return (expiry - System.currentTimeMillis()) * 1000; + return expiry - System.currentTimeMillis(); } } diff --git a/plugins/api/rate-limit/test/org/apache/cloudstack/ratelimit/ApiRateLimitTest.java b/plugins/api/rate-limit/test/org/apache/cloudstack/ratelimit/ApiRateLimitTest.java index 0e2080ab2f1..ef3cf6d7948 100644 --- a/plugins/api/rate-limit/test/org/apache/cloudstack/ratelimit/ApiRateLimitTest.java +++ b/plugins/api/rate-limit/test/org/apache/cloudstack/ratelimit/ApiRateLimitTest.java @@ -23,8 +23,9 @@ import java.util.concurrent.Executors; import javax.naming.ConfigurationException; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.command.admin.ratelimit.ResetApiLimitCmd; import org.apache.cloudstack.api.command.user.ratelimit.GetApiLimitCmd; -import org.apache.cloudstack.api.commands.admin.ratelimit.ResetApiLimitCmd; import org.apache.cloudstack.api.response.ApiLimitResponse; import org.apache.cloudstack.ratelimit.ApiRateLimitServiceImpl; import org.junit.Before; @@ -43,16 +44,10 @@ import static org.mockito.Mockito.*; public class ApiRateLimitTest { static ApiRateLimitServiceImpl _limitService = new ApiRateLimitServiceImpl(); - static ConfigurationDao _configDao = mock(ConfigurationDao.class); private static long acctIdSeq = 0L; @BeforeClass public static void setUp() throws ConfigurationException { - _limitService._configDao = _configDao; - - // No global configuration set, will set in each test case - when(_configDao.getValue(Config.ApiLimitInterval.key())).thenReturn(null); - when(_configDao.getValue(Config.ApiLimitMax.key())).thenReturn(null); _limitService.configure("ApiRateLimitTest", Collections. emptyMap()); } @@ -62,6 +57,16 @@ public class ApiRateLimitTest { return new AccountVO(acctIdSeq++); } + private boolean isUnderLimit(Account key){ + try{ + _limitService.checkLimit(key); + return true; + } + catch (ServerApiException ex){ + return false; + } + } + @Test public void sequentialApiAccess() { int allowedRequests = 1; @@ -69,10 +74,10 @@ public class ApiRateLimitTest { _limitService.setTimeToLive(1); Account key = createFakeAccount(); - assertTrue("Allow for the first request", _limitService.isUnderLimit(key)); + assertTrue("Allow for the first request", isUnderLimit(key)); assertFalse("Second request should be blocked, since we assume that the two api " - + " accesses take less than a second to perform", _limitService.isUnderLimit(key)); + + " accesses take less than a second to perform", isUnderLimit(key)); } @Test @@ -84,11 +89,11 @@ public class ApiRateLimitTest { Account key = createFakeAccount(); for (int i = 0; i < allowedRequests; i++) { - assertTrue("We should allow " + allowedRequests + " requests per second", _limitService.isUnderLimit(key)); + assertTrue("We should allow " + allowedRequests + " requests per second", isUnderLimit(key)); } - assertFalse("We should block >" + allowedRequests + " requests per second", _limitService.isUnderLimit(key)); + assertFalse("We should block >" + allowedRequests + " requests per second", isUnderLimit(key)); } @Test @@ -121,7 +126,7 @@ public class ApiRateLimitTest { try { startGate.await(); - isUsable[j] = _limitService.isUnderLimit(key); + isUsable[j] = isUnderLimit(key); } catch (InterruptedException e) { e.printStackTrace(); @@ -155,12 +160,12 @@ public class ApiRateLimitTest { Account key = this.createFakeAccount(); - assertTrue("The first request should be allowed", _limitService.isUnderLimit(key)); + assertTrue("The first request should be allowed", isUnderLimit(key)); // Allow the token to expire Thread.sleep(1001); - assertTrue("Another request after interval should be allowed as well", _limitService.isUnderLimit(key)); + assertTrue("Another request after interval should be allowed as well", isUnderLimit(key)); } @Test @@ -171,16 +176,16 @@ public class ApiRateLimitTest { Account key = this.createFakeAccount(); - assertTrue("The first request should be allowed", _limitService.isUnderLimit(key)); + assertTrue("The first request should be allowed", isUnderLimit(key)); - assertFalse("Another request should be blocked", _limitService.isUnderLimit(key)); + assertFalse("Another request should be blocked", isUnderLimit(key)); ResetApiLimitCmd cmd = new ResetApiLimitCmd(); cmd.setAccountId(key.getId()); _limitService.resetApiLimit(cmd); - assertTrue("Another request should be allowed after reset counter", _limitService.isUnderLimit(key)); + assertTrue("Another request should be allowed after reset counter", isUnderLimit(key)); } /* Disable this since I cannot mock Static method UserContext.current() @@ -193,7 +198,7 @@ public class ApiRateLimitTest { Account key = this.createFakeAccount(); for ( int i = 0; i < 5; i++ ){ - assertTrue("Issued 5 requests", _limitService.isUnderLimit(key)); + assertTrue("Issued 5 requests", isUnderLimit(key)); } GetApiLimitCmd cmd = new GetApiLimitCmd(); diff --git a/server/src/com/cloud/api/ApiServer.java b/server/src/com/cloud/api/ApiServer.java index b2a6a87d9e5..1d15acf0b6f 100755 --- a/server/src/com/cloud/api/ApiServer.java +++ b/server/src/com/cloud/api/ApiServer.java @@ -556,12 +556,9 @@ public class ApiServer implements HttpRequestHandler { if (userId != null) { User user = ApiDBUtils.findUserById(userId); if (apiThrottlingEnabled){ - // go through each API limit checker - if (!isRequestAllowed(user)) { - //FIXME: more detailed message regarding when he/she can retry - s_logger.warn("The given user has reached his/her account api limit, please retry later"); - throw new ServerApiException(BaseCmd.API_LIMIT_EXCEED, "The given user has reached his/her account api limit"); - } + // go through each API limit checker, throw exception inside adapter implementation so that message + // can contain some detailed information only known for each adapter implementation. + checkRequestLimit(user); } if (!isCommandAvailable(user, commandName)) { s_logger.debug("The given command:" + commandName + " does not exist or it is not available for user with id:" + userId); @@ -803,20 +800,19 @@ public class ApiServer implements HttpRequestHandler { } - private boolean isRequestAllowed(User user) { + private void checkRequestLimit(User user) throws ServerApiException { Account account = ApiDBUtils.findAccountById(user.getAccountId()); if ( _accountMgr.isRootAdmin(account.getType()) ){ // no api throttling for root admin - return true; + return; } for (APILimitChecker apiChecker : _apiLimitCheckers) { // Fail the checking if any checker fails to verify - if (!apiChecker.isUnderLimit(account)) - return false; - } - return true; + apiChecker.checkLimit(account); + } } + private boolean doesCommandExist(String apiName) { for (APIChecker apiChecker : _apiAccessCheckers) { // If any checker has api info on the command, return true diff --git a/server/src/com/cloud/configuration/Config.java b/server/src/com/cloud/configuration/Config.java index ae7651c846e..e6bf3d543de 100755 --- a/server/src/com/cloud/configuration/Config.java +++ b/server/src/com/cloud/configuration/Config.java @@ -361,9 +361,7 @@ public enum Config { null, "Limits number of snapshots that can be handled by the host concurrently; default is NULL - unlimited", null), // API throttling - ApiLimitInterval("Advanced", ManagementServer.class, Long.class, "api.throttling.interval", "1", "The default time interval in seconds used to set account based api limit", null), - ApiLimitMax("Advanced", ManagementServer.class, Long.class, "api.throttling.max", "25", "The max number of API requests within api.throttling.interval duration", null), - ApiLimitEnabled("Advanced", ManagementServer.class, Boolean.class, "api.throttling.enabled", "true", "If true, api throttline feature is enabled", "true,false"); + ApiLimitEnabled("Advanced", ManagementServer.class, Boolean.class, "api.throttling.enable", "true", "If true, api throttline feature is enabled", "true,false"); private final String _category; private final Class _componentClass; diff --git a/server/test/com/cloud/api/ListPerfTest.java b/server/test/com/cloud/api/ListPerfTest.java index eb98d9187fe..e5d277a314f 100644 --- a/server/test/com/cloud/api/ListPerfTest.java +++ b/server/test/com/cloud/api/ListPerfTest.java @@ -17,6 +17,9 @@ package com.cloud.api; import java.util.HashMap; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; import org.junit.Before; import org.junit.Test; @@ -163,6 +166,57 @@ public class ListPerfTest extends APITest { } + @Test + public void testMultiListAccounts() throws Exception { + // log in using normal user + login("demo", "password"); + // issue list Accounts calls + final HashMap params = new HashMap(); + params.put("response", "json"); + params.put("listAll", "true"); + params.put("sessionkey", sessionKey); + int clientCount = 6; + Runnable[] clients = new Runnable[clientCount]; + final boolean[] isUsable = new boolean[clientCount]; + final CountDownLatch startGate = new CountDownLatch(1); + + final CountDownLatch endGate = new CountDownLatch(clientCount); + + + for (int i = 0; i < isUsable.length; ++i) { + final int j = i; + clients[j] = new Runnable() { + + /** + * {@inheritDoc} + */ + @Override + public void run() { + try { + startGate.await(); + + System.out.println(sendRequest("listAccounts", params)); + + } catch (InterruptedException e) { + e.printStackTrace(); + } finally { + endGate.countDown(); + } + } + }; + } + + ExecutorService executor = Executors.newFixedThreadPool(clientCount); + + for (Runnable runnable : clients) { + executor.execute(runnable); + } + + startGate.countDown(); + + endGate.await(); + + } } diff --git a/setup/db/db/schema-40to410.sql b/setup/db/db/schema-40to410.sql index bf3fb303e5b..a6b102a057c 100644 --- a/setup/db/db/schema-40to410.sql +++ b/setup/db/db/schema-40to410.sql @@ -142,6 +142,8 @@ UPDATE `cloud`.`conditions` set uuid=id WHERE uuid is NULL; INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Advanced', 'DEFAULT', 'management-server', '"detail.batch.query.size"', '2000', 'Default entity detail batch query size for listing'); +INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Advanced', 'DEFAULT', 'management-server', 'api.throttling.enabled', 'true, 'enable api rate limiting'); + --- DB views for list api --- use cloud; From ec3dd71adf9eda87063f956bcda99b786b3dedc3 Mon Sep 17 00:00:00 2001 From: Min Chen Date: Mon, 14 Jan 2013 17:19:35 -0800 Subject: [PATCH 12/80] Configure ApiRateLimit adapter. --- client/tomcatconf/components.xml.in | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/client/tomcatconf/components.xml.in b/client/tomcatconf/components.xml.in index dcff94a77e0..630bd9769b2 100755 --- a/client/tomcatconf/components.xml.in +++ b/client/tomcatconf/components.xml.in @@ -57,7 +57,11 @@ under the License. - + + 1 + 25 + 50000 + @@ -183,11 +187,7 @@ under the License. - - 1 - 25 - 50000 - + From a0ade283b7a92af4a8ca402a04c80a7200092bd7 Mon Sep 17 00:00:00 2001 From: Hugo Trippaers Date: Thu, 10 Jan 2013 18:30:07 +0100 Subject: [PATCH 13/80] Summary: Add initial support for OpenVswitch to the KVM hypervisor Create OvsVifDriver to deal with openvswitch specifics for plugging intefaces Create a parameter to set the bridge type to use in LibvirtComputingResource. Create several functions to get bridge information from openvswitch Add a check to detect the libvirt version and throw an exception when the version is to low ( < 0.9.11 ) Fix classpath loading in Script.findScript to deal with missing path separators at the end. Add notification to the BridgeVifDriver that lswitch broadcast type is not supported. --- .../kvm/resource/BridgeVifDriver.java | 3 + .../resource/LibvirtComputingResource.java | 97 +++++++- .../hypervisor/kvm/resource/LibvirtVMDef.java | 25 ++ .../hypervisor/kvm/resource/OvsVifDriver.java | 213 ++++++++++++++++++ utils/src/com/cloud/utils/script/Script.java | 20 +- 5 files changed, 348 insertions(+), 10 deletions(-) create mode 100644 plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/BridgeVifDriver.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/BridgeVifDriver.java index e6f2f7f376a..031721e8a3d 100644 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/BridgeVifDriver.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/BridgeVifDriver.java @@ -85,6 +85,9 @@ public class BridgeVifDriver extends VifDriverBase { URI broadcastUri = nic.getBroadcastUri(); vlanId = broadcastUri.getHost(); } + else if (nic.getBroadcastType() == Networks.BroadcastDomainType.Lswitch) { + throw new InternalErrorException("Nicira NVP Logicalswitches are not supported by the BridgeVifDriver"); + } String trafficLabel = nic.getName(); if (nic.getType() == Networks.TrafficType.Guest) { if (nic.getBroadcastType() == Networks.BroadcastDomainType.Vlan diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java index b52e2d8a0b0..fade750c5f8 100755 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java @@ -362,10 +362,16 @@ public class LibvirtComputingResource extends ServerResourceBase implements private String _pingTestPath; private int _dom0MinMem; + + protected enum BridgeType { + NATIVE, OPENVSWITCH + } protected enum defineOps { UNDEFINE_VM, DEFINE_VM } + + protected BridgeType _bridgeType; private String getEndIpFromStartIp(String startIp, int numIps) { String[] tokens = startIp.split("[.]"); @@ -474,6 +480,14 @@ public class LibvirtComputingResource extends ServerResourceBase implements if (storageScriptsDir == null) { storageScriptsDir = getDefaultStorageScriptsDir(); } + + String bridgeType = (String) params.get("network.bridge.type"); + if (bridgeType == null) { + _bridgeType = BridgeType.NATIVE; + } + else { + _bridgeType = BridgeType.valueOf(bridgeType.toUpperCase()); + } params.put("domr.scripts.dir", domrScriptsDir); @@ -650,11 +664,19 @@ public class LibvirtComputingResource extends ServerResourceBase implements LibvirtConnection.initialize(_hypervisorURI); Connect conn = null; - try { - conn = LibvirtConnection.getConnection(); - } catch (LibvirtException e) { - throw new CloudRuntimeException(e.getMessage()); - } + try { + conn = LibvirtConnection.getConnection(); + + if (_bridgeType == BridgeType.OPENVSWITCH) { + if (conn.getLibVirVersion() < (9 * 1000 + 11)) { + throw new ConfigurationException( + "LibVirt version 0.9.11 required for openvswitch support, but version " + + conn.getLibVirVersion() + " detected"); + } + } + } catch (LibvirtException e) { + throw new CloudRuntimeException(e.getMessage()); + } /* Does node support HVM guest? If not, exit */ if (!IsHVMEnabled(conn)) { @@ -697,7 +719,15 @@ public class LibvirtComputingResource extends ServerResourceBase implements } } - getPifs(); + switch (_bridgeType) { + case NATIVE: + getPifs(); + break; + case OPENVSWITCH: + getOvsPifs(); + break; + } + if (_pifs.get("private") == null) { s_logger.debug("Failed to get private nic name"); throw new ConfigurationException("Failed to get private nic name"); @@ -796,6 +826,26 @@ public class LibvirtComputingResource extends ServerResourceBase implements } s_logger.debug("done looking for pifs, no more bridges"); } + + private void getOvsPifs() { + String cmdout = Script.runSimpleBashScript("ovs-vsctl list-br | sed '{:q;N;s/\\n/%/g;t q}'"); + s_logger.debug("cmdout was " + cmdout); + List bridges = Arrays.asList(cmdout.split("%")); + for (String bridge : bridges) { + s_logger.debug("looking for pif for bridge " + bridge); + //String pif = getOvsPif(bridge); + // Not really interested in the pif name at this point for ovs bridges + String pif = bridge; + if(_publicBridgeName != null && bridge.equals(_publicBridgeName)){ + _pifs.put("public", pif); + } + if (_guestBridgeName != null && bridge.equals(_guestBridgeName)) { + _pifs.put("private", pif); + } + _pifs.put(bridge, pif); + } + s_logger.debug("done looking for pifs, no more bridges"); + } private String getPif(String bridge) { String pif = Script.runSimpleBashScript("brctl show | grep " + bridge + " | awk '{print $4}'"); @@ -808,11 +858,29 @@ public class LibvirtComputingResource extends ServerResourceBase implements return pif; } + private String getOvsPif(String bridge) { + String pif = Script.runSimpleBashScript("ovs-vsctl list-ports " + bridge); + return pif; + } + private boolean checkNetwork(String networkName) { if (networkName == null) { return true; } + if (_bridgeType == BridgeType.OPENVSWITCH) { + return checkOvsNetwork(networkName); + } + else { + return checkBridgeNetwork(networkName); + } + } + + private boolean checkBridgeNetwork(String networkName) { + if (networkName == null) { + return true; + } + String name = Script.runSimpleBashScript("brctl show | grep " + networkName + " | awk '{print $4}'"); if (name == null) { @@ -821,6 +889,23 @@ public class LibvirtComputingResource extends ServerResourceBase implements return true; } } + + private boolean checkOvsNetwork(String networkName) { + s_logger.debug("Checking if network " + networkName + " exists as openvswitch bridge"); + if (networkName == null) { + return true; + } + + Script command = new Script("/bin/sh", _timeout); + command.add("-c"); + command.add("ovs-vsctl br-exists " + networkName); + String result = command.execute(null); + if ("Ok".equals(result)) { + return true; + } else { + return false; + } + } private String getVnetId(String vnetId) { return vnetId; diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtVMDef.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtVMDef.java index ba6c715e455..17f6eef0b8e 100644 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtVMDef.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtVMDef.java @@ -646,6 +646,8 @@ public class LibvirtVMDef { private String _ipAddr; private String _scriptPath; private nicModel _model; + private String _virtualPortType; + private String _virtualPortInterfaceId; public void defBridgeNet(String brName, String targetBrName, String macAddr, nicModel model) { @@ -695,6 +697,22 @@ public class LibvirtVMDef { public String getMacAddress() { return _macAddr; } + + public void setVirtualPortType(String virtualPortType) { + _virtualPortType = virtualPortType; + } + + public String getVirtualPortType() { + return _virtualPortType; + } + + public void setVirtualPortInterfaceId(String virtualPortInterfaceId) { + _virtualPortInterfaceId = virtualPortInterfaceId; + } + + public String getVirtualPortInterfaceId() { + return _virtualPortInterfaceId; + } @Override public String toString() { @@ -714,6 +732,13 @@ public class LibvirtVMDef { if (_model != null) { netBuilder.append("\n"); } + if (_virtualPortType != null) { + netBuilder.append("\n"); + if (_virtualPortInterfaceId != null) { + netBuilder.append("\n"); + } + netBuilder.append("\n"); + } netBuilder.append("\n"); return netBuilder.toString(); } diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java new file mode 100644 index 00000000000..6c3e4963ec5 --- /dev/null +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java @@ -0,0 +1,213 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package com.cloud.hypervisor.kvm.resource; + +import java.net.URI; +import java.util.Map; + +import javax.naming.ConfigurationException; + +import org.apache.log4j.Logger; +import org.libvirt.LibvirtException; + +import com.cloud.agent.api.to.NicTO; +import com.cloud.exception.InternalErrorException; +import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.InterfaceDef; +import com.cloud.network.Networks; +import com.cloud.utils.NumbersUtil; +import com.cloud.utils.net.NetUtils; +import com.cloud.utils.script.OutputInterpreter; +import com.cloud.utils.script.Script; + +public class OvsVifDriver extends VifDriverBase { + private static final Logger s_logger = Logger + .getLogger(BridgeVifDriver.class); + private int _timeout; + private String _modifyVlanPath; + + @Override + public void configure(Map params) throws ConfigurationException { + super.configure(params); + + String networkScriptsDir = (String) params.get("network.scripts.dir"); + if (networkScriptsDir == null) { + networkScriptsDir = "scripts/vm/network/vnet"; + } + + String value = (String) params.get("scripts.timeout"); + _timeout = NumbersUtil.parseInt(value, 30 * 60) * 1000; + + _modifyVlanPath = Script.findScript(networkScriptsDir, "modifyvlan.sh"); + if (_modifyVlanPath == null) { + throw new ConfigurationException("Unable to find modifyvlan.sh"); + } + + createControlNetwork(_bridges.get("linklocal")); + } + + @Override + public InterfaceDef plug(NicTO nic, String guestOsType) + throws InternalErrorException, LibvirtException { + s_logger.debug("plugging nic=" + nic); + + LibvirtVMDef.InterfaceDef intf = new LibvirtVMDef.InterfaceDef(); + intf.setVirtualPortType("openvswitch"); + + String vlanId = null; + String logicalSwitchUuid = null; + if (nic.getBroadcastType() == Networks.BroadcastDomainType.Vlan) { + URI broadcastUri = nic.getBroadcastUri(); + vlanId = broadcastUri.getHost(); + } + else if (nic.getBroadcastType() == Networks.BroadcastDomainType.Lswitch) { + logicalSwitchUuid = nic.getBroadcastUri().getSchemeSpecificPart(); + } + String trafficLabel = nic.getName(); + if (nic.getType() == Networks.TrafficType.Guest) { + if (nic.getBroadcastType() == Networks.BroadcastDomainType.Vlan + && !vlanId.equalsIgnoreCase("untagged")) { + if(trafficLabel != null && !trafficLabel.isEmpty()) { + s_logger.debug("creating a vlan dev and bridge for guest traffic per traffic label " + trafficLabel); + String brName = createVlanBr(vlanId, _pifs.get(trafficLabel)); + intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType)); + } else { + String brName = createVlanBr(vlanId, _pifs.get("private")); + intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType)); + } + } else if (nic.getBroadcastType() == Networks.BroadcastDomainType.Lswitch) { + s_logger.debug("nic " + nic + " needs to be connected to LogicalSwitch " + logicalSwitchUuid); + intf.setVirtualPortInterfaceId(nic.getUuid()); + String brName = (trafficLabel != null && !trafficLabel.isEmpty()) ? _pifs.get(trafficLabel) : _pifs.get("private"); + intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType)); + } + else { + intf.defBridgeNet(_bridges.get("guest"), null, nic.getMac(), getGuestNicModel(guestOsType)); + } + } else if (nic.getType() == Networks.TrafficType.Control) { + /* Make sure the network is still there */ + createControlNetwork(_bridges.get("linklocal")); + intf.defBridgeNet(_bridges.get("linklocal"), null, nic.getMac(), getGuestNicModel(guestOsType)); + } else if (nic.getType() == Networks.TrafficType.Public) { + if (nic.getBroadcastType() == Networks.BroadcastDomainType.Vlan + && !vlanId.equalsIgnoreCase("untagged")) { + if(trafficLabel != null && !trafficLabel.isEmpty()){ + s_logger.debug("creating a vlan dev and bridge for public traffic per traffic label " + trafficLabel); + String brName = createVlanBr(vlanId, _pifs.get(trafficLabel)); + intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType)); + } else { + String brName = createVlanBr(vlanId, _pifs.get("public")); + intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType)); + } + } else { + intf.defBridgeNet(_bridges.get("public"), null, nic.getMac(), getGuestNicModel(guestOsType)); + } + } else if (nic.getType() == Networks.TrafficType.Management) { + intf.defBridgeNet(_bridges.get("private"), null, nic.getMac(), getGuestNicModel(guestOsType)); + } else if (nic.getType() == Networks.TrafficType.Storage) { + String storageBrName = nic.getName() == null ? _bridges.get("private") + : nic.getName(); + intf.defBridgeNet(storageBrName, null, nic.getMac(), getGuestNicModel(guestOsType)); + } + return intf; + } + + @Override + public void unplug(InterfaceDef iface) { + // Libvirt apparently takes care of this, see BridgeVifDriver unplug + } + + private String setVnetBrName(String pifName, String vnetId) { + String brName = "br" + pifName + "-"+ vnetId; + String oldStyleBrName = "cloudVirBr" + vnetId; + + if (isBridgeExists(oldStyleBrName)) { + s_logger.info("Using old style bridge name for vlan " + vnetId + " because existing bridge " + oldStyleBrName + " was found"); + brName = oldStyleBrName; + } + + return brName; + } + + private String createVlanBr(String vlanId, String nic) + throws InternalErrorException { + String brName = setVnetBrName(nic, vlanId); + createVnet(vlanId, nic, brName); + return brName; + } + + private void createVnet(String vnetId, String pif, String brName) + throws InternalErrorException { + final Script command = new Script(_modifyVlanPath, _timeout, s_logger); + command.add("-v", vnetId); + command.add("-p", pif); + command.add("-b", brName); + command.add("-o", "add"); + + final String result = command.execute(); + if (result != null) { + throw new InternalErrorException("Failed to create vnet " + vnetId + + ": " + result); + } + } + + private void deleteExitingLinkLocalRoutTable(String linkLocalBr) { + Script command = new Script("/bin/bash", _timeout); + command.add("-c"); + command.add("ip route | grep " + NetUtils.getLinkLocalCIDR()); + OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser(); + String result = command.execute(parser); + boolean foundLinkLocalBr = false; + if (result == null && parser.getLines() != null) { + String[] lines = parser.getLines().split("\\n"); + for (String line : lines) { + String[] tokens = line.split(" "); + if (!tokens[2].equalsIgnoreCase(linkLocalBr)) { + Script.runSimpleBashScript("ip route del " + NetUtils.getLinkLocalCIDR()); + } else { + foundLinkLocalBr = true; + } + } + } + if (!foundLinkLocalBr) { + Script.runSimpleBashScript("ifconfig " + linkLocalBr + " 169.254.0.1;" + "ip route add " + + NetUtils.getLinkLocalCIDR() + " dev " + linkLocalBr + " src " + NetUtils.getLinkLocalGateway()); + } + } + + private void createControlNetwork(String privBrName) { + deleteExitingLinkLocalRoutTable(privBrName); + if (!isBridgeExists(privBrName)) { + Script.runSimpleBashScript("ovs-vsctl add-br " + privBrName + "; ifconfig " + privBrName + " up; ifconfig " + + privBrName + " 169.254.0.1", _timeout); + } + + } + + private boolean isBridgeExists(String bridgeName) { + Script command = new Script("/bin/sh", _timeout); + command.add("-c"); + command.add("ovs-vsctl br-exists " + bridgeName); + String result = command.execute(null); + if ("Ok".equals(result)) { + return true; + } else { + return false; + } + } +} diff --git a/utils/src/com/cloud/utils/script/Script.java b/utils/src/com/cloud/utils/script/Script.java index 1444f83f425..d82d1d00957 100755 --- a/utils/src/com/cloud/utils/script/Script.java +++ b/utils/src/com/cloud/utils/script/Script.java @@ -195,7 +195,7 @@ public class Script implements Callable { } Task task = null; - if (interpreter.drain()) { + if (interpreter != null && interpreter.drain()) { task = new Task(interpreter, ir); s_executors.execute(task); } @@ -204,8 +204,13 @@ public class Script implements Callable { try { if (_process.waitFor() == 0) { _logger.debug("Execution is successful."); - - return interpreter.drain() ? task.getResult() : interpreter.interpret(ir); + if (interpreter != null) { + return interpreter.drain() ? task.getResult() : interpreter.interpret(ir); + } + else { + // null return is ok apparently + return (_process.exitValue() == 0) ? "Ok" : "Failed, exit code " + _process.exitValue(); + } } else { break; } @@ -239,7 +244,14 @@ public class Script implements Callable { BufferedReader reader = new BufferedReader(new InputStreamReader(_process.getInputStream()), 128); - String error = interpreter.processError(reader); + String error; + if (interpreter != null) { + error = interpreter.processError(reader); + } + else { + error = "Non zero exit code : " + _process.exitValue(); + } + if (_logger.isDebugEnabled()) { _logger.debug(error); } From 3d570c7647c9dcfb214435779c3eaaa918554dbd Mon Sep 17 00:00:00 2001 From: Hugo Trippaers Date: Fri, 11 Jan 2013 17:04:32 +0100 Subject: [PATCH 14/80] Summary: Add vlan configuration to the network inteface definition Add xml piece for defining vlans Set vlan tag in the libvirt definition for the network inteface --- .../hypervisor/kvm/resource/LibvirtVMDef.java | 14 ++++++- .../hypervisor/kvm/resource/OvsVifDriver.java | 38 ++++--------------- 2 files changed, 21 insertions(+), 31 deletions(-) diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtVMDef.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtVMDef.java index 17f6eef0b8e..df277780aa3 100644 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtVMDef.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtVMDef.java @@ -648,6 +648,7 @@ public class LibvirtVMDef { private nicModel _model; private String _virtualPortType; private String _virtualPortInterfaceId; + private int _vlanTag = -1; public void defBridgeNet(String brName, String targetBrName, String macAddr, nicModel model) { @@ -713,7 +714,15 @@ public class LibvirtVMDef { public String getVirtualPortInterfaceId() { return _virtualPortInterfaceId; } - + + public void setVlanTag(int vlanTag) { + _vlanTag = vlanTag; + } + + public int getVlanTag() { + return _vlanTag; + } + @Override public String toString() { StringBuilder netBuilder = new StringBuilder(); @@ -739,6 +748,9 @@ public class LibvirtVMDef { } netBuilder.append("\n"); } + if (_vlanTag != -1) { + netBuilder.append("\n\n"); + } netBuilder.append("\n"); return netBuilder.toString(); } diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java index 6c3e4963ec5..52fc29e5387 100644 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java @@ -84,11 +84,11 @@ public class OvsVifDriver extends VifDriverBase { && !vlanId.equalsIgnoreCase("untagged")) { if(trafficLabel != null && !trafficLabel.isEmpty()) { s_logger.debug("creating a vlan dev and bridge for guest traffic per traffic label " + trafficLabel); - String brName = createVlanBr(vlanId, _pifs.get(trafficLabel)); - intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType)); + intf.defBridgeNet(_pifs.get(trafficLabel), null, nic.getMac(), getGuestNicModel(guestOsType)); + intf.setVlanTag(Integer.parseInt(vlanId)); } else { - String brName = createVlanBr(vlanId, _pifs.get("private")); - intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType)); + intf.defBridgeNet(_pifs.get("private"), null, nic.getMac(), getGuestNicModel(guestOsType)); + intf.setVlanTag(Integer.parseInt(vlanId)); } } else if (nic.getBroadcastType() == Networks.BroadcastDomainType.Lswitch) { s_logger.debug("nic " + nic + " needs to be connected to LogicalSwitch " + logicalSwitchUuid); @@ -108,11 +108,11 @@ public class OvsVifDriver extends VifDriverBase { && !vlanId.equalsIgnoreCase("untagged")) { if(trafficLabel != null && !trafficLabel.isEmpty()){ s_logger.debug("creating a vlan dev and bridge for public traffic per traffic label " + trafficLabel); - String brName = createVlanBr(vlanId, _pifs.get(trafficLabel)); - intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType)); + intf.defBridgeNet(_pifs.get(trafficLabel), null, nic.getMac(), getGuestNicModel(guestOsType)); + intf.setVlanTag(Integer.parseInt(vlanId)); } else { - String brName = createVlanBr(vlanId, _pifs.get("public")); - intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType)); + intf.defBridgeNet(_pifs.get("public"), null, nic.getMac(), getGuestNicModel(guestOsType)); + intf.setVlanTag(Integer.parseInt(vlanId)); } } else { intf.defBridgeNet(_bridges.get("public"), null, nic.getMac(), getGuestNicModel(guestOsType)); @@ -143,28 +143,6 @@ public class OvsVifDriver extends VifDriverBase { return brName; } - - private String createVlanBr(String vlanId, String nic) - throws InternalErrorException { - String brName = setVnetBrName(nic, vlanId); - createVnet(vlanId, nic, brName); - return brName; - } - - private void createVnet(String vnetId, String pif, String brName) - throws InternalErrorException { - final Script command = new Script(_modifyVlanPath, _timeout, s_logger); - command.add("-v", vnetId); - command.add("-p", pif); - command.add("-b", brName); - command.add("-o", "add"); - - final String result = command.execute(); - if (result != null) { - throw new InternalErrorException("Failed to create vnet " + vnetId - + ": " + result); - } - } private void deleteExitingLinkLocalRoutTable(String linkLocalBr) { Script command = new Script("/bin/bash", _timeout); From 68523e641fa323e1303bfc7499a524b0475fa55f Mon Sep 17 00:00:00 2001 From: Hugo Trippaers Date: Thu, 10 Jan 2013 18:30:07 +0100 Subject: [PATCH 15/80] Summary: Add initial support for OpenVswitch to the KVM hypervisor Create OvsVifDriver to deal with openvswitch specifics for plugging intefaces Create a parameter to set the bridge type to use in LibvirtComputingResource. Create several functions to get bridge information from openvswitch Add a check to detect the libvirt version and throw an exception when the version is to low ( < 0.9.11 ) Fix classpath loading in Script.findScript to deal with missing path separators at the end. Add notification to the BridgeVifDriver that lswitch broadcast type is not supported. --- .../cloud/hypervisor/kvm/resource/OvsVifDriver.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java index 52fc29e5387..d8b80e94f45 100644 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java @@ -84,11 +84,11 @@ public class OvsVifDriver extends VifDriverBase { && !vlanId.equalsIgnoreCase("untagged")) { if(trafficLabel != null && !trafficLabel.isEmpty()) { s_logger.debug("creating a vlan dev and bridge for guest traffic per traffic label " + trafficLabel); - intf.defBridgeNet(_pifs.get(trafficLabel), null, nic.getMac(), getGuestNicModel(guestOsType)); - intf.setVlanTag(Integer.parseInt(vlanId)); + String brName = createVlanBr(vlanId, _pifs.get(trafficLabel)); + intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType)); } else { - intf.defBridgeNet(_pifs.get("private"), null, nic.getMac(), getGuestNicModel(guestOsType)); - intf.setVlanTag(Integer.parseInt(vlanId)); + String brName = createVlanBr(vlanId, _pifs.get("private")); + intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType)); } } else if (nic.getBroadcastType() == Networks.BroadcastDomainType.Lswitch) { s_logger.debug("nic " + nic + " needs to be connected to LogicalSwitch " + logicalSwitchUuid); @@ -144,7 +144,7 @@ public class OvsVifDriver extends VifDriverBase { return brName; } - private void deleteExitingLinkLocalRoutTable(String linkLocalBr) { + private void deleteExitingLinkLocalRoutTable(String linkLocalBr) { Script command = new Script("/bin/bash", _timeout); command.add("-c"); command.add("ip route | grep " + NetUtils.getLinkLocalCIDR()); From e0ecf7b834d88d8b50064eba0e149e67bdf2de1e Mon Sep 17 00:00:00 2001 From: Hugo Trippaers Date: Fri, 11 Jan 2013 17:04:32 +0100 Subject: [PATCH 16/80] Summary: Add vlan configuration to the network inteface definition Add xml piece for defining vlans Set vlan tag in the libvirt definition for the network inteface --- .../com/cloud/hypervisor/kvm/resource/OvsVifDriver.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java index d8b80e94f45..5b8fab14c5d 100644 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java @@ -84,11 +84,11 @@ public class OvsVifDriver extends VifDriverBase { && !vlanId.equalsIgnoreCase("untagged")) { if(trafficLabel != null && !trafficLabel.isEmpty()) { s_logger.debug("creating a vlan dev and bridge for guest traffic per traffic label " + trafficLabel); - String brName = createVlanBr(vlanId, _pifs.get(trafficLabel)); - intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType)); + intf.defBridgeNet(_pifs.get(trafficLabel), null, nic.getMac(), getGuestNicModel(guestOsType)); + intf.setVlanTag(Integer.parseInt(vlanId)); } else { - String brName = createVlanBr(vlanId, _pifs.get("private")); - intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType)); + intf.defBridgeNet(_pifs.get("private"), null, nic.getMac(), getGuestNicModel(guestOsType)); + intf.setVlanTag(Integer.parseInt(vlanId)); } } else if (nic.getBroadcastType() == Networks.BroadcastDomainType.Lswitch) { s_logger.debug("nic " + nic + " needs to be connected to LogicalSwitch " + logicalSwitchUuid); From 1ceecc92c88c84b99c99547f5c086657ec26f8d7 Mon Sep 17 00:00:00 2001 From: Hugo Trippaers Date: Mon, 14 Jan 2013 16:16:19 +0100 Subject: [PATCH 17/80] Summary: Fix logic error Should if "if the username is not cloud AND developer is not true, then report an error" --- server/src/com/cloud/server/ConfigurationServerImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/src/com/cloud/server/ConfigurationServerImpl.java b/server/src/com/cloud/server/ConfigurationServerImpl.java index b25c63f6d7f..7e5f42445d5 100755 --- a/server/src/com/cloud/server/ConfigurationServerImpl.java +++ b/server/src/com/cloud/server/ConfigurationServerImpl.java @@ -549,7 +549,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { String username = System.getProperty("user.name"); Boolean devel = Boolean.valueOf(_configDao.getValue("developer")); - if (!username.equalsIgnoreCase("cloud") || !devel) { + if (!username.equalsIgnoreCase("cloud") && !devel) { s_logger.warn("Systemvm keypairs could not be set. Management server should be run as cloud user, or in development mode."); return; } From 87fe64695305d6a2c505f757ab7607b765c313b7 Mon Sep 17 00:00:00 2001 From: Hugo Trippaers Date: Mon, 14 Jan 2013 17:09:49 +0100 Subject: [PATCH 18/80] Summary: small fix causing trouble when shutting down virtual machines --- .../cloud/hypervisor/kvm/storage/KVMStoragePoolManager.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/storage/KVMStoragePoolManager.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/storage/KVMStoragePoolManager.java index ac611275e5a..1af2ed22c27 100644 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/storage/KVMStoragePoolManager.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/storage/KVMStoragePoolManager.java @@ -38,6 +38,10 @@ public class KVMStoragePoolManager { private final Map _storageMapper = new HashMap(); private StorageAdaptor getStorageAdaptor(StoragePoolType type) { + // type can be null: LibVirtComputingResource:3238 + if (type == null) { + return _storageMapper.get("libvirt"); + } StorageAdaptor adaptor = _storageMapper.get(type.toString()); if (adaptor == null) { // LibvirtStorageAdaptor is selected by default From 4267a3fc7ce15e85273eb88ce2c5a8cd2b53f72e Mon Sep 17 00:00:00 2001 From: Hugo Trippaers Date: Mon, 14 Jan 2013 17:17:06 +0100 Subject: [PATCH 19/80] Summary: copy/paste error --- .../kvm/src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java index 5b8fab14c5d..0ff05a913e1 100644 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java @@ -37,7 +37,7 @@ import com.cloud.utils.script.Script; public class OvsVifDriver extends VifDriverBase { private static final Logger s_logger = Logger - .getLogger(BridgeVifDriver.class); + .getLogger(OvsVifDriver.class); private int _timeout; private String _modifyVlanPath; From 9f00302ad3d8229f2e6bd786b3c7749d8c264712 Mon Sep 17 00:00:00 2001 From: Hugo Trippaers Date: Mon, 14 Jan 2013 18:43:15 +0100 Subject: [PATCH 20/80] Summary: Polish and shine Document the used options in agent.properties Default the bridge driver to something sensible based on the configuration of the bridge type. --- agent/conf/agent.properties | 11 +++++++++++ .../kvm/resource/LibvirtComputingResource.java | 10 ++++++++-- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/agent/conf/agent.properties b/agent/conf/agent.properties index 27572b53653..74cfd1c21d6 100644 --- a/agent/conf/agent.properties +++ b/agent/conf/agent.properties @@ -69,3 +69,14 @@ domr.scripts.dir=scripts/network/domr/kvm # set the vm migrate speed, by default, it will try to guess the speed of the guest network # In MegaBytes per second #vm.migrate.speed=0 + +# set the type of bridge used on the hypervisor, this defines what commands the resource +# will use to setup networking. Currently supported NATIVE, OPENVSWITCH +#network.bridge.type=native + +# set the driver used to plug and unplug nics from the bridges +# a sensible default will be selected based on the network.bridge.type but can +# be overridden here. +# native = com.cloud.hypervisor.kvm.resource.BridgeVifDriver +# openvswitch = com.cloud.hypervisor.kvm.resource.OvsBridgeDriver +#libvirt.vif.driver=com.cloud.hypervisor.kvm.resource.BridgeVifDriver \ No newline at end of file diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java index fade750c5f8..1474d114619 100755 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java @@ -786,8 +786,14 @@ public class LibvirtComputingResource extends ServerResourceBase implements // Load the vif driver String vifDriverName = (String) params.get("libvirt.vif.driver"); if (vifDriverName == null) { - s_logger.info("No libvirt.vif.driver specififed. Defaults to BridgeVifDriver."); - vifDriverName = "com.cloud.hypervisor.kvm.resource.BridgeVifDriver"; + if (_bridgeType == BridgeType.OPENVSWITCH) { + s_logger.info("No libvirt.vif.driver specififed. Defaults to OvsVifDriver."); + vifDriverName = "com.cloud.hypervisor.kvm.resource.OvsVifDriver"; + } + else { + s_logger.info("No libvirt.vif.driver specififed. Defaults to BridgeVifDriver."); + vifDriverName = "com.cloud.hypervisor.kvm.resource.BridgeVifDriver"; + } } params.put("libvirt.computing.resource", (Object) this); From 2d69a1855de5110c57010e248f83d88607c668fe Mon Sep 17 00:00:00 2001 From: Hugo Trippaers Date: Tue, 15 Jan 2013 10:00:58 +0100 Subject: [PATCH 21/80] Summary: Begone pesky tabs --- .../kvm/resource/BridgeVifDriver.java | 2 +- .../resource/LibvirtComputingResource.java | 95 +++++++++---------- .../hypervisor/kvm/resource/LibvirtVMDef.java | 34 +++---- .../hypervisor/kvm/resource/OvsVifDriver.java | 46 +++++---- .../kvm/storage/KVMStoragePoolManager.java | 8 +- utils/src/com/cloud/utils/script/Script.java | 82 ++++++++-------- 6 files changed, 133 insertions(+), 134 deletions(-) diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/BridgeVifDriver.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/BridgeVifDriver.java index 031721e8a3d..3883c62fc97 100644 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/BridgeVifDriver.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/BridgeVifDriver.java @@ -86,7 +86,7 @@ public class BridgeVifDriver extends VifDriverBase { vlanId = broadcastUri.getHost(); } else if (nic.getBroadcastType() == Networks.BroadcastDomainType.Lswitch) { - throw new InternalErrorException("Nicira NVP Logicalswitches are not supported by the BridgeVifDriver"); + throw new InternalErrorException("Nicira NVP Logicalswitches are not supported by the BridgeVifDriver"); } String trafficLabel = nic.getName(); if (nic.getType() == Networks.TrafficType.Guest) { diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java index 1474d114619..03c5367fcdc 100755 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java @@ -364,7 +364,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements private int _dom0MinMem; protected enum BridgeType { - NATIVE, OPENVSWITCH + NATIVE, OPENVSWITCH } protected enum defineOps { @@ -483,10 +483,10 @@ public class LibvirtComputingResource extends ServerResourceBase implements String bridgeType = (String) params.get("network.bridge.type"); if (bridgeType == null) { - _bridgeType = BridgeType.NATIVE; + _bridgeType = BridgeType.NATIVE; } else { - _bridgeType = BridgeType.valueOf(bridgeType.toUpperCase()); + _bridgeType = BridgeType.valueOf(bridgeType.toUpperCase()); } params.put("domr.scripts.dir", domrScriptsDir); @@ -664,19 +664,18 @@ public class LibvirtComputingResource extends ServerResourceBase implements LibvirtConnection.initialize(_hypervisorURI); Connect conn = null; - try { - conn = LibvirtConnection.getConnection(); + try { + conn = LibvirtConnection.getConnection(); - if (_bridgeType == BridgeType.OPENVSWITCH) { - if (conn.getLibVirVersion() < (9 * 1000 + 11)) { - throw new ConfigurationException( - "LibVirt version 0.9.11 required for openvswitch support, but version " - + conn.getLibVirVersion() + " detected"); - } - } - } catch (LibvirtException e) { - throw new CloudRuntimeException(e.getMessage()); - } + if (_bridgeType == BridgeType.OPENVSWITCH) { + if (conn.getLibVirVersion() < (9 * 1000 + 11)) { + throw new ConfigurationException("LibVirt version 0.9.11 required for openvswitch support, but version " + + conn.getLibVirVersion() + " detected"); + } + } + } catch (LibvirtException e) { + throw new CloudRuntimeException(e.getMessage()); + } /* Does node support HVM guest? If not, exit */ if (!IsHVMEnabled(conn)) { @@ -720,14 +719,15 @@ public class LibvirtComputingResource extends ServerResourceBase implements } switch (_bridgeType) { - case NATIVE: - getPifs(); - break; case OPENVSWITCH: - getOvsPifs(); - break; + getOvsPifs(); + break; + case NATIVE: + default: + getPifs(); + break; } - + if (_pifs.get("private") == null) { s_logger.debug("Failed to get private nic name"); throw new ConfigurationException("Failed to get private nic name"); @@ -786,31 +786,29 @@ public class LibvirtComputingResource extends ServerResourceBase implements // Load the vif driver String vifDriverName = (String) params.get("libvirt.vif.driver"); if (vifDriverName == null) { - if (_bridgeType == BridgeType.OPENVSWITCH) { - s_logger.info("No libvirt.vif.driver specififed. Defaults to OvsVifDriver."); - vifDriverName = "com.cloud.hypervisor.kvm.resource.OvsVifDriver"; - } - else { - s_logger.info("No libvirt.vif.driver specififed. Defaults to BridgeVifDriver."); - vifDriverName = "com.cloud.hypervisor.kvm.resource.BridgeVifDriver"; - } + if (_bridgeType == BridgeType.OPENVSWITCH) { + s_logger.info("No libvirt.vif.driver specififed. Defaults to OvsVifDriver."); + vifDriverName = "com.cloud.hypervisor.kvm.resource.OvsVifDriver"; + } else { + s_logger.info("No libvirt.vif.driver specififed. Defaults to BridgeVifDriver."); + vifDriverName = "com.cloud.hypervisor.kvm.resource.BridgeVifDriver"; + } } params.put("libvirt.computing.resource", (Object) this); try { - Class clazz = Class.forName(vifDriverName); - _vifDriver = (VifDriver) clazz.newInstance(); - _vifDriver.configure(params); + Class clazz = Class.forName(vifDriverName); + _vifDriver = (VifDriver) clazz.newInstance(); + _vifDriver.configure(params); } catch (ClassNotFoundException e) { - throw new ConfigurationException("Unable to find class for libvirt.vif.driver " + e); + throw new ConfigurationException("Unable to find class for libvirt.vif.driver " + e); } catch (InstantiationException e) { - throw new ConfigurationException("Unable to instantiate class for libvirt.vif.driver " + e); + throw new ConfigurationException("Unable to instantiate class for libvirt.vif.driver " + e); } catch (Exception e) { - throw new ConfigurationException("Failed to initialize libvirt.vif.driver " + e); + throw new ConfigurationException("Failed to initialize libvirt.vif.driver " + e); } - return true; } @@ -834,15 +832,16 @@ public class LibvirtComputingResource extends ServerResourceBase implements } private void getOvsPifs() { - String cmdout = Script.runSimpleBashScript("ovs-vsctl list-br | sed '{:q;N;s/\\n/%/g;t q}'"); + String cmdout = Script.runSimpleBashScript("ovs-vsctl list-br | sed '{:q;N;s/\\n/%/g;t q}'"); s_logger.debug("cmdout was " + cmdout); List bridges = Arrays.asList(cmdout.split("%")); for (String bridge : bridges) { s_logger.debug("looking for pif for bridge " + bridge); - //String pif = getOvsPif(bridge); - // Not really interested in the pif name at this point for ovs bridges + // String pif = getOvsPif(bridge); + // Not really interested in the pif name at this point for ovs + // bridges String pif = bridge; - if(_publicBridgeName != null && bridge.equals(_publicBridgeName)){ + if (_publicBridgeName != null && bridge.equals(_publicBridgeName)) { _pifs.put("public", pif); } if (_guestBridgeName != null && bridge.equals(_guestBridgeName)) { @@ -850,7 +849,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements } _pifs.put(bridge, pif); } - s_logger.debug("done looking for pifs, no more bridges"); + s_logger.debug("done looking for pifs, no more bridges"); } private String getPif(String bridge) { @@ -875,10 +874,10 @@ public class LibvirtComputingResource extends ServerResourceBase implements } if (_bridgeType == BridgeType.OPENVSWITCH) { - return checkOvsNetwork(networkName); + return checkOvsNetwork(networkName); } else { - return checkBridgeNetwork(networkName); + return checkBridgeNetwork(networkName); } } @@ -897,11 +896,11 @@ public class LibvirtComputingResource extends ServerResourceBase implements } private boolean checkOvsNetwork(String networkName) { - s_logger.debug("Checking if network " + networkName + " exists as openvswitch bridge"); - if (networkName == null) { - return true; - } - + s_logger.debug("Checking if network " + networkName + " exists as openvswitch bridge"); + if (networkName == null) { + return true; + } + Script command = new Script("/bin/sh", _timeout); command.add("-c"); command.add("ovs-vsctl br-exists " + networkName); diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtVMDef.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtVMDef.java index df277780aa3..c02d8fc175a 100644 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtVMDef.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtVMDef.java @@ -700,27 +700,27 @@ public class LibvirtVMDef { } public void setVirtualPortType(String virtualPortType) { - _virtualPortType = virtualPortType; + _virtualPortType = virtualPortType; } - + public String getVirtualPortType() { - return _virtualPortType; + return _virtualPortType; } - + public void setVirtualPortInterfaceId(String virtualPortInterfaceId) { - _virtualPortInterfaceId = virtualPortInterfaceId; + _virtualPortInterfaceId = virtualPortInterfaceId; } - + public String getVirtualPortInterfaceId() { - return _virtualPortInterfaceId; + return _virtualPortInterfaceId; } - + public void setVlanTag(int vlanTag) { - _vlanTag = vlanTag; + _vlanTag = vlanTag; } - + public int getVlanTag() { - return _vlanTag; + return _vlanTag; } @Override @@ -742,14 +742,14 @@ public class LibvirtVMDef { netBuilder.append("\n"); } if (_virtualPortType != null) { - netBuilder.append("\n"); - if (_virtualPortInterfaceId != null) { - netBuilder.append("\n"); - } - netBuilder.append("\n"); + netBuilder.append("\n"); + if (_virtualPortInterfaceId != null) { + netBuilder.append("\n"); + } + netBuilder.append("\n"); } if (_vlanTag != -1) { - netBuilder.append("\n\n"); + netBuilder.append("\n\n"); } netBuilder.append("\n"); return netBuilder.toString(); diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java index 0ff05a913e1..04c29a856e0 100644 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java @@ -36,16 +36,15 @@ import com.cloud.utils.script.OutputInterpreter; import com.cloud.utils.script.Script; public class OvsVifDriver extends VifDriverBase { - private static final Logger s_logger = Logger - .getLogger(OvsVifDriver.class); + private static final Logger s_logger = Logger.getLogger(OvsVifDriver.class); private int _timeout; private String _modifyVlanPath; - @Override - public void configure(Map params) throws ConfigurationException { - super.configure(params); + @Override + public void configure(Map params) throws ConfigurationException { + super.configure(params); - String networkScriptsDir = (String) params.get("network.scripts.dir"); + String networkScriptsDir = (String) params.get("network.scripts.dir"); if (networkScriptsDir == null) { networkScriptsDir = "scripts/vm/network/vnet"; } @@ -58,12 +57,12 @@ public class OvsVifDriver extends VifDriverBase { throw new ConfigurationException("Unable to find modifyvlan.sh"); } - createControlNetwork(_bridges.get("linklocal")); - } - - @Override - public InterfaceDef plug(NicTO nic, String guestOsType) - throws InternalErrorException, LibvirtException { + createControlNetwork(_bridges.get("linklocal")); + } + + @Override + public InterfaceDef plug(NicTO nic, String guestOsType) + throws InternalErrorException, LibvirtException { s_logger.debug("plugging nic=" + nic); LibvirtVMDef.InterfaceDef intf = new LibvirtVMDef.InterfaceDef(); @@ -76,7 +75,7 @@ public class OvsVifDriver extends VifDriverBase { vlanId = broadcastUri.getHost(); } else if (nic.getBroadcastType() == Networks.BroadcastDomainType.Lswitch) { - logicalSwitchUuid = nic.getBroadcastUri().getSchemeSpecificPart(); + logicalSwitchUuid = nic.getBroadcastUri().getSchemeSpecificPart(); } String trafficLabel = nic.getName(); if (nic.getType() == Networks.TrafficType.Guest) { @@ -91,11 +90,11 @@ public class OvsVifDriver extends VifDriverBase { intf.setVlanTag(Integer.parseInt(vlanId)); } } else if (nic.getBroadcastType() == Networks.BroadcastDomainType.Lswitch) { - s_logger.debug("nic " + nic + " needs to be connected to LogicalSwitch " + logicalSwitchUuid); - intf.setVirtualPortInterfaceId(nic.getUuid()); - String brName = (trafficLabel != null && !trafficLabel.isEmpty()) ? _pifs.get(trafficLabel) : _pifs.get("private"); + s_logger.debug("nic " + nic + " needs to be connected to LogicalSwitch " + logicalSwitchUuid); + intf.setVirtualPortInterfaceId(nic.getUuid()); + String brName = (trafficLabel != null && !trafficLabel.isEmpty()) ? _pifs.get(trafficLabel) : _pifs.get("private"); intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType)); - } + } else { intf.defBridgeNet(_bridges.get("guest"), null, nic.getMac(), getGuestNicModel(guestOsType)); } @@ -127,11 +126,11 @@ public class OvsVifDriver extends VifDriverBase { return intf; } - @Override - public void unplug(InterfaceDef iface) { - // Libvirt apparently takes care of this, see BridgeVifDriver unplug - } - + @Override + public void unplug(InterfaceDef iface) { + // Libvirt apparently takes care of this, see BridgeVifDriver unplug + } + private String setVnetBrName(String pifName, String vnetId) { String brName = "br" + pifName + "-"+ vnetId; String oldStyleBrName = "cloudVirBr" + vnetId; @@ -167,14 +166,13 @@ public class OvsVifDriver extends VifDriverBase { NetUtils.getLinkLocalCIDR() + " dev " + linkLocalBr + " src " + NetUtils.getLinkLocalGateway()); } } - + private void createControlNetwork(String privBrName) { deleteExitingLinkLocalRoutTable(privBrName); if (!isBridgeExists(privBrName)) { Script.runSimpleBashScript("ovs-vsctl add-br " + privBrName + "; ifconfig " + privBrName + " up; ifconfig " + privBrName + " 169.254.0.1", _timeout); } - } private boolean isBridgeExists(String bridgeName) { diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/storage/KVMStoragePoolManager.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/storage/KVMStoragePoolManager.java index 1af2ed22c27..c2bfad9feef 100644 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/storage/KVMStoragePoolManager.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/storage/KVMStoragePoolManager.java @@ -38,10 +38,10 @@ public class KVMStoragePoolManager { private final Map _storageMapper = new HashMap(); private StorageAdaptor getStorageAdaptor(StoragePoolType type) { - // type can be null: LibVirtComputingResource:3238 - if (type == null) { - return _storageMapper.get("libvirt"); - } + // type can be null: LibVirtComputingResource:3238 + if (type == null) { + return _storageMapper.get("libvirt"); + } StorageAdaptor adaptor = _storageMapper.get(type.toString()); if (adaptor == null) { // LibvirtStorageAdaptor is selected by default diff --git a/utils/src/com/cloud/utils/script/Script.java b/utils/src/com/cloud/utils/script/Script.java index d82d1d00957..1e5aab45408 100755 --- a/utils/src/com/cloud/utils/script/Script.java +++ b/utils/src/com/cloud/utils/script/Script.java @@ -200,56 +200,58 @@ public class Script implements Callable { s_executors.execute(task); } - while (true) { - try { - if (_process.waitFor() == 0) { - _logger.debug("Execution is successful."); - if (interpreter != null) { - return interpreter.drain() ? task.getResult() : interpreter.interpret(ir); - } - else { - // null return is ok apparently - return (_process.exitValue() == 0) ? "Ok" : "Failed, exit code " + _process.exitValue(); - } - } else { - break; - } - } catch (InterruptedException e) { - if (!_isTimeOut) { - /* This is not timeout, we are interrupted by others, continue */ - _logger.debug("We are interrupted but it's not a timeout, just continue"); - continue; - } - - TimedOutLogger log = new TimedOutLogger(_process); - Task timedoutTask = new Task(log, ir); + while (true) { + try { + if (_process.waitFor() == 0) { + _logger.debug("Execution is successful."); + if (interpreter != null) { + return interpreter.drain() ? task.getResult() : interpreter.interpret(ir); + } else { + // null return is ok apparently + return (_process.exitValue() == 0) ? "Ok" : "Failed, exit code " + _process.exitValue(); + } + } else { + break; + } + } catch (InterruptedException e) { + if (!_isTimeOut) { + /* + * This is not timeout, we are interrupted by others, + * continue + */ + _logger.debug("We are interrupted but it's not a timeout, just continue"); + continue; + } - timedoutTask.run(); - if (!_passwordCommand) { - _logger.warn("Timed out: " + buildCommandLine(command) + ". Output is: " + timedoutTask.getResult()); - } else { - _logger.warn("Timed out: " + buildCommandLine(command)); - } + TimedOutLogger log = new TimedOutLogger(_process); + Task timedoutTask = new Task(log, ir); - return ERR_TIMEOUT; - } finally { - if (future != null) { - future.cancel(false); - } - Thread.interrupted(); - } - } + timedoutTask.run(); + if (!_passwordCommand) { + _logger.warn("Timed out: " + buildCommandLine(command) + ". Output is: " + timedoutTask.getResult()); + } else { + _logger.warn("Timed out: " + buildCommandLine(command)); + } - _logger.debug("Exit value is " + _process.exitValue()); + return ERR_TIMEOUT; + } finally { + if (future != null) { + future.cancel(false); + } + Thread.interrupted(); + } + } + + _logger.debug("Exit value is " + _process.exitValue()); BufferedReader reader = new BufferedReader(new InputStreamReader(_process.getInputStream()), 128); String error; if (interpreter != null) { - error = interpreter.processError(reader); + error = interpreter.processError(reader); } else { - error = "Non zero exit code : " + _process.exitValue(); + error = "Non zero exit code : " + _process.exitValue(); } if (_logger.isDebugEnabled()) { From 3698d64ba2457833d18eb2a5c275a55437ed4eba Mon Sep 17 00:00:00 2001 From: Min Chen Date: Tue, 15 Jan 2013 16:08:47 -0800 Subject: [PATCH 22/80] Use 429 Error code for API_LIMIT_EXCEED error due to latest Http status code in http://en.wikipedia.org/wiki/List_of_HTTP_status_codes#4xx_Client_Error --- api/src/org/apache/cloudstack/api/BaseCmd.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/api/src/org/apache/cloudstack/api/BaseCmd.java b/api/src/org/apache/cloudstack/api/BaseCmd.java index 80530421f18..ae8bb2f69a6 100644 --- a/api/src/org/apache/cloudstack/api/BaseCmd.java +++ b/api/src/org/apache/cloudstack/api/BaseCmd.java @@ -87,7 +87,7 @@ public abstract class BaseCmd { public static final int PARAM_ERROR = 431; public static final int UNSUPPORTED_ACTION_ERROR = 432; public static final int PAGE_LIMIT_EXCEED = 433; - public static final int API_LIMIT_EXCEED = 434; + public static final int API_LIMIT_EXCEED = 429; // Server error codes public static final int INTERNAL_ERROR = 530; From bdcfa1919b03665437490fab485809b6f74a8cd4 Mon Sep 17 00:00:00 2001 From: Min Chen Date: Wed, 16 Jan 2013 21:52:48 -0800 Subject: [PATCH 23/80] Clean up ApiServer, ApiServlet and ApiDispatcher in handling various exceptions, and Introduced ApiErrorCode to handle CloudStack API error code to standard Http code mapping. --- .../api/commands/CreatePrivateNetworkCmd.java | 8 +- .../api/commands/DestroyConsoleProxyCmd.java | 2 +- .../apache/cloudstack/api/ApiErrorCode.java | 59 +++++ .../org/apache/cloudstack/api/BaseCmd.java | 25 +- ...BaseUpdateTemplateOrIsoPermissionsCmd.java | 2 +- .../cloudstack/api/ServerApiException.java | 33 ++- .../admin/account/CreateAccountCmd.java | 2 +- .../admin/account/DeleteAccountCmd.java | 2 +- .../admin/account/DisableAccountCmd.java | 2 +- .../admin/account/EnableAccountCmd.java | 3 +- .../command/admin/account/LockAccountCmd.java | 2 +- .../admin/account/UpdateAccountCmd.java | 3 +- .../admin/autoscale/CreateCounterCmd.java | 3 +- .../admin/autoscale/DeleteCounterCmd.java | 5 +- .../command/admin/cluster/AddClusterCmd.java | 6 +- .../admin/cluster/DeleteClusterCmd.java | 3 +- .../admin/cluster/UpdateClusterCmd.java | 3 +- .../command/admin/config/UpdateCfgCmd.java | 3 +- .../UpdateHypervisorCapabilitiesCmd.java | 3 +- .../command/admin/domain/CreateDomainCmd.java | 2 +- .../command/admin/domain/DeleteDomainCmd.java | 2 +- .../command/admin/domain/UpdateDomainCmd.java | 2 +- .../api/command/admin/host/AddHostCmd.java | 5 +- .../admin/host/AddSecondaryStorageCmd.java | 4 +- .../admin/host/CancelMaintenanceCmd.java | 3 +- .../api/command/admin/host/DeleteHostCmd.java | 3 +- .../admin/host/PrepareForMaintenanceCmd.java | 3 +- .../command/admin/host/ReconnectHostCmd.java | 5 +- .../api/command/admin/host/UpdateHostCmd.java | 3 +- .../admin/network/AddNetworkDeviceCmd.java | 5 +- .../network/AddNetworkServiceProviderCmd.java | 5 +- .../network/CreateNetworkOfferingCmd.java | 2 +- .../network/CreatePhysicalNetworkCmd.java | 5 +- .../CreateStorageNetworkIpRangeCmd.java | 3 +- .../admin/network/DeleteNetworkDeviceCmd.java | 7 +- .../network/DeleteNetworkOfferingCmd.java | 3 +- .../DeleteNetworkServiceProviderCmd.java | 7 +- .../network/DeletePhysicalNetworkCmd.java | 2 +- .../DeleteStorageNetworkIpRangeCmd.java | 2 +- .../admin/network/ListNetworkDeviceCmd.java | 5 +- .../network/ListPhysicalNetworksCmd.java | 3 +- .../network/ListStorageNetworkIpRangeCmd.java | 2 +- .../network/UpdateNetworkOfferingCmd.java | 2 +- .../UpdateNetworkServiceProviderCmd.java | 3 +- .../UpdateStorageNetworkIpRangeCmd.java | 2 +- .../admin/offering/CreateDiskOfferingCmd.java | 3 +- .../offering/CreateServiceOfferingCmd.java | 3 +- .../admin/offering/DeleteDiskOfferingCmd.java | 3 +- .../offering/DeleteServiceOfferingCmd.java | 2 +- .../admin/offering/UpdateDiskOfferingCmd.java | 3 +- .../offering/UpdateServiceOfferingCmd.java | 2 +- .../api/command/admin/pod/CreatePodCmd.java | 2 +- .../api/command/admin/pod/DeletePodCmd.java | 3 +- .../api/command/admin/pod/UpdatePodCmd.java | 2 +- .../resource/UploadCustomCertificateCmd.java | 2 +- .../ConfigureVirtualRouterElementCmd.java | 3 +- .../router/CreateVirtualRouterElementCmd.java | 4 +- .../admin/router/DestroyRouterCmd.java | 3 +- .../command/admin/router/RebootRouterCmd.java | 2 +- .../command/admin/router/StartRouterCmd.java | 2 +- .../command/admin/router/StopRouterCmd.java | 3 +- .../admin/router/UpgradeRouterCmd.java | 2 +- .../api/command/admin/storage/AddS3Cmd.java | 5 +- .../CancelPrimaryStorageMaintenanceCmd.java | 3 +- .../admin/storage/CreateStoragePoolCmd.java | 8 +- .../command/admin/storage/DeletePoolCmd.java | 4 +- ...reparePrimaryStorageForMaintenanceCmd.java | 3 +- .../admin/storage/UpdateStoragePoolCmd.java | 2 +- .../api/command/admin/swift/AddSwiftCmd.java | 4 +- .../admin/systemvm/DestroySystemVmCmd.java | 2 +- .../admin/systemvm/MigrateSystemVMCmd.java | 11 +- .../admin/systemvm/RebootSystemVmCmd.java | 3 +- .../admin/systemvm/StartSystemVMCmd.java | 3 +- .../admin/systemvm/StopSystemVmCmd.java | 2 +- .../admin/systemvm/UpgradeSystemVMCmd.java | 2 +- .../admin/usage/AddTrafficTypeCmd.java | 5 +- .../admin/usage/DeleteTrafficTypeCmd.java | 3 +- .../admin/usage/UpdateTrafficTypeCmd.java | 3 +- .../api/command/admin/user/CreateUserCmd.java | 3 +- .../api/command/admin/user/DeleteUserCmd.java | 3 +- .../command/admin/user/DisableUserCmd.java | 3 +- .../api/command/admin/user/EnableUserCmd.java | 2 +- .../api/command/admin/user/LockUserCmd.java | 3 +- .../api/command/admin/user/UpdateUserCmd.java | 2 +- .../admin/vlan/CreateVlanIpRangeCmd.java | 6 +- .../admin/vlan/DeleteVlanIpRangeCmd.java | 3 +- .../api/command/admin/vm/AssignVMCmd.java | 4 +- .../api/command/admin/vm/MigrateVMCmd.java | 10 +- .../api/command/admin/vm/RecoverVMCmd.java | 3 +- .../admin/vpc/CreatePrivateGatewayCmd.java | 9 +- .../admin/vpc/CreateVPCOfferingCmd.java | 4 +- .../admin/vpc/DeletePrivateGatewayCmd.java | 3 +- .../admin/vpc/DeleteVPCOfferingCmd.java | 3 +- .../admin/vpc/UpdateVPCOfferingCmd.java | 2 +- .../api/command/admin/zone/CreateZoneCmd.java | 3 +- .../api/command/admin/zone/DeleteZoneCmd.java | 2 +- .../zone/MarkDefaultZoneForAccountCmd.java | 3 +- .../api/command/admin/zone/UpdateZoneCmd.java | 2 +- .../user/account/AddAccountToProjectCmd.java | 2 +- .../account/DeleteAccountFromProjectCmd.java | 2 +- .../user/address/AssociateIPAddrCmd.java | 9 +- .../user/address/DisassociateIPAddrCmd.java | 2 +- .../autoscale/CreateAutoScalePolicyCmd.java | 2 +- .../autoscale/CreateAutoScaleVmGroupCmd.java | 4 +- .../CreateAutoScaleVmProfileCmd.java | 3 +- .../user/autoscale/CreateConditionCmd.java | 3 +- .../autoscale/DeleteAutoScalePolicyCmd.java | 3 +- .../autoscale/DeleteAutoScaleVmGroupCmd.java | 3 +- .../DeleteAutoScaleVmProfileCmd.java | 3 +- .../user/autoscale/DeleteConditionCmd.java | 5 +- .../autoscale/DisableAutoScaleVmGroupCmd.java | 3 +- .../autoscale/EnableAutoScaleVmGroupCmd.java | 2 +- .../autoscale/UpdateAutoScalePolicyCmd.java | 3 +- .../autoscale/UpdateAutoScaleVmGroupCmd.java | 2 +- .../UpdateAutoScaleVmProfileCmd.java | 2 +- .../user/firewall/CreateFirewallRuleCmd.java | 7 +- .../firewall/CreatePortForwardingRuleCmd.java | 4 +- .../user/firewall/DeleteFirewallRuleCmd.java | 2 +- .../firewall/DeletePortForwardingRuleCmd.java | 2 +- .../firewall/UpdatePortForwardingRuleCmd.java | 2 +- .../api/command/user/iso/AttachIsoCmd.java | 5 +- .../api/command/user/iso/DeleteIsoCmd.java | 3 +- .../api/command/user/iso/DetachIsoCmd.java | 3 +- .../api/command/user/iso/ExtractIsoCmd.java | 4 +- .../api/command/user/iso/RegisterIsoCmd.java | 2 +- .../api/command/user/iso/UpdateIsoCmd.java | 3 +- .../AssignToLoadBalancerRuleCmd.java | 3 +- .../CreateLBStickinessPolicyCmd.java | 5 +- .../CreateLoadBalancerRuleCmd.java | 7 +- .../DeleteLBStickinessPolicyCmd.java | 3 +- .../DeleteLoadBalancerRuleCmd.java | 2 +- .../RemoveFromLoadBalancerRuleCmd.java | 2 +- .../UpdateLoadBalancerRuleCmd.java | 2 +- .../user/nat/CreateIpForwardingRuleCmd.java | 5 +- .../user/nat/DeleteIpForwardingRuleCmd.java | 3 +- .../command/user/nat/DisableStaticNatCmd.java | 3 +- .../command/user/nat/EnableStaticNatCmd.java | 5 +- .../user/network/CreateNetworkACLCmd.java | 7 +- .../user/network/CreateNetworkCmd.java | 3 +- .../user/network/DeleteNetworkACLCmd.java | 3 +- .../user/network/DeleteNetworkCmd.java | 2 +- .../user/network/RestartNetworkCmd.java | 2 +- .../user/network/UpdateNetworkCmd.java | 3 +- .../user/project/ActivateProjectCmd.java | 2 +- .../user/project/CreateProjectCmd.java | 4 +- .../user/project/DeleteProjectCmd.java | 3 +- .../project/DeleteProjectInvitationCmd.java | 3 +- .../user/project/SuspendProjectCmd.java | 2 +- .../user/project/UpdateProjectCmd.java | 3 +- .../project/UpdateProjectInvitationCmd.java | 2 +- .../user/resource/GetCloudIdentifierCmd.java | 3 +- .../user/resource/UpdateResourceCountCmd.java | 2 +- .../user/resource/UpdateResourceLimitCmd.java | 2 +- .../AuthorizeSecurityGroupEgressCmd.java | 2 +- .../AuthorizeSecurityGroupIngressCmd.java | 5 +- .../securitygroup/CreateSecurityGroupCmd.java | 3 +- .../securitygroup/DeleteSecurityGroupCmd.java | 5 +- .../RevokeSecurityGroupEgressCmd.java | 2 +- .../RevokeSecurityGroupIngressCmd.java | 3 +- .../user/snapshot/CreateSnapshotCmd.java | 4 +- .../snapshot/CreateSnapshotPolicyCmd.java | 2 +- .../user/snapshot/DeleteSnapshotCmd.java | 2 +- .../snapshot/DeleteSnapshotPoliciesCmd.java | 3 +- .../api/command/user/tag/CreateTagsCmd.java | 3 +- .../api/command/user/tag/DeleteTagsCmd.java | 3 +- .../user/template/CopyTemplateCmd.java | 5 +- .../user/template/CreateTemplateCmd.java | 4 +- .../user/template/DeleteTemplateCmd.java | 2 +- .../user/template/ExtractTemplateCmd.java | 4 +- .../user/template/RegisterTemplateCmd.java | 5 +- .../user/template/UpdateTemplateCmd.java | 3 +- .../api/command/user/vm/DeployVMCmd.java | 16 +- .../api/command/user/vm/DestroyVMCmd.java | 2 +- .../api/command/user/vm/RebootVMCmd.java | 3 +- .../command/user/vm/ResetVMPasswordCmd.java | 3 +- .../api/command/user/vm/RestoreVMCmd.java | 3 +- .../api/command/user/vm/StartVMCmd.java | 8 +- .../api/command/user/vm/StopVMCmd.java | 2 +- .../api/command/user/vm/UpdateVMCmd.java | 3 +- .../api/command/user/vm/UpgradeVMCmd.java | 2 +- .../user/vmgroup/CreateVMGroupCmd.java | 2 +- .../user/vmgroup/DeleteVMGroupCmd.java | 2 +- .../user/vmgroup/UpdateVMGroupCmd.java | 2 +- .../command/user/volume/AttachVolumeCmd.java | 3 +- .../command/user/volume/CreateVolumeCmd.java | 5 +- .../command/user/volume/DeleteVolumeCmd.java | 3 +- .../command/user/volume/DetachVolumeCmd.java | 2 +- .../command/user/volume/ExtractVolumeCmd.java | 5 +- .../command/user/volume/MigrateVolumeCmd.java | 3 +- .../command/user/volume/UploadVolumeCmd.java | 2 +- .../user/vpc/CreateStaticRouteCmd.java | 5 +- .../api/command/user/vpc/CreateVPCCmd.java | 11 +- .../user/vpc/DeleteStaticRouteCmd.java | 2 +- .../api/command/user/vpc/DeleteVPCCmd.java | 6 +- .../api/command/user/vpc/RestartVPCCmd.java | 8 +- .../api/command/user/vpc/UpdateVPCCmd.java | 3 +- .../api/command/user/vpn/AddVpnUserCmd.java | 5 +- .../user/vpn/CreateRemoteAccessVpnCmd.java | 8 +- .../user/vpn/CreateVpnConnectionCmd.java | 8 +- .../user/vpn/CreateVpnCustomerGatewayCmd.java | 3 +- .../command/user/vpn/CreateVpnGatewayCmd.java | 3 +- .../user/vpn/DeleteVpnConnectionCmd.java | 4 +- .../user/vpn/DeleteVpnCustomerGatewayCmd.java | 2 +- .../command/user/vpn/DeleteVpnGatewayCmd.java | 2 +- .../command/user/vpn/RemoveVpnUserCmd.java | 5 +- .../user/vpn/ResetVpnConnectionCmd.java | 4 +- .../user/vpn/UpdateVpnCustomerGatewayCmd.java | 2 +- .../command/user/discovery/ListApisCmd.java | 3 +- .../api/commands/netapp/AssociateLunCmd.java | 27 +- .../api/commands/netapp/CreateLunCmd.java | 21 +- .../netapp/CreateVolumeOnFilerCmd.java | 49 ++-- .../commands/netapp/CreateVolumePoolCmd.java | 13 +- .../commands/netapp/DeleteVolumePoolCmd.java | 9 +- .../api/commands/netapp/DestroyLunCmd.java | 9 +- .../netapp/DestroyVolumeOnFilerCmd.java | 20 +- .../api/commands/netapp/DissociateLunCmd.java | 8 +- .../api/commands/netapp/ListLunsCmd.java | 7 +- .../commands/netapp/ListVolumePoolsCmd.java | 7 +- .../netapp/ListVolumesOnFilerCmd.java | 8 +- .../api/commands/ConfigureSimulator.java | 3 +- .../api/commands/DeleteCiscoNexusVSMCmd.java | 5 +- .../api/commands/DisableCiscoNexusVSMCmd.java | 5 +- .../api/commands/EnableCiscoNexusVSMCmd.java | 2 +- .../api/commands/ListCiscoNexusVSMsCmd.java | 15 +- .../commands/AddExternalLoadBalancerCmd.java | 17 +- .../api/commands/AddF5LoadBalancerCmd.java | 10 +- .../commands/ConfigureF5LoadBalancerCmd.java | 6 +- .../DeleteExternalLoadBalancerCmd.java | 16 +- .../api/commands/DeleteF5LoadBalancerCmd.java | 7 +- .../ListF5LoadBalancerNetworksCmd.java | 5 +- .../api/commands/ListF5LoadBalancersCmd.java | 4 +- .../api/commands/AddExternalFirewallCmd.java | 37 +-- .../cloud/api/commands/AddSrxFirewallCmd.java | 13 +- .../api/commands/ConfigureSrxFirewallCmd.java | 9 +- .../commands/DeleteExternalFirewallCmd.java | 21 +- .../api/commands/DeleteSrxFirewallCmd.java | 9 +- .../commands/ListSrxFirewallNetworksCmd.java | 6 +- .../api/commands/ListSrxFirewallsCmd.java | 6 +- .../commands/AddNetscalerLoadBalancerCmd.java | 10 +- .../ConfigureNetscalerLoadBalancerCmd.java | 6 +- .../DeleteNetscalerLoadBalancerCmd.java | 7 +- .../ListNetscalerLoadBalancerNetworksCmd.java | 5 +- .../ListNetscalerLoadBalancersCmd.java | 5 +- .../api/commands/AddNiciraNvpDeviceCmd.java | 22 +- .../commands/DeleteNiciraNvpDeviceCmd.java | 7 +- .../ListNiciraNvpDeviceNetworksCmd.java | 5 +- .../api/commands/ListNiciraNvpDevicesCmd.java | 7 +- server/src/com/cloud/api/ApiDispatcher.java | 233 +++--------------- server/src/com/cloud/api/ApiServer.java | 225 ++++++++++------- server/src/com/cloud/api/ApiServlet.java | 23 +- .../api/commands/AddTrafficMonitorCmd.java | 4 +- .../api/commands/DeleteTrafficMonitorCmd.java | 23 +- .../api/commands/GenerateUsageRecordsCmd.java | 2 +- .../com/cloud/async/AsyncJobManagerImpl.java | 158 ++++++------ .../utils/exception/CSExceptionErrorCode.java | 32 --- 255 files changed, 1016 insertions(+), 962 deletions(-) create mode 100644 api/src/org/apache/cloudstack/api/ApiErrorCode.java diff --git a/api/src/com/cloud/api/commands/CreatePrivateNetworkCmd.java b/api/src/com/cloud/api/commands/CreatePrivateNetworkCmd.java index 263f023b3e5..1cc20d78930 100644 --- a/api/src/com/cloud/api/commands/CreatePrivateNetworkCmd.java +++ b/api/src/com/cloud/api/commands/CreatePrivateNetworkCmd.java @@ -145,17 +145,17 @@ public class CreatePrivateNetworkCmd extends BaseAsyncCreateCmd { } catch (InsufficientCapacityException ex){ s_logger.info(ex); s_logger.trace(ex); - throw new ServerApiException(BaseCmd.INSUFFICIENT_CAPACITY_ERROR, ex.getMessage()); + throw new ServerApiException(ApiErrorCode.INSUFFICIENT_CAPACITY_ERROR, ex.getMessage()); } catch (ConcurrentOperationException ex) { s_logger.warn("Exception: ", ex); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } if (result != null) { this.setEntityId(result.getId()); this.setEntityUuid(result.getUuid()); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create a Private network"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create a Private network"); } } @@ -167,7 +167,7 @@ public class CreatePrivateNetworkCmd extends BaseAsyncCreateCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create private network"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create private network"); } } diff --git a/api/src/com/cloud/api/commands/DestroyConsoleProxyCmd.java b/api/src/com/cloud/api/commands/DestroyConsoleProxyCmd.java index 80269075744..e749f2210ce 100644 --- a/api/src/com/cloud/api/commands/DestroyConsoleProxyCmd.java +++ b/api/src/com/cloud/api/commands/DestroyConsoleProxyCmd.java @@ -84,7 +84,7 @@ public class DestroyConsoleProxyCmd extends BaseAsyncCmd { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to destroy console proxy"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to destroy console proxy"); } } } diff --git a/api/src/org/apache/cloudstack/api/ApiErrorCode.java b/api/src/org/apache/cloudstack/api/ApiErrorCode.java new file mode 100644 index 00000000000..51671cd7ec2 --- /dev/null +++ b/api/src/org/apache/cloudstack/api/ApiErrorCode.java @@ -0,0 +1,59 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.api; + +/** + * Enum class for various API error code used in CloudStack + * @author minc + * + */ +public enum ApiErrorCode { + + MALFORMED_PARAMETER_ERROR(430), + PARAM_ERROR(431), + UNSUPPORTED_ACTION_ERROR(432), + API_LIMIT_EXCEED(429), + + INTERNAL_ERROR(530), + ACCOUNT_ERROR(531), + ACCOUNT_RESOURCE_LIMIT_ERROR(532), + INSUFFICIENT_CAPACITY_ERROR(533), + RESOURCE_UNAVAILABLE_ERROR(534), + RESOURCE_ALLOCATION_ERROR(534), + RESOURCE_IN_USE_ERROR(536), + NETWORK_RULE_CONFLICT_ERROR(537); + + private int httpCode; + + private ApiErrorCode(int httpStatusCode){ + httpCode = httpStatusCode; + } + + public int getHttpCode() { + return httpCode; + } + + public void setHttpCode(int httpCode) { + this.httpCode = httpCode; + } + + public String toString(){ + return String.valueOf(this.httpCode); + } + + +} diff --git a/api/src/org/apache/cloudstack/api/BaseCmd.java b/api/src/org/apache/cloudstack/api/BaseCmd.java index ae8bb2f69a6..14faf9f3cec 100644 --- a/api/src/org/apache/cloudstack/api/BaseCmd.java +++ b/api/src/org/apache/cloudstack/api/BaseCmd.java @@ -81,23 +81,6 @@ public abstract class BaseCmd { BOOLEAN, DATE, FLOAT, INTEGER, SHORT, LIST, LONG, OBJECT, MAP, STRING, TZDATE, UUID } - // FIXME: Extract these out into a separate file - // Client error codes - public static final int MALFORMED_PARAMETER_ERROR = 430; - public static final int PARAM_ERROR = 431; - public static final int UNSUPPORTED_ACTION_ERROR = 432; - public static final int PAGE_LIMIT_EXCEED = 433; - public static final int API_LIMIT_EXCEED = 429; - - // Server error codes - public static final int INTERNAL_ERROR = 530; - public static final int ACCOUNT_ERROR = 531; - public static final int ACCOUNT_RESOURCE_LIMIT_ERROR = 532; - public static final int INSUFFICIENT_CAPACITY_ERROR = 533; - public static final int RESOURCE_UNAVAILABLE_ERROR = 534; - public static final int RESOURCE_ALLOCATION_ERROR = 534; - public static final int RESOURCE_IN_USE_ERROR = 536; - public static final int NETWORK_RULE_CONFLICT_ERROR = 537; public static final DateFormat INPUT_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); public static final DateFormat NEW_INPUT_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); @@ -231,7 +214,7 @@ public abstract class BaseCmd { int arrayStartIndex = key.indexOf('['); int arrayStartLastIndex = key.lastIndexOf('['); if (arrayStartIndex != arrayStartLastIndex) { - throw new ServerApiException(MALFORMED_PARAMETER_ERROR, "Unable to decode parameter " + key + throw new ServerApiException(ApiErrorCode.MALFORMED_PARAMETER_ERROR, "Unable to decode parameter " + key + "; if specifying an object array, please use parameter[index].field=XXX, e.g. userGroupList[0].group=httpGroup"); } @@ -240,7 +223,7 @@ public abstract class BaseCmd { int arrayEndLastIndex = key.lastIndexOf(']'); if ((arrayEndIndex < arrayStartIndex) || (arrayEndIndex != arrayEndLastIndex)) { // malformed parameter - throw new ServerApiException(MALFORMED_PARAMETER_ERROR, "Unable to decode parameter " + key + throw new ServerApiException(ApiErrorCode.MALFORMED_PARAMETER_ERROR, "Unable to decode parameter " + key + "; if specifying an object array, please use parameter[index].field=XXX, e.g. userGroupList[0].group=httpGroup"); } @@ -248,7 +231,7 @@ public abstract class BaseCmd { int fieldIndex = key.indexOf('.'); String fieldName = null; if (fieldIndex < arrayEndIndex) { - throw new ServerApiException(MALFORMED_PARAMETER_ERROR, "Unable to decode parameter " + key + throw new ServerApiException(ApiErrorCode.MALFORMED_PARAMETER_ERROR, "Unable to decode parameter " + key + "; if specifying an object array, please use parameter[index].field=XXX, e.g. userGroupList[0].group=httpGroup"); } else { fieldName = key.substring(fieldIndex + 1); @@ -273,7 +256,7 @@ public abstract class BaseCmd { } if (!parsedIndex) { - throw new ServerApiException(MALFORMED_PARAMETER_ERROR, "Unable to decode parameter " + key + throw new ServerApiException(ApiErrorCode.MALFORMED_PARAMETER_ERROR, "Unable to decode parameter " + key + "; if specifying an object array, please use parameter[index].field=XXX, e.g. userGroupList[0].group=httpGroup"); } diff --git a/api/src/org/apache/cloudstack/api/BaseUpdateTemplateOrIsoPermissionsCmd.java b/api/src/org/apache/cloudstack/api/BaseUpdateTemplateOrIsoPermissionsCmd.java index aacc6efa2e0..3222c710c5d 100755 --- a/api/src/org/apache/cloudstack/api/BaseUpdateTemplateOrIsoPermissionsCmd.java +++ b/api/src/org/apache/cloudstack/api/BaseUpdateTemplateOrIsoPermissionsCmd.java @@ -119,7 +119,7 @@ public abstract class BaseUpdateTemplateOrIsoPermissionsCmd extends BaseCmd { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update template/iso permissions"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update template/iso permissions"); } } } diff --git a/api/src/org/apache/cloudstack/api/ServerApiException.java b/api/src/org/apache/cloudstack/api/ServerApiException.java index 1f57b74745d..682e5b7e774 100644 --- a/api/src/org/apache/cloudstack/api/ServerApiException.java +++ b/api/src/org/apache/cloudstack/api/ServerApiException.java @@ -15,28 +15,51 @@ // specific language governing permissions and limitations // under the License. package org.apache.cloudstack.api; +import java.util.ArrayList; + +import com.cloud.exception.CloudException; +import com.cloud.utils.exception.CSExceptionErrorCode; import com.cloud.utils.exception.CloudRuntimeException; @SuppressWarnings("serial") public class ServerApiException extends CloudRuntimeException { - private int _errorCode; + private ApiErrorCode _errorCode; private String _description; public ServerApiException() { - _errorCode = 0; + _errorCode = ApiErrorCode.INTERNAL_ERROR; _description = null; + setCSErrorCode(CSExceptionErrorCode.getCSErrCode(ServerApiException.class.getName())); } - public ServerApiException(int errorCode, String description) { + public ServerApiException(ApiErrorCode errorCode, String description) { _errorCode = errorCode; _description = description; + setCSErrorCode(CSExceptionErrorCode.getCSErrCode(ServerApiException.class.getName())); } - public int getErrorCode() { + // wrap a specific CloudRuntimeException to a ServerApiException + public ServerApiException(ApiErrorCode errorCode, String description, Throwable cause){ + super(description, cause); + _errorCode = errorCode; + _description = description; + if (cause instanceof CloudRuntimeException || cause instanceof CloudException ) { + CloudRuntimeException rt = (CloudRuntimeException) cause; + ArrayList idList = rt.getIdProxyList(); + if (idList != null) { + for (int i = 0; i < idList.size(); i++) { + addProxyObject(idList.get(i)); + } + } + setCSErrorCode(rt.getCSErrorCode()); + } + } + + public ApiErrorCode getErrorCode() { return _errorCode; } - public void setErrorCode(int errorCode) { + public void setErrorCode(ApiErrorCode errorCode) { _errorCode = errorCode; } diff --git a/api/src/org/apache/cloudstack/api/command/admin/account/CreateAccountCmd.java b/api/src/org/apache/cloudstack/api/command/admin/account/CreateAccountCmd.java index f93787b7bc5..a13cf6253a7 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/account/CreateAccountCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/account/CreateAccountCmd.java @@ -151,7 +151,7 @@ public class CreateAccountCmd extends BaseCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create a user account"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create a user account"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/account/DeleteAccountCmd.java b/api/src/org/apache/cloudstack/api/command/admin/account/DeleteAccountCmd.java index a1d9b6419cb..86ccb4ba20b 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/account/DeleteAccountCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/account/DeleteAccountCmd.java @@ -91,7 +91,7 @@ public class DeleteAccountCmd extends BaseAsyncCmd { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete user account and all corresponding users"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete user account and all corresponding users"); } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/account/DisableAccountCmd.java b/api/src/org/apache/cloudstack/api/command/admin/account/DisableAccountCmd.java index f0a5e7078b7..318dfda7ded 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/account/DisableAccountCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/account/DisableAccountCmd.java @@ -115,7 +115,7 @@ public class DisableAccountCmd extends BaseAsyncCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, lockRequested == true ? "Failed to lock account" : "Failed to disable account" ); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, lockRequested == true ? "Failed to lock account" : "Failed to disable account" ); } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/account/EnableAccountCmd.java b/api/src/org/apache/cloudstack/api/command/admin/account/EnableAccountCmd.java index 4aa1e4fc1b9..2688ef1510a 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/account/EnableAccountCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/account/EnableAccountCmd.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.api.command.admin.account; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.Parameter; @@ -95,7 +96,7 @@ public class EnableAccountCmd extends BaseCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to enable account"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to enable account"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/account/LockAccountCmd.java b/api/src/org/apache/cloudstack/api/command/admin/account/LockAccountCmd.java index 34e9e53b84d..c67e8463228 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/account/LockAccountCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/account/LockAccountCmd.java @@ -84,7 +84,7 @@ public class LockAccountCmd extends BaseCmd { // response.setResponseName(getCommandName()); // this.setResponseObject(response); // } else { -// throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to lock account"); +// throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to lock account"); // } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/account/UpdateAccountCmd.java b/api/src/org/apache/cloudstack/api/command/admin/account/UpdateAccountCmd.java index f1340464d6b..ea6d9078ed6 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/account/UpdateAccountCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/account/UpdateAccountCmd.java @@ -22,6 +22,7 @@ import java.util.Map; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.Parameter; @@ -125,7 +126,7 @@ public class UpdateAccountCmd extends BaseCmd{ response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update account"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update account"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/autoscale/CreateCounterCmd.java b/api/src/org/apache/cloudstack/api/command/admin/autoscale/CreateCounterCmd.java index a119d0f44bf..8c987228022 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/autoscale/CreateCounterCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/autoscale/CreateCounterCmd.java @@ -20,6 +20,7 @@ package org.apache.cloudstack.api.command.admin.autoscale; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCreateCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -86,7 +87,7 @@ public class CreateCounterCmd extends BaseAsyncCreateCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create Counter with name " + getName()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create Counter with name " + getName()); } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/autoscale/DeleteCounterCmd.java b/api/src/org/apache/cloudstack/api/command/admin/autoscale/DeleteCounterCmd.java index 9304eeb7b93..2fde0617693 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/autoscale/DeleteCounterCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/autoscale/DeleteCounterCmd.java @@ -20,6 +20,7 @@ package org.apache.cloudstack.api.command.admin.autoscale; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -56,7 +57,7 @@ public class DeleteCounterCmd extends BaseAsyncCmd { result = _autoScaleService.deleteCounter(getId()); } catch (ResourceInUseException ex) { s_logger.warn("Exception: ", ex); - throw new ServerApiException(BaseCmd.RESOURCE_IN_USE_ERROR, ex.getMessage()); + throw new ServerApiException(ApiErrorCode.RESOURCE_IN_USE_ERROR, ex.getMessage()); } if (result) { @@ -64,7 +65,7 @@ public class DeleteCounterCmd extends BaseAsyncCmd { this.setResponseObject(response); } else { s_logger.warn("Failed to delete counter with Id: " + getId()); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete counter."); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete counter."); } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/cluster/AddClusterCmd.java b/api/src/org/apache/cloudstack/api/command/admin/cluster/AddClusterCmd.java index 28bf72ddba7..c64883c16cf 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/cluster/AddClusterCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/cluster/AddClusterCmd.java @@ -156,7 +156,7 @@ public class AddClusterCmd extends BaseCmd { clusterResponses.add(clusterResponse); } } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to add cluster"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add cluster"); } response.setResponses(clusterResponses); @@ -165,10 +165,10 @@ public class AddClusterCmd extends BaseCmd { this.setResponseObject(response); } catch (DiscoveryException ex) { s_logger.warn("Exception: ", ex); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } catch (ResourceInUseException ex) { s_logger.warn("Exception: ", ex); - ServerApiException e = new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); + ServerApiException e = new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); for (String proxyObj : ex.getIdProxyList()) { e.addProxyObject(proxyObj); } diff --git a/api/src/org/apache/cloudstack/api/command/admin/cluster/DeleteClusterCmd.java b/api/src/org/apache/cloudstack/api/command/admin/cluster/DeleteClusterCmd.java index f0b40cb6b03..93103d3f60e 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/cluster/DeleteClusterCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/cluster/DeleteClusterCmd.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.api.command.admin.cluster; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.Parameter; @@ -70,7 +71,7 @@ public class DeleteClusterCmd extends BaseCmd { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete cluster"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete cluster"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/cluster/UpdateClusterCmd.java b/api/src/org/apache/cloudstack/api/command/admin/cluster/UpdateClusterCmd.java index 03b43def3ca..d6ec7188d0b 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/cluster/UpdateClusterCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/cluster/UpdateClusterCmd.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.api.command.admin.cluster; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.Parameter; @@ -112,7 +113,7 @@ public class UpdateClusterCmd extends BaseCmd { clusterResponse.setResponseName(getCommandName()); this.setResponseObject(clusterResponse); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update cluster"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update cluster"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/config/UpdateCfgCmd.java b/api/src/org/apache/cloudstack/api/command/admin/config/UpdateCfgCmd.java index 79693e76f84..1c435178efa 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/config/UpdateCfgCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/config/UpdateCfgCmd.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.api.command.admin.config; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.Parameter; @@ -76,7 +77,7 @@ public class UpdateCfgCmd extends BaseCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update config"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update config"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/config/UpdateHypervisorCapabilitiesCmd.java b/api/src/org/apache/cloudstack/api/command/admin/config/UpdateHypervisorCapabilitiesCmd.java index 82880c1fbae..19587f4483c 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/config/UpdateHypervisorCapabilitiesCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/config/UpdateHypervisorCapabilitiesCmd.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.api.command.admin.config; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.Parameter; @@ -86,7 +87,7 @@ public class UpdateHypervisorCapabilitiesCmd extends BaseCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update hypervisor capabilities"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update hypervisor capabilities"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/domain/CreateDomainCmd.java b/api/src/org/apache/cloudstack/api/command/admin/domain/CreateDomainCmd.java index 0e6ae32583b..61614d171f0 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/domain/CreateDomainCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/domain/CreateDomainCmd.java @@ -84,7 +84,7 @@ public class CreateDomainCmd extends BaseCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create domain"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create domain"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/domain/DeleteDomainCmd.java b/api/src/org/apache/cloudstack/api/command/admin/domain/DeleteDomainCmd.java index 7009e70ca32..3fda9608c13 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/domain/DeleteDomainCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/domain/DeleteDomainCmd.java @@ -93,7 +93,7 @@ public class DeleteDomainCmd extends BaseAsyncCmd { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete domain"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete domain"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/domain/UpdateDomainCmd.java b/api/src/org/apache/cloudstack/api/command/admin/domain/UpdateDomainCmd.java index cc5926cace1..607120c1886 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/domain/UpdateDomainCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/domain/UpdateDomainCmd.java @@ -83,7 +83,7 @@ public class UpdateDomainCmd extends BaseCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update domain"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update domain"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/host/AddHostCmd.java b/api/src/org/apache/cloudstack/api/command/admin/host/AddHostCmd.java index 0a0a98c1c45..77296c72a4a 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/host/AddHostCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/host/AddHostCmd.java @@ -22,6 +22,7 @@ import java.util.List; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.Parameter; @@ -148,7 +149,7 @@ public class AddHostCmd extends BaseCmd { hostResponses.add(hostResponse); } } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to add host"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add host"); } response.setResponses(hostResponses); @@ -157,7 +158,7 @@ public class AddHostCmd extends BaseCmd { this.setResponseObject(response); } catch (DiscoveryException ex) { s_logger.warn("Exception: ", ex); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/host/AddSecondaryStorageCmd.java b/api/src/org/apache/cloudstack/api/command/admin/host/AddSecondaryStorageCmd.java index 579e286f884..3bcee811151 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/host/AddSecondaryStorageCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/host/AddSecondaryStorageCmd.java @@ -84,11 +84,11 @@ public class AddSecondaryStorageCmd extends BaseCmd { this.setResponseObject(hostResponse); } } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to add secondary storage"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add secondary storage"); } } catch (DiscoveryException ex) { s_logger.warn("Exception: ", ex); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/host/CancelMaintenanceCmd.java b/api/src/org/apache/cloudstack/api/command/admin/host/CancelMaintenanceCmd.java index 93dca9140f9..8c617c03c76 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/host/CancelMaintenanceCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/host/CancelMaintenanceCmd.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.api.command.admin.host; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -104,7 +105,7 @@ public class CancelMaintenanceCmd extends BaseAsyncCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to cancel host maintenance"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to cancel host maintenance"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/host/DeleteHostCmd.java b/api/src/org/apache/cloudstack/api/command/admin/host/DeleteHostCmd.java index 5103f986e10..c2b731b8407 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/host/DeleteHostCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/host/DeleteHostCmd.java @@ -20,6 +20,7 @@ import org.apache.cloudstack.api.response.HostResponse; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.Parameter; @@ -84,7 +85,7 @@ public class DeleteHostCmd extends BaseCmd { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete host"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete host"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/host/PrepareForMaintenanceCmd.java b/api/src/org/apache/cloudstack/api/command/admin/host/PrepareForMaintenanceCmd.java index 385e2aef415..80b53aa1362 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/host/PrepareForMaintenanceCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/host/PrepareForMaintenanceCmd.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.api.command.admin.host; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -104,7 +105,7 @@ public class PrepareForMaintenanceCmd extends BaseAsyncCmd { response.setResponseName("host"); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to prepare host for maintenance"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to prepare host for maintenance"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/host/ReconnectHostCmd.java b/api/src/org/apache/cloudstack/api/command/admin/host/ReconnectHostCmd.java index 99e867bbebd..f42ec4b4814 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/host/ReconnectHostCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/host/ReconnectHostCmd.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.api.command.admin.host; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -103,11 +104,11 @@ public class ReconnectHostCmd extends BaseAsyncCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to reconnect host"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to reconnect host"); } } catch (Exception ex) { s_logger.warn("Exception: ", ex); - throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); + throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/host/UpdateHostCmd.java b/api/src/org/apache/cloudstack/api/command/admin/host/UpdateHostCmd.java index 9ab27178838..c1e374e030b 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/host/UpdateHostCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/host/UpdateHostCmd.java @@ -21,6 +21,7 @@ import java.util.List; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.Parameter; @@ -108,7 +109,7 @@ public class UpdateHostCmd extends BaseCmd { this.setResponseObject(hostResponse); } catch (Exception e) { s_logger.debug("Failed to update host:" + getId(), e); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update host:" + getId() + "," + e.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update host:" + getId() + "," + e.getMessage()); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/network/AddNetworkDeviceCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/AddNetworkDeviceCmd.java index 3e1d74df405..b8f98021c40 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/network/AddNetworkDeviceCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/network/AddNetworkDeviceCmd.java @@ -21,6 +21,7 @@ import java.util.Map; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.Parameter; @@ -74,9 +75,9 @@ public class AddNetworkDeviceCmd extends BaseCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } catch (InvalidParameterValueException ipve) { - throw new ServerApiException(BaseCmd.PARAM_ERROR, ipve.getMessage()); + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, ipve.getMessage()); } catch (CloudRuntimeException cre) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, cre.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, cre.getMessage()); } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/network/AddNetworkServiceProviderCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/AddNetworkServiceProviderCmd.java index 6d4b962d4a1..22802f936a0 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/network/AddNetworkServiceProviderCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/network/AddNetworkServiceProviderCmd.java @@ -21,6 +21,7 @@ import java.util.List; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCreateCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -103,7 +104,7 @@ public class AddNetworkServiceProviderCmd extends BaseAsyncCreateCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); }else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to add service provider to physical network"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add service provider to physical network"); } } @@ -114,7 +115,7 @@ public class AddNetworkServiceProviderCmd extends BaseAsyncCreateCmd { setEntityId(result.getId()); setEntityUuid(result.getUuid()); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to add service provider entity to physical network"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add service provider entity to physical network"); } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/network/CreateNetworkOfferingCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/CreateNetworkOfferingCmd.java index b97f85ec1ba..6733a35a5fd 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/network/CreateNetworkOfferingCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/network/CreateNetworkOfferingCmd.java @@ -225,7 +225,7 @@ public class CreateNetworkOfferingCmd extends BaseCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create network offering"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create network offering"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/network/CreatePhysicalNetworkCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/CreatePhysicalNetworkCmd.java index f56ae7dbf50..1b83a9114e4 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/network/CreatePhysicalNetworkCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/network/CreatePhysicalNetworkCmd.java @@ -21,6 +21,7 @@ import java.util.List; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCreateCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -151,7 +152,7 @@ public class CreatePhysicalNetworkCmd extends BaseAsyncCreateCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); }else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create physical network"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create physical network"); } } @@ -162,7 +163,7 @@ public class CreatePhysicalNetworkCmd extends BaseAsyncCreateCmd { setEntityId(result.getId()); setEntityUuid(result.getUuid()); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create physical network entity"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create physical network entity"); } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/network/CreateStorageNetworkIpRangeCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/CreateStorageNetworkIpRangeCmd.java index ccd92e19d67..59db3eb17c5 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/network/CreateStorageNetworkIpRangeCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/network/CreateStorageNetworkIpRangeCmd.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.api.command.admin.network; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -110,7 +111,7 @@ public class CreateStorageNetworkIpRangeCmd extends BaseAsyncCmd { this.setResponseObject(response); } catch (Exception e) { s_logger.warn("Create storage network IP range failed", e); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage()); } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/network/DeleteNetworkDeviceCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/DeleteNetworkDeviceCmd.java index 09451242daf..4d8d18e59ba 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/network/DeleteNetworkDeviceCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/network/DeleteNetworkDeviceCmd.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.api.command.admin.network; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.Parameter; @@ -65,12 +66,12 @@ public class DeleteNetworkDeviceCmd extends BaseCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete network device:" + getId()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete network device:" + getId()); } } catch (InvalidParameterValueException ipve) { - throw new ServerApiException(BaseCmd.PARAM_ERROR, ipve.getMessage()); + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, ipve.getMessage()); } catch (CloudRuntimeException cre) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, cre.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, cre.getMessage()); } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/network/DeleteNetworkOfferingCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/DeleteNetworkOfferingCmd.java index c13088f6123..69f24b419c0 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/network/DeleteNetworkOfferingCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/network/DeleteNetworkOfferingCmd.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.api.command.admin.network; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.Parameter; @@ -70,7 +71,7 @@ public class DeleteNetworkOfferingCmd extends BaseCmd{ SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete service offering"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete service offering"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/network/DeleteNetworkServiceProviderCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/DeleteNetworkServiceProviderCmd.java index bc744399a33..f0d2a128acc 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/network/DeleteNetworkServiceProviderCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/network/DeleteNetworkServiceProviderCmd.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.api.command.admin.network; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -76,14 +77,14 @@ public class DeleteNetworkServiceProviderCmd extends BaseAsyncCmd { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete network service provider"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete network service provider"); } } catch (ResourceUnavailableException ex) { s_logger.warn("Exception: ", ex); - throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); + throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } catch (ConcurrentOperationException ex) { s_logger.warn("Exception: ", ex); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/network/DeletePhysicalNetworkCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/DeletePhysicalNetworkCmd.java index 5f86efa9ad8..178ccb8e0b7 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/network/DeletePhysicalNetworkCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/network/DeletePhysicalNetworkCmd.java @@ -70,7 +70,7 @@ public class DeletePhysicalNetworkCmd extends BaseAsyncCmd { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete physical network"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete physical network"); } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/network/DeleteStorageNetworkIpRangeCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/DeleteStorageNetworkIpRangeCmd.java index 1873fc7d6ef..5fa26f69a48 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/network/DeleteStorageNetworkIpRangeCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/network/DeleteStorageNetworkIpRangeCmd.java @@ -70,7 +70,7 @@ public class DeleteStorageNetworkIpRangeCmd extends BaseAsyncCmd { this.setResponseObject(response); } catch (Exception e) { s_logger.warn("Failed to delete storage network ip range " + getId(), e); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage()); } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/network/ListNetworkDeviceCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/ListNetworkDeviceCmd.java index 742ff1f74af..11e74fbb8ce 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/network/ListNetworkDeviceCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/network/ListNetworkDeviceCmd.java @@ -23,6 +23,7 @@ import java.util.Map; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.BaseListCmd; import org.apache.cloudstack.api.APICommand; @@ -85,9 +86,9 @@ public class ListNetworkDeviceCmd extends BaseListCmd { listResponse.setResponseName(getCommandName()); this.setResponseObject(listResponse); } catch (InvalidParameterValueException ipve) { - throw new ServerApiException(BaseCmd.PARAM_ERROR, ipve.getMessage()); + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, ipve.getMessage()); } catch (CloudRuntimeException cre) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, cre.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, cre.getMessage()); } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/network/ListPhysicalNetworksCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/ListPhysicalNetworksCmd.java index a301ac004ea..3331d48103a 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/network/ListPhysicalNetworksCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/network/ListPhysicalNetworksCmd.java @@ -23,6 +23,7 @@ import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.BaseListCmd; import org.apache.cloudstack.api.APICommand; @@ -100,7 +101,7 @@ public class ListPhysicalNetworksCmd extends BaseListCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); }else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to search for physical networks"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to search for physical networks"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/network/ListStorageNetworkIpRangeCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/ListStorageNetworkIpRangeCmd.java index 8fcaf4958b1..b5045bb99fd 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/network/ListStorageNetworkIpRangeCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/network/ListStorageNetworkIpRangeCmd.java @@ -88,7 +88,7 @@ public class ListStorageNetworkIpRangeCmd extends BaseListCmd { this.setResponseObject(response); } catch (Exception e) { s_logger.warn("Failed to list storage network ip range for rangeId=" + getRangeId() + " podId=" + getPodId() + " zoneId=" + getZoneId()); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage()); } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/network/UpdateNetworkOfferingCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/UpdateNetworkOfferingCmd.java index dc2f3099206..ca4709deb2b 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/network/UpdateNetworkOfferingCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/network/UpdateNetworkOfferingCmd.java @@ -102,7 +102,7 @@ public class UpdateNetworkOfferingCmd extends BaseCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update network offering"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update network offering"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/network/UpdateNetworkServiceProviderCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/UpdateNetworkServiceProviderCmd.java index b770ea26c12..d64fd0796ee 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/network/UpdateNetworkServiceProviderCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/network/UpdateNetworkServiceProviderCmd.java @@ -21,6 +21,7 @@ import java.util.List; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -88,7 +89,7 @@ public class UpdateNetworkServiceProviderCmd extends BaseAsyncCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); }else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update service provider"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update service provider"); } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/network/UpdateStorageNetworkIpRangeCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/UpdateStorageNetworkIpRangeCmd.java index d6d0b92e4b7..d49d3c4e911 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/network/UpdateStorageNetworkIpRangeCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/network/UpdateStorageNetworkIpRangeCmd.java @@ -96,7 +96,7 @@ public class UpdateStorageNetworkIpRangeCmd extends BaseAsyncCmd { this.setResponseObject(response); } catch (Exception e) { s_logger.warn("Update storage network IP range failed", e); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage()); } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/offering/CreateDiskOfferingCmd.java b/api/src/org/apache/cloudstack/api/command/admin/offering/CreateDiskOfferingCmd.java index 08101dc4137..6c3630690f7 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/offering/CreateDiskOfferingCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/offering/CreateDiskOfferingCmd.java @@ -20,6 +20,7 @@ import org.apache.cloudstack.api.response.DomainResponse; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.Parameter; @@ -115,7 +116,7 @@ public class CreateDiskOfferingCmd extends BaseCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create disk offering"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create disk offering"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/offering/CreateServiceOfferingCmd.java b/api/src/org/apache/cloudstack/api/command/admin/offering/CreateServiceOfferingCmd.java index f93c2a88ce2..54151fe13b9 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/offering/CreateServiceOfferingCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/offering/CreateServiceOfferingCmd.java @@ -20,6 +20,7 @@ import org.apache.cloudstack.api.response.DomainResponse; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.Parameter; @@ -162,7 +163,7 @@ public class CreateServiceOfferingCmd extends BaseCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create service offering"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create service offering"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/offering/DeleteDiskOfferingCmd.java b/api/src/org/apache/cloudstack/api/command/admin/offering/DeleteDiskOfferingCmd.java index 85e034f6191..3f854637b8c 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/offering/DeleteDiskOfferingCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/offering/DeleteDiskOfferingCmd.java @@ -20,6 +20,7 @@ import org.apache.cloudstack.api.response.DiskOfferingResponse; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.Parameter; @@ -70,7 +71,7 @@ public class DeleteDiskOfferingCmd extends BaseCmd { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete disk offering"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete disk offering"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/offering/DeleteServiceOfferingCmd.java b/api/src/org/apache/cloudstack/api/command/admin/offering/DeleteServiceOfferingCmd.java index d1ea4de0504..0a8949b9071 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/offering/DeleteServiceOfferingCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/offering/DeleteServiceOfferingCmd.java @@ -68,7 +68,7 @@ public class DeleteServiceOfferingCmd extends BaseCmd{ SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete service offering"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete service offering"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/offering/UpdateDiskOfferingCmd.java b/api/src/org/apache/cloudstack/api/command/admin/offering/UpdateDiskOfferingCmd.java index 8db731d3b31..734b18bfb93 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/offering/UpdateDiskOfferingCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/offering/UpdateDiskOfferingCmd.java @@ -18,6 +18,7 @@ package org.apache.cloudstack.api.command.admin.offering; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.Parameter; @@ -91,7 +92,7 @@ public class UpdateDiskOfferingCmd extends BaseCmd{ response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update disk offering"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update disk offering"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/offering/UpdateServiceOfferingCmd.java b/api/src/org/apache/cloudstack/api/command/admin/offering/UpdateServiceOfferingCmd.java index 38220b90673..9dddd7d6718 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/offering/UpdateServiceOfferingCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/offering/UpdateServiceOfferingCmd.java @@ -89,7 +89,7 @@ public class UpdateServiceOfferingCmd extends BaseCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update service offering"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update service offering"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/pod/CreatePodCmd.java b/api/src/org/apache/cloudstack/api/command/admin/pod/CreatePodCmd.java index 331968b00db..95d9e53be75 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/pod/CreatePodCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/pod/CreatePodCmd.java @@ -111,7 +111,7 @@ public class CreatePodCmd extends BaseCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create pod"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create pod"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/pod/DeletePodCmd.java b/api/src/org/apache/cloudstack/api/command/admin/pod/DeletePodCmd.java index 8c64a8dad33..4080a7c46ee 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/pod/DeletePodCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/pod/DeletePodCmd.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.api.command.admin.pod; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.Parameter; @@ -70,7 +71,7 @@ public class DeletePodCmd extends BaseCmd { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete pod"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete pod"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/pod/UpdatePodCmd.java b/api/src/org/apache/cloudstack/api/command/admin/pod/UpdatePodCmd.java index ca5e03953a3..c99da9d8199 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/pod/UpdatePodCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/pod/UpdatePodCmd.java @@ -110,7 +110,7 @@ public class UpdatePodCmd extends BaseCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update pod"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update pod"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/resource/UploadCustomCertificateCmd.java b/api/src/org/apache/cloudstack/api/command/admin/resource/UploadCustomCertificateCmd.java index 0e559189904..97ec1dcee45 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/resource/UploadCustomCertificateCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/resource/UploadCustomCertificateCmd.java @@ -99,7 +99,7 @@ public class UploadCustomCertificateCmd extends BaseAsyncCmd { response.setObjectName("customcertificate"); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to upload custom certificate"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to upload custom certificate"); } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/router/ConfigureVirtualRouterElementCmd.java b/api/src/org/apache/cloudstack/api/command/admin/router/ConfigureVirtualRouterElementCmd.java index be6be26a36f..766e19cbe57 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/router/ConfigureVirtualRouterElementCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/router/ConfigureVirtualRouterElementCmd.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.api.command.admin.router; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -120,7 +121,7 @@ public class ConfigureVirtualRouterElementCmd extends BaseAsyncCmd { routerResponse.setResponseName(getCommandName()); this.setResponseObject(routerResponse); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to configure the virtual router provider"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to configure the virtual router provider"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/router/CreateVirtualRouterElementCmd.java b/api/src/org/apache/cloudstack/api/command/admin/router/CreateVirtualRouterElementCmd.java index f6a7b744ca3..54a840987df 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/router/CreateVirtualRouterElementCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/router/CreateVirtualRouterElementCmd.java @@ -82,7 +82,7 @@ public class CreateVirtualRouterElementCmd extends BaseAsyncCreateCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); }else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to add Virtual Router entity to physical network"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add Virtual Router entity to physical network"); } } @@ -93,7 +93,7 @@ public class CreateVirtualRouterElementCmd extends BaseAsyncCreateCmd { setEntityId(result.getId()); setEntityUuid(result.getUuid()); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to add Virtual Router entity to physical network"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add Virtual Router entity to physical network"); } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/router/DestroyRouterCmd.java b/api/src/org/apache/cloudstack/api/command/admin/router/DestroyRouterCmd.java index 1157aaa7b93..1645456bffb 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/router/DestroyRouterCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/router/DestroyRouterCmd.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.api.command.admin.router; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -104,7 +105,7 @@ public class DestroyRouterCmd extends BaseAsyncCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to destroy router"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to destroy router"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/router/RebootRouterCmd.java b/api/src/org/apache/cloudstack/api/command/admin/router/RebootRouterCmd.java index 9c50d2ffb0f..a095fce9cb9 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/router/RebootRouterCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/router/RebootRouterCmd.java @@ -98,7 +98,7 @@ public class RebootRouterCmd extends BaseAsyncCmd { response.setResponseName("router"); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to reboot router"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to reboot router"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/router/StartRouterCmd.java b/api/src/org/apache/cloudstack/api/command/admin/router/StartRouterCmd.java index f1f3f681829..595afc76d12 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/router/StartRouterCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/router/StartRouterCmd.java @@ -102,7 +102,7 @@ public class StartRouterCmd extends BaseAsyncCmd { routerResponse.setResponseName(getCommandName()); this.setResponseObject(routerResponse); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to start router"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to start router"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/router/StopRouterCmd.java b/api/src/org/apache/cloudstack/api/command/admin/router/StopRouterCmd.java index 2d1b609aa5d..571b2c19977 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/router/StopRouterCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/router/StopRouterCmd.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.api.command.admin.router; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -109,7 +110,7 @@ public class StopRouterCmd extends BaseAsyncCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to stop router"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to stop router"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/router/UpgradeRouterCmd.java b/api/src/org/apache/cloudstack/api/command/admin/router/UpgradeRouterCmd.java index e2b020e09f9..f8742a2cefb 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/router/UpgradeRouterCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/router/UpgradeRouterCmd.java @@ -81,7 +81,7 @@ public class UpgradeRouterCmd extends BaseCmd { routerResponse.setResponseName(getCommandName()); this.setResponseObject(routerResponse); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to upgrade router"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to upgrade router"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/storage/AddS3Cmd.java b/api/src/org/apache/cloudstack/api/command/admin/storage/AddS3Cmd.java index 13f066a6e57..ec62858f597 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/storage/AddS3Cmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/storage/AddS3Cmd.java @@ -31,6 +31,7 @@ import static org.apache.cloudstack.api.BaseCmd.CommandType.STRING; import static org.apache.cloudstack.api.BaseCmd.CommandType.BOOLEAN; import static com.cloud.user.Account.ACCOUNT_ID_SYSTEM; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.Parameter; @@ -93,12 +94,12 @@ public final class AddS3Cmd extends BaseCmd { result = _resourceService.discoverS3(this); if (result == null) { - throw new ServerApiException(INTERNAL_ERROR, "Failed to add S3."); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add S3."); } } catch (DiscoveryException e) { - throw new ServerApiException(INTERNAL_ERROR, "Failed to add S3 due to " + e.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add S3 due to " + e.getMessage()); } diff --git a/api/src/org/apache/cloudstack/api/command/admin/storage/CancelPrimaryStorageMaintenanceCmd.java b/api/src/org/apache/cloudstack/api/command/admin/storage/CancelPrimaryStorageMaintenanceCmd.java index 24ef48be222..59a2164e4d6 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/storage/CancelPrimaryStorageMaintenanceCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/storage/CancelPrimaryStorageMaintenanceCmd.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.api.command.admin.storage; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -107,7 +108,7 @@ public class CancelPrimaryStorageMaintenanceCmd extends BaseAsyncCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to cancel primary storage maintenance"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to cancel primary storage maintenance"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/storage/CreateStoragePoolCmd.java b/api/src/org/apache/cloudstack/api/command/admin/storage/CreateStoragePoolCmd.java index 78a142ac449..b5068115eb1 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/storage/CreateStoragePoolCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/storage/CreateStoragePoolCmd.java @@ -122,17 +122,17 @@ public class CreateStoragePoolCmd extends BaseCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to add storage pool"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add storage pool"); } } catch (ResourceUnavailableException ex1) { s_logger.warn("Exception: ", ex1); - throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, ex1.getMessage()); + throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, ex1.getMessage()); }catch (ResourceInUseException ex2) { s_logger.warn("Exception: ", ex2); - throw new ServerApiException(BaseCmd.RESOURCE_IN_USE_ERROR, ex2.getMessage()); + throw new ServerApiException(ApiErrorCode.RESOURCE_IN_USE_ERROR, ex2.getMessage()); } catch (UnknownHostException ex3) { s_logger.warn("Exception: ", ex3); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex3.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex3.getMessage()); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/storage/DeletePoolCmd.java b/api/src/org/apache/cloudstack/api/command/admin/storage/DeletePoolCmd.java index 1510f7822f7..8cf4a4b7970 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/storage/DeletePoolCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/storage/DeletePoolCmd.java @@ -78,9 +78,9 @@ public class DeletePoolCmd extends BaseCmd { } else { StoragePool pool = _storageService.getStoragePool(id); if (pool != null && pool.getStatus() == StoragePoolStatus.Removed) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to finish storage pool removal. The storage pool will not be used but cleanup is needed"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to finish storage pool removal. The storage pool will not be used but cleanup is needed"); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete storage pool"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete storage pool"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/storage/PreparePrimaryStorageForMaintenanceCmd.java b/api/src/org/apache/cloudstack/api/command/admin/storage/PreparePrimaryStorageForMaintenanceCmd.java index 6a4175516cc..ab9c226909d 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/storage/PreparePrimaryStorageForMaintenanceCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/storage/PreparePrimaryStorageForMaintenanceCmd.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.api.command.admin.storage; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -105,7 +106,7 @@ public class PreparePrimaryStorageForMaintenanceCmd extends BaseAsyncCmd { response.setResponseName("storagepool"); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to prepare primary storage for maintenance"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to prepare primary storage for maintenance"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/storage/UpdateStoragePoolCmd.java b/api/src/org/apache/cloudstack/api/command/admin/storage/UpdateStoragePoolCmd.java index 806df561397..b60ed7f9767 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/storage/UpdateStoragePoolCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/storage/UpdateStoragePoolCmd.java @@ -78,7 +78,7 @@ public class UpdateStoragePoolCmd extends BaseCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update storage pool"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update storage pool"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/swift/AddSwiftCmd.java b/api/src/org/apache/cloudstack/api/command/admin/swift/AddSwiftCmd.java index 23a00ca04dc..61f903e9c3c 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/swift/AddSwiftCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/swift/AddSwiftCmd.java @@ -92,12 +92,12 @@ public class AddSwiftCmd extends BaseCmd { swiftResponse.setObjectName("swift"); this.setResponseObject(swiftResponse); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to add Swift"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add Swift"); } } catch (DiscoveryException ex) { String errMsg = "Failed to add Swift due to " + ex.toString(); s_logger.warn(errMsg, ex); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, errMsg); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, errMsg); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/systemvm/DestroySystemVmCmd.java b/api/src/org/apache/cloudstack/api/command/admin/systemvm/DestroySystemVmCmd.java index ad0f09cba46..dc53ea751b4 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/systemvm/DestroySystemVmCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/systemvm/DestroySystemVmCmd.java @@ -95,7 +95,7 @@ public class DestroySystemVmCmd extends BaseAsyncCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Fail to destroy system vm"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Fail to destroy system vm"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/systemvm/MigrateSystemVMCmd.java b/api/src/org/apache/cloudstack/api/command/admin/systemvm/MigrateSystemVMCmd.java index dd844acd17f..909fe20f883 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/systemvm/MigrateSystemVMCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/systemvm/MigrateSystemVMCmd.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.api.command.admin.systemvm; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -116,20 +117,20 @@ public class MigrateSystemVMCmd extends BaseAsyncCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to migrate the system vm"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to migrate the system vm"); } } catch (ResourceUnavailableException ex) { s_logger.warn("Exception: ", ex); - throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); + throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } catch (ConcurrentOperationException e) { s_logger.warn("Exception: ", e); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage()); } catch (ManagementServerException e) { s_logger.warn("Exception: ", e); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage()); } catch (VirtualMachineMigrationException e) { s_logger.warn("Exception: ", e); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage()); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/systemvm/RebootSystemVmCmd.java b/api/src/org/apache/cloudstack/api/command/admin/systemvm/RebootSystemVmCmd.java index 49e895b22fe..2e7b5303395 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/systemvm/RebootSystemVmCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/systemvm/RebootSystemVmCmd.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.api.command.admin.systemvm; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -105,7 +106,7 @@ public class RebootSystemVmCmd extends BaseAsyncCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Fail to reboot system vm"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Fail to reboot system vm"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/systemvm/StartSystemVMCmd.java b/api/src/org/apache/cloudstack/api/command/admin/systemvm/StartSystemVMCmd.java index 70ab5f38720..40f9d62aa64 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/systemvm/StartSystemVMCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/systemvm/StartSystemVMCmd.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.api.command.admin.systemvm; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -109,7 +110,7 @@ public class StartSystemVMCmd extends BaseAsyncCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Fail to start system vm"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Fail to start system vm"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/systemvm/StopSystemVmCmd.java b/api/src/org/apache/cloudstack/api/command/admin/systemvm/StopSystemVmCmd.java index af2bd3ad64f..134043cb388 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/systemvm/StopSystemVmCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/systemvm/StopSystemVmCmd.java @@ -112,7 +112,7 @@ public class StopSystemVmCmd extends BaseAsyncCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Fail to stop system vm"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Fail to stop system vm"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/systemvm/UpgradeSystemVMCmd.java b/api/src/org/apache/cloudstack/api/command/admin/systemvm/UpgradeSystemVMCmd.java index 290c3603f1f..14046f39aaf 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/systemvm/UpgradeSystemVMCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/systemvm/UpgradeSystemVMCmd.java @@ -94,7 +94,7 @@ public class UpgradeSystemVMCmd extends BaseCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Fail to reboot system vm"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Fail to reboot system vm"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/usage/AddTrafficTypeCmd.java b/api/src/org/apache/cloudstack/api/command/admin/usage/AddTrafficTypeCmd.java index 5dca9d2d4c1..a7336245366 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/usage/AddTrafficTypeCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/usage/AddTrafficTypeCmd.java @@ -20,6 +20,7 @@ import org.apache.cloudstack.api.response.PhysicalNetworkResponse; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCreateCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -123,7 +124,7 @@ public class AddTrafficTypeCmd extends BaseAsyncCreateCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); }else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to add traffic type to physical network"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add traffic type to physical network"); } } @@ -134,7 +135,7 @@ public class AddTrafficTypeCmd extends BaseAsyncCreateCmd { setEntityId(result.getId()); setEntityUuid(result.getUuid()); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to add traffic type to physical network"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add traffic type to physical network"); } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/usage/DeleteTrafficTypeCmd.java b/api/src/org/apache/cloudstack/api/command/admin/usage/DeleteTrafficTypeCmd.java index bb665fbfd58..526921830ec 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/usage/DeleteTrafficTypeCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/usage/DeleteTrafficTypeCmd.java @@ -20,6 +20,7 @@ import org.apache.cloudstack.api.response.TrafficTypeResponse; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -73,7 +74,7 @@ public class DeleteTrafficTypeCmd extends BaseAsyncCmd { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); }else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete traffic type"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete traffic type"); } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/usage/UpdateTrafficTypeCmd.java b/api/src/org/apache/cloudstack/api/command/admin/usage/UpdateTrafficTypeCmd.java index 279c2b858d3..fca07028160 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/usage/UpdateTrafficTypeCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/usage/UpdateTrafficTypeCmd.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.api.command.admin.usage; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -95,7 +96,7 @@ public class UpdateTrafficTypeCmd extends BaseAsyncCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); }else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update traffic type"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update traffic type"); } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/user/CreateUserCmd.java b/api/src/org/apache/cloudstack/api/command/admin/user/CreateUserCmd.java index 2045abf4e93..1f1e3abc1af 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/user/CreateUserCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/user/CreateUserCmd.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.api.command.admin.user; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.Parameter; @@ -137,7 +138,7 @@ public class CreateUserCmd extends BaseCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create a user"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create a user"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/user/DeleteUserCmd.java b/api/src/org/apache/cloudstack/api/command/admin/user/DeleteUserCmd.java index a43501e7641..74a073c72d9 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/user/DeleteUserCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/user/DeleteUserCmd.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.api.command.admin.user; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.Parameter; @@ -76,7 +77,7 @@ public class DeleteUserCmd extends BaseCmd { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete user"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete user"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/user/DisableUserCmd.java b/api/src/org/apache/cloudstack/api/command/admin/user/DisableUserCmd.java index f483e628928..6b59de5672d 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/user/DisableUserCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/user/DisableUserCmd.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.api.command.admin.user; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -92,7 +93,7 @@ public class DisableUserCmd extends BaseAsyncCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to disable user"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to disable user"); } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/user/EnableUserCmd.java b/api/src/org/apache/cloudstack/api/command/admin/user/EnableUserCmd.java index e444aa395d2..bcd0f43e03a 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/user/EnableUserCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/user/EnableUserCmd.java @@ -76,7 +76,7 @@ public class EnableUserCmd extends BaseCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to enable user"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to enable user"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/user/LockUserCmd.java b/api/src/org/apache/cloudstack/api/command/admin/user/LockUserCmd.java index 622b4e9a023..1b00bfd29ca 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/user/LockUserCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/user/LockUserCmd.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.api.command.admin.user; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.Parameter; @@ -77,7 +78,7 @@ public class LockUserCmd extends BaseCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to lock user"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to lock user"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/user/UpdateUserCmd.java b/api/src/org/apache/cloudstack/api/command/admin/user/UpdateUserCmd.java index 170d852ff58..00bfccc1038 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/user/UpdateUserCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/user/UpdateUserCmd.java @@ -132,7 +132,7 @@ public class UpdateUserCmd extends BaseCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update user"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update user"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/vlan/CreateVlanIpRangeCmd.java b/api/src/org/apache/cloudstack/api/command/admin/vlan/CreateVlanIpRangeCmd.java index c9717480e44..9ac1e253bfe 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/vlan/CreateVlanIpRangeCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/vlan/CreateVlanIpRangeCmd.java @@ -169,14 +169,14 @@ public class CreateVlanIpRangeCmd extends BaseCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); }else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create vlan ip range"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create vlan ip range"); } } catch (ConcurrentOperationException ex) { s_logger.warn("Exception: ", ex); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } catch (InsufficientCapacityException ex) { s_logger.info(ex); - throw new ServerApiException(BaseCmd.INSUFFICIENT_CAPACITY_ERROR, ex.getMessage()); + throw new ServerApiException(ApiErrorCode.INSUFFICIENT_CAPACITY_ERROR, ex.getMessage()); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/vlan/DeleteVlanIpRangeCmd.java b/api/src/org/apache/cloudstack/api/command/admin/vlan/DeleteVlanIpRangeCmd.java index f12b2175aef..d45082a2ace 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/vlan/DeleteVlanIpRangeCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/vlan/DeleteVlanIpRangeCmd.java @@ -20,6 +20,7 @@ import org.apache.cloudstack.api.response.VlanIpRangeResponse; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.Parameter; @@ -70,7 +71,7 @@ public class DeleteVlanIpRangeCmd extends BaseCmd { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete vlan ip range"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete vlan ip range"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/vm/AssignVMCmd.java b/api/src/org/apache/cloudstack/api/command/admin/vm/AssignVMCmd.java index 3482ec756fb..525e8d72f8f 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/vm/AssignVMCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/vm/AssignVMCmd.java @@ -101,14 +101,14 @@ public class AssignVMCmd extends BaseCmd { try { UserVm userVm = _userVmService.moveVMToUser(this); if (userVm == null){ - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to move vm"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to move vm"); } UserVmResponse response = _responseGenerator.createUserVmResponse("virtualmachine", userVm).get(0); response.setResponseName(DeployVMCmd.getResultObjectName()); this.setResponseObject(response); }catch (Exception e){ e.printStackTrace(); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to move vm " + e.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to move vm " + e.getMessage()); } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/vm/MigrateVMCmd.java b/api/src/org/apache/cloudstack/api/command/admin/vm/MigrateVMCmd.java index 5bb694da655..e1f20a8e9d3 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/vm/MigrateVMCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/vm/MigrateVMCmd.java @@ -150,20 +150,20 @@ public class MigrateVMCmd extends BaseAsyncCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to migrate vm"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to migrate vm"); } } catch (ResourceUnavailableException ex) { s_logger.warn("Exception: ", ex); - throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); + throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } catch (ConcurrentOperationException e) { s_logger.warn("Exception: ", e); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage()); } catch (ManagementServerException e) { s_logger.warn("Exception: ", e); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage()); } catch (VirtualMachineMigrationException e) { s_logger.warn("Exception: ", e); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage()); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/vm/RecoverVMCmd.java b/api/src/org/apache/cloudstack/api/command/admin/vm/RecoverVMCmd.java index f8308614b89..be4d10b8b5f 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/vm/RecoverVMCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/vm/RecoverVMCmd.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.api.command.admin.vm; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.Parameter; @@ -77,7 +78,7 @@ public class RecoverVMCmd extends BaseCmd { recoverVmResponse.setResponseName(getCommandName()); this.setResponseObject(recoverVmResponse); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to recover vm"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to recover vm"); } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/vpc/CreatePrivateGatewayCmd.java b/api/src/org/apache/cloudstack/api/command/admin/vpc/CreatePrivateGatewayCmd.java index 5bb76ab034b..392b6276bc9 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/vpc/CreatePrivateGatewayCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/vpc/CreatePrivateGatewayCmd.java @@ -21,6 +21,7 @@ import org.apache.cloudstack.api.response.VpcResponse; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseAsyncCreateCmd; import org.apache.cloudstack.api.BaseCmd; @@ -115,17 +116,17 @@ public class CreatePrivateGatewayCmd extends BaseAsyncCreateCmd { } catch (InsufficientCapacityException ex){ s_logger.info(ex); s_logger.trace(ex); - throw new ServerApiException(BaseCmd.INSUFFICIENT_CAPACITY_ERROR, ex.getMessage()); + throw new ServerApiException(ApiErrorCode.INSUFFICIENT_CAPACITY_ERROR, ex.getMessage()); } catch (ConcurrentOperationException ex) { s_logger.warn("Exception: ", ex); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } if (result != null) { this.setEntityId(result.getId()); this.setEntityUuid(result.getUuid()); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create private gateway"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create private gateway"); } } @@ -138,7 +139,7 @@ public class CreatePrivateGatewayCmd extends BaseAsyncCreateCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create private gateway"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create private gateway"); } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/vpc/CreateVPCOfferingCmd.java b/api/src/org/apache/cloudstack/api/command/admin/vpc/CreateVPCOfferingCmd.java index 273f7c05233..8ccb9d5e68c 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/vpc/CreateVPCOfferingCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/vpc/CreateVPCOfferingCmd.java @@ -72,7 +72,7 @@ public class CreateVPCOfferingCmd extends BaseAsyncCreateCmd{ this.setEntityId(vpcOff.getId()); this.setEntityUuid(vpcOff.getUuid()); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create a VPC offering"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create a VPC offering"); } } @@ -84,7 +84,7 @@ public class CreateVPCOfferingCmd extends BaseAsyncCreateCmd{ response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create VPC offering"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create VPC offering"); } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/vpc/DeletePrivateGatewayCmd.java b/api/src/org/apache/cloudstack/api/command/admin/vpc/DeletePrivateGatewayCmd.java index 4a1e8d05912..2b0e1a6a193 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/vpc/DeletePrivateGatewayCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/vpc/DeletePrivateGatewayCmd.java @@ -20,6 +20,7 @@ import org.apache.cloudstack.api.response.PrivateGatewayResponse; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -87,7 +88,7 @@ public class DeletePrivateGatewayCmd extends BaseAsyncCmd { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete private gateway"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete private gateway"); } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/vpc/DeleteVPCOfferingCmd.java b/api/src/org/apache/cloudstack/api/command/admin/vpc/DeleteVPCOfferingCmd.java index 231f2ee2955..9a257c24c0c 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/vpc/DeleteVPCOfferingCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/vpc/DeleteVPCOfferingCmd.java @@ -20,6 +20,7 @@ import org.apache.cloudstack.api.response.VpcOfferingResponse; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -71,7 +72,7 @@ public class DeleteVPCOfferingCmd extends BaseAsyncCmd{ SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete VPC offering"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete VPC offering"); } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/vpc/UpdateVPCOfferingCmd.java b/api/src/org/apache/cloudstack/api/command/admin/vpc/UpdateVPCOfferingCmd.java index 65df48e3e1f..c8fa77df1ff 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/vpc/UpdateVPCOfferingCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/vpc/UpdateVPCOfferingCmd.java @@ -90,7 +90,7 @@ public class UpdateVPCOfferingCmd extends BaseAsyncCmd{ response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update VPC offering"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update VPC offering"); } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/zone/CreateZoneCmd.java b/api/src/org/apache/cloudstack/api/command/admin/zone/CreateZoneCmd.java index e49f2439288..ae57fae5a8d 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/zone/CreateZoneCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/zone/CreateZoneCmd.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.api.command.admin.zone; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.Parameter; @@ -156,7 +157,7 @@ public class CreateZoneCmd extends BaseCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create a zone"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create a zone"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/zone/DeleteZoneCmd.java b/api/src/org/apache/cloudstack/api/command/admin/zone/DeleteZoneCmd.java index d09c7fff891..e9a02accba1 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/zone/DeleteZoneCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/zone/DeleteZoneCmd.java @@ -71,7 +71,7 @@ public class DeleteZoneCmd extends BaseCmd { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete zone"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete zone"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/zone/MarkDefaultZoneForAccountCmd.java b/api/src/org/apache/cloudstack/api/command/admin/zone/MarkDefaultZoneForAccountCmd.java index 816befbd029..59a37c96a84 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/zone/MarkDefaultZoneForAccountCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/zone/MarkDefaultZoneForAccountCmd.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.api.command.admin.zone; import org.apache.log4j.Logger; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.Parameter; @@ -109,7 +110,7 @@ public class MarkDefaultZoneForAccountCmd extends BaseAsyncCmd { this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to mark the account with the default zone"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to mark the account with the default zone"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/zone/UpdateZoneCmd.java b/api/src/org/apache/cloudstack/api/command/admin/zone/UpdateZoneCmd.java index 0bfd1a31a0f..143c8f7a892 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/zone/UpdateZoneCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/zone/UpdateZoneCmd.java @@ -164,7 +164,7 @@ public class UpdateZoneCmd extends BaseCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update zone; internal error."); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update zone; internal error."); } } } diff --git a/api/src/org/apache/cloudstack/api/command/user/account/AddAccountToProjectCmd.java b/api/src/org/apache/cloudstack/api/command/user/account/AddAccountToProjectCmd.java index 889c3697515..f62be0bf8c3 100644 --- a/api/src/org/apache/cloudstack/api/command/user/account/AddAccountToProjectCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/account/AddAccountToProjectCmd.java @@ -87,7 +87,7 @@ public class AddAccountToProjectCmd extends BaseAsyncCmd { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to add account to the project"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add account to the project"); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/account/DeleteAccountFromProjectCmd.java b/api/src/org/apache/cloudstack/api/command/user/account/DeleteAccountFromProjectCmd.java index f9e967ad4c2..ef14d1ae7aa 100644 --- a/api/src/org/apache/cloudstack/api/command/user/account/DeleteAccountFromProjectCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/account/DeleteAccountFromProjectCmd.java @@ -76,7 +76,7 @@ public class DeleteAccountFromProjectCmd extends BaseAsyncCmd { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete account from the project"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete account from the project"); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/address/AssociateIPAddrCmd.java b/api/src/org/apache/cloudstack/api/command/user/address/AssociateIPAddrCmd.java index 93bb2401d8f..4437191db37 100644 --- a/api/src/org/apache/cloudstack/api/command/user/address/AssociateIPAddrCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/address/AssociateIPAddrCmd.java @@ -21,6 +21,7 @@ import java.util.List; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseAsyncCreateCmd; import org.apache.cloudstack.api.BaseCmd; @@ -219,15 +220,15 @@ public class AssociateIPAddrCmd extends BaseAsyncCreateCmd { this.setEntityId(ip.getId()); this.setEntityUuid(ip.getUuid()); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to allocate ip address"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to allocate ip address"); } } catch (ConcurrentOperationException ex) { s_logger.warn("Exception: ", ex); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } catch (InsufficientAddressCapacityException ex) { s_logger.info(ex); s_logger.trace(ex); - throw new ServerApiException(BaseCmd.INSUFFICIENT_CAPACITY_ERROR, ex.getMessage()); + throw new ServerApiException(ApiErrorCode.INSUFFICIENT_CAPACITY_ERROR, ex.getMessage()); } } @@ -249,7 +250,7 @@ public class AssociateIPAddrCmd extends BaseAsyncCreateCmd { ipResponse.setResponseName(getCommandName()); this.setResponseObject(ipResponse); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to assign ip address"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to assign ip address"); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/address/DisassociateIPAddrCmd.java b/api/src/org/apache/cloudstack/api/command/user/address/DisassociateIPAddrCmd.java index 20ccd89ba84..c208a1a3d92 100644 --- a/api/src/org/apache/cloudstack/api/command/user/address/DisassociateIPAddrCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/address/DisassociateIPAddrCmd.java @@ -75,7 +75,7 @@ public class DisassociateIPAddrCmd extends BaseAsyncCmd { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to disassociate ip address"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to disassociate ip address"); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/autoscale/CreateAutoScalePolicyCmd.java b/api/src/org/apache/cloudstack/api/command/user/autoscale/CreateAutoScalePolicyCmd.java index e92721d77bf..987d305b4b0 100644 --- a/api/src/org/apache/cloudstack/api/command/user/autoscale/CreateAutoScalePolicyCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/autoscale/CreateAutoScalePolicyCmd.java @@ -157,7 +157,7 @@ public class CreateAutoScalePolicyCmd extends BaseAsyncCreateCmd { this.setEntityId(result.getId()); this.setEntityUuid(result.getUuid()); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create AutoScale Policy"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create AutoScale Policy"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/user/autoscale/CreateAutoScaleVmGroupCmd.java b/api/src/org/apache/cloudstack/api/command/user/autoscale/CreateAutoScaleVmGroupCmd.java index e3d47a09c7d..400be5db3f1 100644 --- a/api/src/org/apache/cloudstack/api/command/user/autoscale/CreateAutoScaleVmGroupCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/autoscale/CreateAutoScaleVmGroupCmd.java @@ -159,7 +159,7 @@ public class CreateAutoScaleVmGroupCmd extends BaseAsyncCreateCmd { this.setEntityId(result.getId()); this.setEntityUuid(result.getUuid()); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create Autoscale Vm Group"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create Autoscale Vm Group"); } } @@ -182,7 +182,7 @@ public class CreateAutoScaleVmGroupCmd extends BaseAsyncCreateCmd { } finally { if (!success || vmGroup == null) { _autoScaleService.deleteAutoScaleVmGroup(getEntityId()); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create Autoscale Vm Group"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create Autoscale Vm Group"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/user/autoscale/CreateAutoScaleVmProfileCmd.java b/api/src/org/apache/cloudstack/api/command/user/autoscale/CreateAutoScaleVmProfileCmd.java index 25bb03b778f..39814e7b9ce 100644 --- a/api/src/org/apache/cloudstack/api/command/user/autoscale/CreateAutoScaleVmProfileCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/autoscale/CreateAutoScaleVmProfileCmd.java @@ -22,6 +22,7 @@ import java.util.Map; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCreateCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -231,7 +232,7 @@ public class CreateAutoScaleVmProfileCmd extends BaseAsyncCreateCmd { this.setEntityId(result.getId()); this.setEntityUuid(result.getUuid()); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create Autoscale Vm Profile"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create Autoscale Vm Profile"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/user/autoscale/CreateConditionCmd.java b/api/src/org/apache/cloudstack/api/command/user/autoscale/CreateConditionCmd.java index 58926f2a4ff..89da2345134 100644 --- a/api/src/org/apache/cloudstack/api/command/user/autoscale/CreateConditionCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/autoscale/CreateConditionCmd.java @@ -22,6 +22,7 @@ import org.apache.cloudstack.api.response.DomainResponse; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCreateCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -74,7 +75,7 @@ public class CreateConditionCmd extends BaseAsyncCreateCmd { this.setEntityId(condition.getId()); this.setEntityUuid(condition.getUuid()); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create condition."); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create condition."); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/autoscale/DeleteAutoScalePolicyCmd.java b/api/src/org/apache/cloudstack/api/command/user/autoscale/DeleteAutoScalePolicyCmd.java index 483a87ac892..aa236ee082e 100644 --- a/api/src/org/apache/cloudstack/api/command/user/autoscale/DeleteAutoScalePolicyCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/autoscale/DeleteAutoScalePolicyCmd.java @@ -20,6 +20,7 @@ import org.apache.cloudstack.api.response.AutoScalePolicyResponse; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -92,7 +93,7 @@ public class DeleteAutoScalePolicyCmd extends BaseAsyncCmd { this.setResponseObject(response); } else { s_logger.warn("Failed to delete autoscale policy " + getId()); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete AutoScale Policy"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete AutoScale Policy"); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/autoscale/DeleteAutoScaleVmGroupCmd.java b/api/src/org/apache/cloudstack/api/command/user/autoscale/DeleteAutoScaleVmGroupCmd.java index 1d78fe80395..54eb7462750 100644 --- a/api/src/org/apache/cloudstack/api/command/user/autoscale/DeleteAutoScaleVmGroupCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/autoscale/DeleteAutoScaleVmGroupCmd.java @@ -20,6 +20,7 @@ import org.apache.cloudstack.api.response.AutoScaleVmGroupResponse; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -92,7 +93,7 @@ public class DeleteAutoScaleVmGroupCmd extends BaseAsyncCmd { this.setResponseObject(response); } else { s_logger.warn("Failed to delete autoscale vm group " + getId()); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete autoscale vm group"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete autoscale vm group"); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/autoscale/DeleteAutoScaleVmProfileCmd.java b/api/src/org/apache/cloudstack/api/command/user/autoscale/DeleteAutoScaleVmProfileCmd.java index e49f0c862a3..726f006ef02 100644 --- a/api/src/org/apache/cloudstack/api/command/user/autoscale/DeleteAutoScaleVmProfileCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/autoscale/DeleteAutoScaleVmProfileCmd.java @@ -20,6 +20,7 @@ import org.apache.cloudstack.api.response.AutoScaleVmProfileResponse; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -91,7 +92,7 @@ public class DeleteAutoScaleVmProfileCmd extends BaseAsyncCmd { this.setResponseObject(response); } else { s_logger.warn("Failed to delete autoscale vm profile " + getId()); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete autoscale vm profile"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete autoscale vm profile"); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/autoscale/DeleteConditionCmd.java b/api/src/org/apache/cloudstack/api/command/user/autoscale/DeleteConditionCmd.java index a1fba2e3725..5ce1ee27a73 100644 --- a/api/src/org/apache/cloudstack/api/command/user/autoscale/DeleteConditionCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/autoscale/DeleteConditionCmd.java @@ -21,6 +21,7 @@ import org.apache.cloudstack.api.response.ConditionResponse; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -57,14 +58,14 @@ public class DeleteConditionCmd extends BaseAsyncCmd { result = _autoScaleService.deleteCondition(getId()); } catch (ResourceInUseException ex) { s_logger.warn("Exception: ", ex); - throw new ServerApiException(BaseCmd.RESOURCE_IN_USE_ERROR, ex.getMessage()); + throw new ServerApiException(ApiErrorCode.RESOURCE_IN_USE_ERROR, ex.getMessage()); } if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { s_logger.warn("Failed to delete condition " + getId()); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete condition."); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete condition."); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/autoscale/DisableAutoScaleVmGroupCmd.java b/api/src/org/apache/cloudstack/api/command/user/autoscale/DisableAutoScaleVmGroupCmd.java index 2aba82c2a93..f4f9212979e 100644 --- a/api/src/org/apache/cloudstack/api/command/user/autoscale/DisableAutoScaleVmGroupCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/autoscale/DisableAutoScaleVmGroupCmd.java @@ -20,6 +20,7 @@ package org.apache.cloudstack.api.command.user.autoscale; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -56,7 +57,7 @@ public class DisableAutoScaleVmGroupCmd extends BaseAsyncCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to disable AutoScale Vm Group"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to disable AutoScale Vm Group"); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/autoscale/EnableAutoScaleVmGroupCmd.java b/api/src/org/apache/cloudstack/api/command/user/autoscale/EnableAutoScaleVmGroupCmd.java index db7acdf5d98..80ac818d263 100644 --- a/api/src/org/apache/cloudstack/api/command/user/autoscale/EnableAutoScaleVmGroupCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/autoscale/EnableAutoScaleVmGroupCmd.java @@ -52,7 +52,7 @@ public class EnableAutoScaleVmGroupCmd extends BaseAsyncCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to enable AutoScale Vm Group"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to enable AutoScale Vm Group"); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/autoscale/UpdateAutoScalePolicyCmd.java b/api/src/org/apache/cloudstack/api/command/user/autoscale/UpdateAutoScalePolicyCmd.java index 56d71078ece..6a55a4aa1e6 100644 --- a/api/src/org/apache/cloudstack/api/command/user/autoscale/UpdateAutoScalePolicyCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/autoscale/UpdateAutoScalePolicyCmd.java @@ -23,6 +23,7 @@ import org.apache.cloudstack.api.response.ConditionResponse; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -68,7 +69,7 @@ public class UpdateAutoScalePolicyCmd extends BaseAsyncCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update autoscale policy"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update autoscale policy"); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/autoscale/UpdateAutoScaleVmGroupCmd.java b/api/src/org/apache/cloudstack/api/command/user/autoscale/UpdateAutoScaleVmGroupCmd.java index ea5b6a9f489..fc6a7c6b861 100644 --- a/api/src/org/apache/cloudstack/api/command/user/autoscale/UpdateAutoScaleVmGroupCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/autoscale/UpdateAutoScaleVmGroupCmd.java @@ -75,7 +75,7 @@ public class UpdateAutoScaleVmGroupCmd extends BaseAsyncCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update autoscale VmGroup"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update autoscale VmGroup"); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/autoscale/UpdateAutoScaleVmProfileCmd.java b/api/src/org/apache/cloudstack/api/command/user/autoscale/UpdateAutoScaleVmProfileCmd.java index c8ef8b11198..570ed0beb3d 100644 --- a/api/src/org/apache/cloudstack/api/command/user/autoscale/UpdateAutoScaleVmProfileCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/autoscale/UpdateAutoScaleVmProfileCmd.java @@ -73,7 +73,7 @@ public class UpdateAutoScaleVmProfileCmd extends BaseAsyncCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update autoscale vm profile"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update autoscale vm profile"); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/firewall/CreateFirewallRuleCmd.java b/api/src/org/apache/cloudstack/api/command/user/firewall/CreateFirewallRuleCmd.java index 7039b417ced..0dcba5f4d5b 100644 --- a/api/src/org/apache/cloudstack/api/command/user/firewall/CreateFirewallRuleCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/firewall/CreateFirewallRuleCmd.java @@ -23,6 +23,7 @@ import org.apache.cloudstack.api.response.IPAddressResponse; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseAsyncCreateCmd; import org.apache.cloudstack.api.BaseCmd; @@ -134,7 +135,7 @@ public class CreateFirewallRuleCmd extends BaseAsyncCreateCmd implements Firewal } finally { if (!success || rule == null) { _firewallService.revokeFirewallRule(getEntityId(), true); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create firewall rule"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create firewall rule"); } } } @@ -231,7 +232,7 @@ public class CreateFirewallRuleCmd extends BaseAsyncCreateCmd implements Firewal if (getSourceCidrList() != null) { for (String cidr: getSourceCidrList()){ if (!NetUtils.isValidCIDR(cidr)){ - throw new ServerApiException(BaseCmd.PARAM_ERROR, "Source cidrs formatting error " + cidr); + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Source cidrs formatting error " + cidr); } } } @@ -243,7 +244,7 @@ public class CreateFirewallRuleCmd extends BaseAsyncCreateCmd implements Firewal } catch (NetworkRuleConflictException ex) { s_logger.info("Network rule conflict: " + ex.getMessage()); s_logger.trace("Network Rule Conflict: ", ex); - throw new ServerApiException(BaseCmd.NETWORK_RULE_CONFLICT_ERROR, ex.getMessage()); + throw new ServerApiException(ApiErrorCode.NETWORK_RULE_CONFLICT_ERROR, ex.getMessage()); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/firewall/CreatePortForwardingRuleCmd.java b/api/src/org/apache/cloudstack/api/command/user/firewall/CreatePortForwardingRuleCmd.java index 1feefde9a1a..7d8dbb0bbdf 100644 --- a/api/src/org/apache/cloudstack/api/command/user/firewall/CreatePortForwardingRuleCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/firewall/CreatePortForwardingRuleCmd.java @@ -185,7 +185,7 @@ public class CreatePortForwardingRuleCmd extends BaseAsyncCreateCmd implements P _rulesService.revokePortForwardingRule(getEntityId(), true); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to apply port forwarding rule"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to apply port forwarding rule"); } } } @@ -302,7 +302,7 @@ public class CreatePortForwardingRuleCmd extends BaseAsyncCreateCmd implements P } catch (NetworkRuleConflictException ex) { s_logger.info("Network rule conflict: " , ex); s_logger.trace("Network Rule Conflict: ", ex); - throw new ServerApiException(BaseCmd.NETWORK_RULE_CONFLICT_ERROR, ex.getMessage()); + throw new ServerApiException(ApiErrorCode.NETWORK_RULE_CONFLICT_ERROR, ex.getMessage()); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/firewall/DeleteFirewallRuleCmd.java b/api/src/org/apache/cloudstack/api/command/user/firewall/DeleteFirewallRuleCmd.java index 5655b5e430f..8b0a5c16e07 100644 --- a/api/src/org/apache/cloudstack/api/command/user/firewall/DeleteFirewallRuleCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/firewall/DeleteFirewallRuleCmd.java @@ -95,7 +95,7 @@ public class DeleteFirewallRuleCmd extends BaseAsyncCmd { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete firewall rule"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete firewall rule"); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/firewall/DeletePortForwardingRuleCmd.java b/api/src/org/apache/cloudstack/api/command/user/firewall/DeletePortForwardingRuleCmd.java index 8f4d5996df8..e70bb1556df 100644 --- a/api/src/org/apache/cloudstack/api/command/user/firewall/DeletePortForwardingRuleCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/firewall/DeletePortForwardingRuleCmd.java @@ -97,7 +97,7 @@ public class DeletePortForwardingRuleCmd extends BaseAsyncCmd { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete port forwarding rule"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete port forwarding rule"); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/firewall/UpdatePortForwardingRuleCmd.java b/api/src/org/apache/cloudstack/api/command/user/firewall/UpdatePortForwardingRuleCmd.java index a52ebb77257..2eafaaf7293 100644 --- a/api/src/org/apache/cloudstack/api/command/user/firewall/UpdatePortForwardingRuleCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/firewall/UpdatePortForwardingRuleCmd.java @@ -124,7 +124,7 @@ public class UpdatePortForwardingRuleCmd extends BaseAsyncCmd { // response.setResponseName(getName()); // this.setResponseObject(response); // } else { -// throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update port forwarding rule"); +// throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update port forwarding rule"); // } } } diff --git a/api/src/org/apache/cloudstack/api/command/user/iso/AttachIsoCmd.java b/api/src/org/apache/cloudstack/api/command/user/iso/AttachIsoCmd.java index 1e154e2a07d..2a0b2c61617 100644 --- a/api/src/org/apache/cloudstack/api/command/user/iso/AttachIsoCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/iso/AttachIsoCmd.java @@ -21,6 +21,7 @@ import org.apache.cloudstack.api.response.TemplateResponse; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -104,10 +105,10 @@ public class AttachIsoCmd extends BaseAsyncCmd { response.setResponseName(DeployVMCmd.getResultObjectName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to attach iso"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to attach iso"); } } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to attach iso"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to attach iso"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/user/iso/DeleteIsoCmd.java b/api/src/org/apache/cloudstack/api/command/user/iso/DeleteIsoCmd.java index 44efbf88f2c..4c370c70325 100644 --- a/api/src/org/apache/cloudstack/api/command/user/iso/DeleteIsoCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/iso/DeleteIsoCmd.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.api.command.user.iso; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -112,7 +113,7 @@ public class DeleteIsoCmd extends BaseAsyncCmd { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete iso"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete iso"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/user/iso/DetachIsoCmd.java b/api/src/org/apache/cloudstack/api/command/user/iso/DetachIsoCmd.java index eb1c6eed2d6..c8a87cbdb3e 100644 --- a/api/src/org/apache/cloudstack/api/command/user/iso/DetachIsoCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/iso/DetachIsoCmd.java @@ -21,6 +21,7 @@ import org.apache.cloudstack.api.response.TemplateResponse; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -91,7 +92,7 @@ public class DetachIsoCmd extends BaseAsyncCmd { response.setResponseName(DeployVMCmd.getResultObjectName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to detach iso"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to detach iso"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/user/iso/ExtractIsoCmd.java b/api/src/org/apache/cloudstack/api/command/user/iso/ExtractIsoCmd.java index 5f8303ec320..7f893ccd06d 100644 --- a/api/src/org/apache/cloudstack/api/command/user/iso/ExtractIsoCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/iso/ExtractIsoCmd.java @@ -126,11 +126,11 @@ public class ExtractIsoCmd extends BaseAsyncCmd { response.setObjectName("iso"); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to extract iso"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to extract iso"); } } catch (InternalErrorException ex) { s_logger.warn("Exception: ", ex); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } } diff --git a/api/src/org/apache/cloudstack/api/command/user/iso/RegisterIsoCmd.java b/api/src/org/apache/cloudstack/api/command/user/iso/RegisterIsoCmd.java index 214d18de5cc..fbc09d8bd56 100644 --- a/api/src/org/apache/cloudstack/api/command/user/iso/RegisterIsoCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/iso/RegisterIsoCmd.java @@ -166,7 +166,7 @@ public class RegisterIsoCmd extends BaseCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to register iso"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to register iso"); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/iso/UpdateIsoCmd.java b/api/src/org/apache/cloudstack/api/command/user/iso/UpdateIsoCmd.java index f54f8a66daa..fd1ee3e22de 100644 --- a/api/src/org/apache/cloudstack/api/command/user/iso/UpdateIsoCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/iso/UpdateIsoCmd.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.api.command.user.iso; import org.apache.cloudstack.api.BaseUpdateTemplateOrIsoCmd; import org.apache.log4j.Logger; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ServerApiException; @@ -72,7 +73,7 @@ public class UpdateIsoCmd extends BaseUpdateTemplateOrIsoCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update iso"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update iso"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/user/loadbalancer/AssignToLoadBalancerRuleCmd.java b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/AssignToLoadBalancerRuleCmd.java index 972673f4954..72c317c89d2 100644 --- a/api/src/org/apache/cloudstack/api/command/user/loadbalancer/AssignToLoadBalancerRuleCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/AssignToLoadBalancerRuleCmd.java @@ -23,6 +23,7 @@ import org.apache.cloudstack.api.response.UserVmResponse; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -102,7 +103,7 @@ public class AssignToLoadBalancerRuleCmd extends BaseAsyncCmd { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to assign load balancer rule"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to assign load balancer rule"); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/loadbalancer/CreateLBStickinessPolicyCmd.java b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/CreateLBStickinessPolicyCmd.java index c01e138c1d1..90e89137bf9 100644 --- a/api/src/org/apache/cloudstack/api/command/user/loadbalancer/CreateLBStickinessPolicyCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/CreateLBStickinessPolicyCmd.java @@ -23,6 +23,7 @@ import org.apache.cloudstack.api.response.FirewallRuleResponse; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCreateCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -129,7 +130,7 @@ public class CreateLBStickinessPolicyCmd extends BaseAsyncCreateCmd { } } finally { if (!success || (policy == null)) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create stickiness policy "); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create stickiness policy "); } } } @@ -142,7 +143,7 @@ public class CreateLBStickinessPolicyCmd extends BaseAsyncCreateCmd { this.setEntityUuid(result.getUuid()); } catch (NetworkRuleConflictException e) { s_logger.warn("Exception: ", e); - throw new ServerApiException(BaseCmd.NETWORK_RULE_CONFLICT_ERROR, e.getMessage()); + throw new ServerApiException(ApiErrorCode.NETWORK_RULE_CONFLICT_ERROR, e.getMessage()); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/loadbalancer/CreateLoadBalancerRuleCmd.java b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/CreateLoadBalancerRuleCmd.java index 4e76a6b676f..b42ff4cc5f1 100644 --- a/api/src/org/apache/cloudstack/api/command/user/loadbalancer/CreateLoadBalancerRuleCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/CreateLoadBalancerRuleCmd.java @@ -21,6 +21,7 @@ import java.util.List; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCreateCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -266,7 +267,7 @@ public class CreateLoadBalancerRuleCmd extends BaseAsyncCreateCmd /*implements // no need to apply the rule on the backend as it exists in the db only _lbService.deleteLoadBalancerRule(getEntityId(), false); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create load balancer rule"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create load balancer rule"); } } } @@ -283,10 +284,10 @@ public class CreateLoadBalancerRuleCmd extends BaseAsyncCreateCmd /*implements this.setEntityUuid(result.getUuid()); } catch (NetworkRuleConflictException e) { s_logger.warn("Exception: ", e); - throw new ServerApiException(BaseCmd.NETWORK_RULE_CONFLICT_ERROR, e.getMessage()); + throw new ServerApiException(ApiErrorCode.NETWORK_RULE_CONFLICT_ERROR, e.getMessage()); } catch (InsufficientAddressCapacityException e) { s_logger.warn("Exception: ", e); - throw new ServerApiException(BaseCmd.INSUFFICIENT_CAPACITY_ERROR, e.getMessage()); + throw new ServerApiException(ApiErrorCode.INSUFFICIENT_CAPACITY_ERROR, e.getMessage()); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/loadbalancer/DeleteLBStickinessPolicyCmd.java b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/DeleteLBStickinessPolicyCmd.java index 9329bd35aba..6405dca169b 100644 --- a/api/src/org/apache/cloudstack/api/command/user/loadbalancer/DeleteLBStickinessPolicyCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/DeleteLBStickinessPolicyCmd.java @@ -20,6 +20,7 @@ import org.apache.cloudstack.api.response.LBStickinessResponse; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -91,7 +92,7 @@ public class DeleteLBStickinessPolicyCmd extends BaseAsyncCmd { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete load balancer stickiness policy"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete load balancer stickiness policy"); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/loadbalancer/DeleteLoadBalancerRuleCmd.java b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/DeleteLoadBalancerRuleCmd.java index d53155f17b9..84ce225fa1e 100644 --- a/api/src/org/apache/cloudstack/api/command/user/loadbalancer/DeleteLoadBalancerRuleCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/DeleteLoadBalancerRuleCmd.java @@ -89,7 +89,7 @@ public class DeleteLoadBalancerRuleCmd extends BaseAsyncCmd { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete load balancer"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete load balancer"); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/loadbalancer/RemoveFromLoadBalancerRuleCmd.java b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/RemoveFromLoadBalancerRuleCmd.java index f56f06d15c5..54c136fae6d 100644 --- a/api/src/org/apache/cloudstack/api/command/user/loadbalancer/RemoveFromLoadBalancerRuleCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/RemoveFromLoadBalancerRuleCmd.java @@ -98,7 +98,7 @@ public class RemoveFromLoadBalancerRuleCmd extends BaseAsyncCmd { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to remove instance from load balancer rule"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to remove instance from load balancer rule"); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/loadbalancer/UpdateLoadBalancerRuleCmd.java b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/UpdateLoadBalancerRuleCmd.java index 8a86f74260d..dd2b360ec23 100644 --- a/api/src/org/apache/cloudstack/api/command/user/loadbalancer/UpdateLoadBalancerRuleCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/UpdateLoadBalancerRuleCmd.java @@ -106,7 +106,7 @@ public class UpdateLoadBalancerRuleCmd extends BaseAsyncCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update load balancer rule"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update load balancer rule"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/user/nat/CreateIpForwardingRuleCmd.java b/api/src/org/apache/cloudstack/api/command/user/nat/CreateIpForwardingRuleCmd.java index 1ce3458dde3..c3894c47f57 100644 --- a/api/src/org/apache/cloudstack/api/command/user/nat/CreateIpForwardingRuleCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/nat/CreateIpForwardingRuleCmd.java @@ -22,6 +22,7 @@ import org.apache.cloudstack.api.response.IPAddressResponse; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseAsyncCreateCmd; import org.apache.cloudstack.api.BaseCmd; @@ -132,7 +133,7 @@ public class CreateIpForwardingRuleCmd extends BaseAsyncCreateCmd implements Sta _rulesService.revokeStaticNatRule(getEntityId(), true); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Error in creating ip forwarding rule on the domr"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Error in creating ip forwarding rule on the domr"); } } } @@ -151,7 +152,7 @@ public class CreateIpForwardingRuleCmd extends BaseAsyncCreateCmd implements Sta this.setEntityUuid(rule.getUuid()); } catch (NetworkRuleConflictException e) { s_logger.info("Unable to create Static Nat Rule due to ", e); - throw new ServerApiException(BaseCmd.NETWORK_RULE_CONFLICT_ERROR, e.getMessage()); + throw new ServerApiException(ApiErrorCode.NETWORK_RULE_CONFLICT_ERROR, e.getMessage()); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/nat/DeleteIpForwardingRuleCmd.java b/api/src/org/apache/cloudstack/api/command/user/nat/DeleteIpForwardingRuleCmd.java index 6300a412d54..9879cf5011b 100644 --- a/api/src/org/apache/cloudstack/api/command/user/nat/DeleteIpForwardingRuleCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/nat/DeleteIpForwardingRuleCmd.java @@ -21,6 +21,7 @@ import org.apache.cloudstack.api.response.FirewallRuleResponse; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -78,7 +79,7 @@ public class DeleteIpForwardingRuleCmd extends BaseAsyncCmd { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete ip forwarding rule"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete ip forwarding rule"); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/nat/DisableStaticNatCmd.java b/api/src/org/apache/cloudstack/api/command/user/nat/DisableStaticNatCmd.java index fbd0b5ce900..eded5a10742 100644 --- a/api/src/org/apache/cloudstack/api/command/user/nat/DisableStaticNatCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/nat/DisableStaticNatCmd.java @@ -21,6 +21,7 @@ import org.apache.cloudstack.api.response.IPAddressResponse; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -86,7 +87,7 @@ public class DisableStaticNatCmd extends BaseAsyncCmd { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to disable static nat"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to disable static nat"); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/nat/EnableStaticNatCmd.java b/api/src/org/apache/cloudstack/api/command/user/nat/EnableStaticNatCmd.java index 79a8e2bc9ff..f7cf5aad5d0 100644 --- a/api/src/org/apache/cloudstack/api/command/user/nat/EnableStaticNatCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/nat/EnableStaticNatCmd.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.api.command.user.nat; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.Parameter; @@ -114,12 +115,12 @@ public class EnableStaticNatCmd extends BaseCmd{ SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to enable static nat"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to enable static nat"); } } catch (NetworkRuleConflictException ex) { s_logger.info("Network rule conflict: " + ex.getMessage()); s_logger.trace("Network Rule Conflict: ", ex); - throw new ServerApiException(BaseCmd.NETWORK_RULE_CONFLICT_ERROR, ex.getMessage()); + throw new ServerApiException(ApiErrorCode.NETWORK_RULE_CONFLICT_ERROR, ex.getMessage()); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/network/CreateNetworkACLCmd.java b/api/src/org/apache/cloudstack/api/command/user/network/CreateNetworkACLCmd.java index 16843b56d67..d1289b8ddc6 100644 --- a/api/src/org/apache/cloudstack/api/command/user/network/CreateNetworkACLCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/network/CreateNetworkACLCmd.java @@ -23,6 +23,7 @@ import org.apache.cloudstack.api.response.NetworkResponse; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseAsyncCreateCmd; import org.apache.cloudstack.api.BaseCmd; @@ -164,7 +165,7 @@ public class CreateNetworkACLCmd extends BaseAsyncCreateCmd implements FirewallR } finally { if (!success || rule == null) { _networkACLService.revokeNetworkACL(getEntityId(), true); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create network ACL"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create network ACL"); } } } @@ -250,7 +251,7 @@ public class CreateNetworkACLCmd extends BaseAsyncCreateCmd implements FirewallR if (getSourceCidrList() != null) { for (String cidr: getSourceCidrList()){ if (!NetUtils.isValidCIDR(cidr)){ - throw new ServerApiException(BaseCmd.PARAM_ERROR, "Source cidrs formatting error " + cidr); + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Source cidrs formatting error " + cidr); } } } @@ -262,7 +263,7 @@ public class CreateNetworkACLCmd extends BaseAsyncCreateCmd implements FirewallR } catch (NetworkRuleConflictException ex) { s_logger.info("Network rule conflict: " + ex.getMessage()); s_logger.trace("Network Rule Conflict: ", ex); - throw new ServerApiException(BaseCmd.NETWORK_RULE_CONFLICT_ERROR, ex.getMessage()); + throw new ServerApiException(ApiErrorCode.NETWORK_RULE_CONFLICT_ERROR, ex.getMessage()); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/network/CreateNetworkCmd.java b/api/src/org/apache/cloudstack/api/command/user/network/CreateNetworkCmd.java index 3b2608729a4..870a591bb36 100644 --- a/api/src/org/apache/cloudstack/api/command/user/network/CreateNetworkCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/network/CreateNetworkCmd.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.api.command.user.network; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.Parameter; @@ -233,7 +234,7 @@ public class CreateNetworkCmd extends BaseCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); }else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create network"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create network"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/user/network/DeleteNetworkACLCmd.java b/api/src/org/apache/cloudstack/api/command/user/network/DeleteNetworkACLCmd.java index 4b078ed7fe3..798bd43aa0b 100644 --- a/api/src/org/apache/cloudstack/api/command/user/network/DeleteNetworkACLCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/network/DeleteNetworkACLCmd.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.api.command.user.network; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -99,7 +100,7 @@ public class DeleteNetworkACLCmd extends BaseAsyncCmd { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete network ACL"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete network ACL"); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/network/DeleteNetworkCmd.java b/api/src/org/apache/cloudstack/api/command/user/network/DeleteNetworkCmd.java index df070ff8ecb..2104501d9c2 100644 --- a/api/src/org/apache/cloudstack/api/command/user/network/DeleteNetworkCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/network/DeleteNetworkCmd.java @@ -68,7 +68,7 @@ public class DeleteNetworkCmd extends BaseAsyncCmd{ SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete network"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete network"); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/network/RestartNetworkCmd.java b/api/src/org/apache/cloudstack/api/command/user/network/RestartNetworkCmd.java index ee9af3b0009..c6b5690aeaf 100644 --- a/api/src/org/apache/cloudstack/api/command/user/network/RestartNetworkCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/network/RestartNetworkCmd.java @@ -90,7 +90,7 @@ public class RestartNetworkCmd extends BaseAsyncCmd { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to restart network"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to restart network"); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/network/UpdateNetworkCmd.java b/api/src/org/apache/cloudstack/api/command/user/network/UpdateNetworkCmd.java index 5ab8a6035ad..978c71b946c 100644 --- a/api/src/org/apache/cloudstack/api/command/user/network/UpdateNetworkCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/network/UpdateNetworkCmd.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.api.command.user.network; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -136,7 +137,7 @@ public class UpdateNetworkCmd extends BaseAsyncCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update network"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update network"); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/project/ActivateProjectCmd.java b/api/src/org/apache/cloudstack/api/command/user/project/ActivateProjectCmd.java index 6cc9387ac2b..8fd52753d77 100644 --- a/api/src/org/apache/cloudstack/api/command/user/project/ActivateProjectCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/project/ActivateProjectCmd.java @@ -79,7 +79,7 @@ public class ActivateProjectCmd extends BaseAsyncCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to activate a project"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to activate a project"); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/project/CreateProjectCmd.java b/api/src/org/apache/cloudstack/api/command/user/project/CreateProjectCmd.java index 865f7a0aa99..095cbfc49b8 100644 --- a/api/src/org/apache/cloudstack/api/command/user/project/CreateProjectCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/project/CreateProjectCmd.java @@ -114,7 +114,7 @@ public class CreateProjectCmd extends BaseAsyncCreateCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create a project"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create a project"); } } @@ -126,7 +126,7 @@ public class CreateProjectCmd extends BaseAsyncCreateCmd { this.setEntityId(project.getId()); this.setEntityUuid(project.getUuid()); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create a project"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create a project"); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/project/DeleteProjectCmd.java b/api/src/org/apache/cloudstack/api/command/user/project/DeleteProjectCmd.java index fb41a7f14ef..6f7467fadf8 100644 --- a/api/src/org/apache/cloudstack/api/command/user/project/DeleteProjectCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/project/DeleteProjectCmd.java @@ -20,6 +20,7 @@ import org.apache.cloudstack.api.response.ProjectResponse; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -71,7 +72,7 @@ public class DeleteProjectCmd extends BaseAsyncCmd { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete project"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete project"); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/project/DeleteProjectInvitationCmd.java b/api/src/org/apache/cloudstack/api/command/user/project/DeleteProjectInvitationCmd.java index 67c7cefc252..7ed857e575b 100644 --- a/api/src/org/apache/cloudstack/api/command/user/project/DeleteProjectInvitationCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/project/DeleteProjectInvitationCmd.java @@ -20,6 +20,7 @@ import org.apache.cloudstack.api.response.ProjectInvitationResponse; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -72,7 +73,7 @@ public class DeleteProjectInvitationCmd extends BaseAsyncCmd { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete the project invitation"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete the project invitation"); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/project/SuspendProjectCmd.java b/api/src/org/apache/cloudstack/api/command/user/project/SuspendProjectCmd.java index 120e4fe0c55..01e4082c193 100644 --- a/api/src/org/apache/cloudstack/api/command/user/project/SuspendProjectCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/project/SuspendProjectCmd.java @@ -69,7 +69,7 @@ public class SuspendProjectCmd extends BaseAsyncCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to suspend a project"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to suspend a project"); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/project/UpdateProjectCmd.java b/api/src/org/apache/cloudstack/api/command/user/project/UpdateProjectCmd.java index bad117727e0..01f56311d17 100644 --- a/api/src/org/apache/cloudstack/api/command/user/project/UpdateProjectCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/project/UpdateProjectCmd.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.api.command.user.project; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -97,7 +98,7 @@ public class UpdateProjectCmd extends BaseAsyncCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update a project"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update a project"); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/project/UpdateProjectInvitationCmd.java b/api/src/org/apache/cloudstack/api/command/user/project/UpdateProjectInvitationCmd.java index 32e1a755484..637c6339521 100644 --- a/api/src/org/apache/cloudstack/api/command/user/project/UpdateProjectInvitationCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/project/UpdateProjectInvitationCmd.java @@ -92,7 +92,7 @@ public class UpdateProjectInvitationCmd extends BaseAsyncCmd { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to join the project"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to join the project"); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/resource/GetCloudIdentifierCmd.java b/api/src/org/apache/cloudstack/api/command/user/resource/GetCloudIdentifierCmd.java index 0d62c18f55d..5799db26d7a 100644 --- a/api/src/org/apache/cloudstack/api/command/user/resource/GetCloudIdentifierCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/resource/GetCloudIdentifierCmd.java @@ -21,6 +21,7 @@ import java.util.ArrayList; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.Parameter; @@ -74,7 +75,7 @@ public class GetCloudIdentifierCmd extends BaseCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to get cloud identifier"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to get cloud identifier"); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/resource/UpdateResourceCountCmd.java b/api/src/org/apache/cloudstack/api/command/user/resource/UpdateResourceCountCmd.java index d2b6870f0ca..4aa694b6857 100644 --- a/api/src/org/apache/cloudstack/api/command/user/resource/UpdateResourceCountCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/resource/UpdateResourceCountCmd.java @@ -123,7 +123,7 @@ public class UpdateResourceCountCmd extends BaseCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to recalculate resource counts"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to recalculate resource counts"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/user/resource/UpdateResourceLimitCmd.java b/api/src/org/apache/cloudstack/api/command/user/resource/UpdateResourceLimitCmd.java index 262d12dc264..9b6359fcc4c 100644 --- a/api/src/org/apache/cloudstack/api/command/user/resource/UpdateResourceLimitCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/resource/UpdateResourceLimitCmd.java @@ -100,7 +100,7 @@ public class UpdateResourceLimitCmd extends BaseCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update resource limit"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update resource limit"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/user/securitygroup/AuthorizeSecurityGroupEgressCmd.java b/api/src/org/apache/cloudstack/api/command/user/securitygroup/AuthorizeSecurityGroupEgressCmd.java index acafcbe19a9..0551089f033 100644 --- a/api/src/org/apache/cloudstack/api/command/user/securitygroup/AuthorizeSecurityGroupEgressCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/securitygroup/AuthorizeSecurityGroupEgressCmd.java @@ -206,7 +206,7 @@ public class AuthorizeSecurityGroupEgressCmd extends BaseAsyncCmd { SecurityGroupResponse response = _responseGenerator.createSecurityGroupResponseFromSecurityGroupRule(egressRules); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to authorize security group egress rule(s)"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to authorize security group egress rule(s)"); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/securitygroup/AuthorizeSecurityGroupIngressCmd.java b/api/src/org/apache/cloudstack/api/command/user/securitygroup/AuthorizeSecurityGroupIngressCmd.java index abd20fcc81d..35939d36659 100644 --- a/api/src/org/apache/cloudstack/api/command/user/securitygroup/AuthorizeSecurityGroupIngressCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/securitygroup/AuthorizeSecurityGroupIngressCmd.java @@ -25,6 +25,7 @@ import java.util.Map; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -210,7 +211,7 @@ public class AuthorizeSecurityGroupIngressCmd extends BaseAsyncCmd { if(cidrList != null){ for(String cidr : cidrList ){ if (!NetUtils.isValidCIDR(cidr)){ - throw new ServerApiException(BaseCmd.PARAM_ERROR, cidr + " is an Invalid CIDR "); + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, cidr + " is an Invalid CIDR "); } } } @@ -219,7 +220,7 @@ public class AuthorizeSecurityGroupIngressCmd extends BaseAsyncCmd { SecurityGroupResponse response = _responseGenerator.createSecurityGroupResponseFromSecurityGroupRule(ingressRules); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to authorize security group ingress rule(s)"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to authorize security group ingress rule(s)"); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/securitygroup/CreateSecurityGroupCmd.java b/api/src/org/apache/cloudstack/api/command/user/securitygroup/CreateSecurityGroupCmd.java index c494355e15e..5dc49291426 100644 --- a/api/src/org/apache/cloudstack/api/command/user/securitygroup/CreateSecurityGroupCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/securitygroup/CreateSecurityGroupCmd.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.api.command.user.securitygroup; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.Parameter; @@ -116,7 +117,7 @@ public class CreateSecurityGroupCmd extends BaseCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create security group"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create security group"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/user/securitygroup/DeleteSecurityGroupCmd.java b/api/src/org/apache/cloudstack/api/command/user/securitygroup/DeleteSecurityGroupCmd.java index 15a00253b63..506dc53ff23 100644 --- a/api/src/org/apache/cloudstack/api/command/user/securitygroup/DeleteSecurityGroupCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/securitygroup/DeleteSecurityGroupCmd.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.api.command.user.securitygroup; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.Parameter; @@ -120,11 +121,11 @@ public class DeleteSecurityGroupCmd extends BaseCmd { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete security group"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete security group"); } } catch (ResourceInUseException ex) { s_logger.warn("Exception: ", ex); - throw new ServerApiException(BaseCmd.RESOURCE_IN_USE_ERROR, ex.getMessage()); + throw new ServerApiException(ApiErrorCode.RESOURCE_IN_USE_ERROR, ex.getMessage()); } } } diff --git a/api/src/org/apache/cloudstack/api/command/user/securitygroup/RevokeSecurityGroupEgressCmd.java b/api/src/org/apache/cloudstack/api/command/user/securitygroup/RevokeSecurityGroupEgressCmd.java index 53d8fcf59c7..27072fcb6c3 100644 --- a/api/src/org/apache/cloudstack/api/command/user/securitygroup/RevokeSecurityGroupEgressCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/securitygroup/RevokeSecurityGroupEgressCmd.java @@ -88,7 +88,7 @@ public class RevokeSecurityGroupEgressCmd extends BaseAsyncCmd { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to revoke security group egress rule"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to revoke security group egress rule"); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/securitygroup/RevokeSecurityGroupIngressCmd.java b/api/src/org/apache/cloudstack/api/command/user/securitygroup/RevokeSecurityGroupIngressCmd.java index 1f56dee9bca..70851cf1e41 100644 --- a/api/src/org/apache/cloudstack/api/command/user/securitygroup/RevokeSecurityGroupIngressCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/securitygroup/RevokeSecurityGroupIngressCmd.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.api.command.user.securitygroup; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -92,7 +93,7 @@ public class RevokeSecurityGroupIngressCmd extends BaseAsyncCmd { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to revoke security group ingress rule"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to revoke security group ingress rule"); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/snapshot/CreateSnapshotCmd.java b/api/src/org/apache/cloudstack/api/command/user/snapshot/CreateSnapshotCmd.java index 14f46540cc3..49158a64d17 100644 --- a/api/src/org/apache/cloudstack/api/command/user/snapshot/CreateSnapshotCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/snapshot/CreateSnapshotCmd.java @@ -152,7 +152,7 @@ public class CreateSnapshotCmd extends BaseAsyncCreateCmd { this.setEntityId(snapshot.getId()); this.setEntityUuid(snapshot.getUuid()); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create snapshot"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create snapshot"); } } @@ -165,7 +165,7 @@ public class CreateSnapshotCmd extends BaseAsyncCreateCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create snapshot due to an internal error creating snapshot for volume " + volumeId); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create snapshot due to an internal error creating snapshot for volume " + volumeId); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/snapshot/CreateSnapshotPolicyCmd.java b/api/src/org/apache/cloudstack/api/command/user/snapshot/CreateSnapshotPolicyCmd.java index cafb79e0523..756a93aa8f4 100644 --- a/api/src/org/apache/cloudstack/api/command/user/snapshot/CreateSnapshotPolicyCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/snapshot/CreateSnapshotPolicyCmd.java @@ -126,7 +126,7 @@ public class CreateSnapshotPolicyCmd extends BaseCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create snapshot policy"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create snapshot policy"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/user/snapshot/DeleteSnapshotCmd.java b/api/src/org/apache/cloudstack/api/command/user/snapshot/DeleteSnapshotCmd.java index 6def8730cbd..dc0b8ee8138 100644 --- a/api/src/org/apache/cloudstack/api/command/user/snapshot/DeleteSnapshotCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/snapshot/DeleteSnapshotCmd.java @@ -94,7 +94,7 @@ public class DeleteSnapshotCmd extends BaseAsyncCmd { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete snapshot"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete snapshot"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/user/snapshot/DeleteSnapshotPoliciesCmd.java b/api/src/org/apache/cloudstack/api/command/user/snapshot/DeleteSnapshotPoliciesCmd.java index 17f28d931ea..0207f3c3416 100644 --- a/api/src/org/apache/cloudstack/api/command/user/snapshot/DeleteSnapshotPoliciesCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/snapshot/DeleteSnapshotPoliciesCmd.java @@ -21,6 +21,7 @@ import java.util.List; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.Parameter; @@ -80,7 +81,7 @@ public class DeleteSnapshotPoliciesCmd extends BaseCmd { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete snapshot policy"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete snapshot policy"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/user/tag/CreateTagsCmd.java b/api/src/org/apache/cloudstack/api/command/user/tag/CreateTagsCmd.java index 54338bd24e2..9c108b4904c 100644 --- a/api/src/org/apache/cloudstack/api/command/user/tag/CreateTagsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/tag/CreateTagsCmd.java @@ -26,6 +26,7 @@ import java.util.Map; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -115,7 +116,7 @@ public class CreateTagsCmd extends BaseAsyncCmd{ SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create tags"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create tags"); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/tag/DeleteTagsCmd.java b/api/src/org/apache/cloudstack/api/command/user/tag/DeleteTagsCmd.java index cf2ea9ec1cb..c142f141f86 100644 --- a/api/src/org/apache/cloudstack/api/command/user/tag/DeleteTagsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/tag/DeleteTagsCmd.java @@ -26,6 +26,7 @@ import java.util.Map; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -106,7 +107,7 @@ public class DeleteTagsCmd extends BaseAsyncCmd{ SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete tags"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete tags"); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/template/CopyTemplateCmd.java b/api/src/org/apache/cloudstack/api/command/user/template/CopyTemplateCmd.java index c6461a75e28..406f32cc958 100644 --- a/api/src/org/apache/cloudstack/api/command/user/template/CopyTemplateCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/template/CopyTemplateCmd.java @@ -21,6 +21,7 @@ import java.util.List; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -133,11 +134,11 @@ public class CopyTemplateCmd extends BaseAsyncCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to copy template"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to copy template"); } } catch (StorageUnavailableException ex) { s_logger.warn("Exception: ", ex); - throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); + throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } } } diff --git a/api/src/org/apache/cloudstack/api/command/user/template/CreateTemplateCmd.java b/api/src/org/apache/cloudstack/api/command/user/template/CreateTemplateCmd.java index e72b49b4e4d..9723f9a14a1 100644 --- a/api/src/org/apache/cloudstack/api/command/user/template/CreateTemplateCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/template/CreateTemplateCmd.java @@ -247,7 +247,7 @@ import com.cloud.user.UserContext; this.setEntityId(template.getId()); this.setEntityUuid(template.getUuid()); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create a template"); } } @@ -277,7 +277,7 @@ import com.cloud.user.UserContext; response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create private template"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create private template"); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/template/DeleteTemplateCmd.java b/api/src/org/apache/cloudstack/api/command/user/template/DeleteTemplateCmd.java index 26f3e841f68..8ee3041713c 100644 --- a/api/src/org/apache/cloudstack/api/command/user/template/DeleteTemplateCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/template/DeleteTemplateCmd.java @@ -109,7 +109,7 @@ public class DeleteTemplateCmd extends BaseAsyncCmd { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete template"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete template"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/user/template/ExtractTemplateCmd.java b/api/src/org/apache/cloudstack/api/command/user/template/ExtractTemplateCmd.java index 521293cb275..54f3e3782fb 100644 --- a/api/src/org/apache/cloudstack/api/command/user/template/ExtractTemplateCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/template/ExtractTemplateCmd.java @@ -126,11 +126,11 @@ public class ExtractTemplateCmd extends BaseAsyncCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to extract template"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to extract template"); } } catch (InternalErrorException ex) { s_logger.warn("Exception: ", ex); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } } diff --git a/api/src/org/apache/cloudstack/api/command/user/template/RegisterTemplateCmd.java b/api/src/org/apache/cloudstack/api/command/user/template/RegisterTemplateCmd.java index b3677b9d3a1..cc4c52486e7 100644 --- a/api/src/org/apache/cloudstack/api/command/user/template/RegisterTemplateCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/template/RegisterTemplateCmd.java @@ -24,6 +24,7 @@ import java.util.Map; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.Parameter; @@ -233,11 +234,11 @@ public class RegisterTemplateCmd extends BaseCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to register template"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to register template"); } } catch (URISyntaxException ex1) { s_logger.info(ex1); - throw new ServerApiException(BaseCmd.PARAM_ERROR, ex1.getMessage()); + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, ex1.getMessage()); } } } diff --git a/api/src/org/apache/cloudstack/api/command/user/template/UpdateTemplateCmd.java b/api/src/org/apache/cloudstack/api/command/user/template/UpdateTemplateCmd.java index 01ea200293e..8893e8faeef 100644 --- a/api/src/org/apache/cloudstack/api/command/user/template/UpdateTemplateCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/template/UpdateTemplateCmd.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.api.command.user.template; import org.apache.cloudstack.api.BaseUpdateTemplateOrIsoCmd; import org.apache.log4j.Logger; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ServerApiException; @@ -73,7 +74,7 @@ public class UpdateTemplateCmd extends BaseUpdateTemplateOrIsoCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update template"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update template"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/user/vm/DeployVMCmd.java b/api/src/org/apache/cloudstack/api/command/user/vm/DeployVMCmd.java index e675c83dd6f..9d39f692eaf 100644 --- a/api/src/org/apache/cloudstack/api/command/user/vm/DeployVMCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vm/DeployVMCmd.java @@ -364,14 +364,14 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { } } catch (ResourceUnavailableException ex) { s_logger.warn("Exception: ", ex); - throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); + throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } catch (ConcurrentOperationException ex) { s_logger.warn("Exception: ", ex); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } catch (InsufficientCapacityException ex) { s_logger.info(ex); s_logger.trace(ex); - throw new ServerApiException(BaseCmd.INSUFFICIENT_CAPACITY_ERROR, ex.getMessage()); + throw new ServerApiException(ApiErrorCode.INSUFFICIENT_CAPACITY_ERROR, ex.getMessage()); } } else { result = _userVmService.getUserVm(getEntityId()); @@ -382,7 +382,7 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to deploy vm"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to deploy vm"); } } @@ -454,18 +454,18 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { setEntityId(vm.getId()); setEntityUuid(vm.getUuid()); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to deploy vm"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to deploy vm"); } } catch (InsufficientCapacityException ex) { s_logger.info(ex); s_logger.trace(ex); - throw new ServerApiException(BaseCmd.INSUFFICIENT_CAPACITY_ERROR, ex.getMessage()); + throw new ServerApiException(ApiErrorCode.INSUFFICIENT_CAPACITY_ERROR, ex.getMessage()); } catch (ResourceUnavailableException ex) { s_logger.warn("Exception: ", ex); - throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); + throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } catch (ConcurrentOperationException ex) { s_logger.warn("Exception: ", ex); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } } diff --git a/api/src/org/apache/cloudstack/api/command/user/vm/DestroyVMCmd.java b/api/src/org/apache/cloudstack/api/command/user/vm/DestroyVMCmd.java index db830d1a188..381f5b744b8 100644 --- a/api/src/org/apache/cloudstack/api/command/user/vm/DestroyVMCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vm/DestroyVMCmd.java @@ -104,7 +104,7 @@ public class DestroyVMCmd extends BaseAsyncCmd { response.setResponseName("virtualmachine"); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to destroy vm"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to destroy vm"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/user/vm/RebootVMCmd.java b/api/src/org/apache/cloudstack/api/command/user/vm/RebootVMCmd.java index 45ebc287913..63319dc6853 100644 --- a/api/src/org/apache/cloudstack/api/command/user/vm/RebootVMCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vm/RebootVMCmd.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.api.command.user.vm; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -107,7 +108,7 @@ public class RebootVMCmd extends BaseAsyncCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to reboot vm instance"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to reboot vm instance"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/user/vm/ResetVMPasswordCmd.java b/api/src/org/apache/cloudstack/api/command/user/vm/ResetVMPasswordCmd.java index a4c2b3772e9..2ca94bf6a89 100644 --- a/api/src/org/apache/cloudstack/api/command/user/vm/ResetVMPasswordCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vm/ResetVMPasswordCmd.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.api.command.user.vm; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -116,7 +117,7 @@ public class ResetVMPasswordCmd extends BaseAsyncCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to reset vm password"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to reset vm password"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/user/vm/RestoreVMCmd.java b/api/src/org/apache/cloudstack/api/command/user/vm/RestoreVMCmd.java index 9b2452e355d..d906c7f6343 100644 --- a/api/src/org/apache/cloudstack/api/command/user/vm/RestoreVMCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vm/RestoreVMCmd.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.api.command.user.vm; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -64,7 +65,7 @@ public class RestoreVMCmd extends BaseAsyncCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to restore vm " + getVmId()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to restore vm " + getVmId()); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/vm/StartVMCmd.java b/api/src/org/apache/cloudstack/api/command/user/vm/StartVMCmd.java index 36199d13c24..65391f7f8ff 100644 --- a/api/src/org/apache/cloudstack/api/command/user/vm/StartVMCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vm/StartVMCmd.java @@ -125,17 +125,17 @@ public class StartVMCmd extends BaseAsyncCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to start a vm"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to start a vm"); } } catch (ConcurrentOperationException ex) { s_logger.warn("Exception: ", ex); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } catch (StorageUnavailableException ex) { s_logger.warn("Exception: ", ex); - throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); + throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } catch (ExecutionException ex) { s_logger.warn("Exception: ", ex); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/vm/StopVMCmd.java b/api/src/org/apache/cloudstack/api/command/user/vm/StopVMCmd.java index 8e589060520..cfa89a54249 100644 --- a/api/src/org/apache/cloudstack/api/command/user/vm/StopVMCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vm/StopVMCmd.java @@ -120,7 +120,7 @@ public class StopVMCmd extends BaseAsyncCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to stop vm"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to stop vm"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/user/vm/UpdateVMCmd.java b/api/src/org/apache/cloudstack/api/command/user/vm/UpdateVMCmd.java index 7f1e7efdc1a..60b23389ddd 100644 --- a/api/src/org/apache/cloudstack/api/command/user/vm/UpdateVMCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vm/UpdateVMCmd.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.api.command.user.vm; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.Parameter; @@ -126,7 +127,7 @@ public class UpdateVMCmd extends BaseCmd{ response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update vm"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update vm"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/user/vm/UpgradeVMCmd.java b/api/src/org/apache/cloudstack/api/command/user/vm/UpgradeVMCmd.java index f2c3882bd3c..6c2e0f1eb54 100644 --- a/api/src/org/apache/cloudstack/api/command/user/vm/UpgradeVMCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vm/UpgradeVMCmd.java @@ -98,7 +98,7 @@ public class UpgradeVMCmd extends BaseCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to upgrade vm"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to upgrade vm"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/user/vmgroup/CreateVMGroupCmd.java b/api/src/org/apache/cloudstack/api/command/user/vmgroup/CreateVMGroupCmd.java index 9c2c6027ac9..ea28497053d 100644 --- a/api/src/org/apache/cloudstack/api/command/user/vmgroup/CreateVMGroupCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vmgroup/CreateVMGroupCmd.java @@ -99,7 +99,7 @@ public class CreateVMGroupCmd extends BaseCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create vm instance group"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create vm instance group"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/user/vmgroup/DeleteVMGroupCmd.java b/api/src/org/apache/cloudstack/api/command/user/vmgroup/DeleteVMGroupCmd.java index 47c2f764db6..3e9d1a24afa 100644 --- a/api/src/org/apache/cloudstack/api/command/user/vmgroup/DeleteVMGroupCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vmgroup/DeleteVMGroupCmd.java @@ -73,7 +73,7 @@ public class DeleteVMGroupCmd extends BaseCmd{ SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete vm group"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete vm group"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/user/vmgroup/UpdateVMGroupCmd.java b/api/src/org/apache/cloudstack/api/command/user/vmgroup/UpdateVMGroupCmd.java index 09313c0f797..eb0d747d54b 100644 --- a/api/src/org/apache/cloudstack/api/command/user/vmgroup/UpdateVMGroupCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vmgroup/UpdateVMGroupCmd.java @@ -80,7 +80,7 @@ public class UpdateVMGroupCmd extends BaseCmd{ response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update vm instance group"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update vm instance group"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/user/volume/AttachVolumeCmd.java b/api/src/org/apache/cloudstack/api/command/user/volume/AttachVolumeCmd.java index e48e4e43093..e5652952a0f 100644 --- a/api/src/org/apache/cloudstack/api/command/user/volume/AttachVolumeCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/volume/AttachVolumeCmd.java @@ -20,6 +20,7 @@ import org.apache.cloudstack.api.response.UserVmResponse; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -125,7 +126,7 @@ public class AttachVolumeCmd extends BaseAsyncCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to attach volume"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to attach volume"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/user/volume/CreateVolumeCmd.java b/api/src/org/apache/cloudstack/api/command/user/volume/CreateVolumeCmd.java index 04541b9fda7..0a0ba54e04f 100644 --- a/api/src/org/apache/cloudstack/api/command/user/volume/CreateVolumeCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/volume/CreateVolumeCmd.java @@ -20,6 +20,7 @@ import org.apache.cloudstack.api.response.*; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCreateCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -153,7 +154,7 @@ public class CreateVolumeCmd extends BaseAsyncCreateCmd { this.setEntityId(volume.getId()); this.setEntityUuid(volume.getUuid()); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create volume"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create volume"); } } @@ -179,7 +180,7 @@ public class CreateVolumeCmd extends BaseAsyncCreateCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create a volume"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create a volume"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/user/volume/DeleteVolumeCmd.java b/api/src/org/apache/cloudstack/api/command/user/volume/DeleteVolumeCmd.java index 2b2e94cab6b..6e3b4e12f7f 100644 --- a/api/src/org/apache/cloudstack/api/command/user/volume/DeleteVolumeCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/volume/DeleteVolumeCmd.java @@ -20,6 +20,7 @@ import org.apache.cloudstack.api.response.VolumeResponse; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.Parameter; @@ -84,7 +85,7 @@ public class DeleteVolumeCmd extends BaseCmd { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete volume"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete volume"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/user/volume/DetachVolumeCmd.java b/api/src/org/apache/cloudstack/api/command/user/volume/DetachVolumeCmd.java index c8ecddea699..db17f58e6e6 100644 --- a/api/src/org/apache/cloudstack/api/command/user/volume/DetachVolumeCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/volume/DetachVolumeCmd.java @@ -132,7 +132,7 @@ public class DetachVolumeCmd extends BaseAsyncCmd { response.setResponseName("volume"); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to detach volume"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to detach volume"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/user/volume/ExtractVolumeCmd.java b/api/src/org/apache/cloudstack/api/command/user/volume/ExtractVolumeCmd.java index 43b25a83663..40e46fd6b88 100644 --- a/api/src/org/apache/cloudstack/api/command/user/volume/ExtractVolumeCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/volume/ExtractVolumeCmd.java @@ -23,6 +23,7 @@ import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -148,11 +149,11 @@ public class ExtractVolumeCmd extends BaseAsyncCmd { response.setUrl(uploadInfo.getUploadUrl()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to extract volume"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to extract volume"); } } catch (URISyntaxException ex) { s_logger.info(ex); - throw new ServerApiException(BaseCmd.PARAM_ERROR, ex.getMessage()); + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, ex.getMessage()); } } } diff --git a/api/src/org/apache/cloudstack/api/command/user/volume/MigrateVolumeCmd.java b/api/src/org/apache/cloudstack/api/command/user/volume/MigrateVolumeCmd.java index 30e672ada1b..88076dbfb8b 100644 --- a/api/src/org/apache/cloudstack/api/command/user/volume/MigrateVolumeCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/volume/MigrateVolumeCmd.java @@ -17,6 +17,7 @@ package org.apache.cloudstack.api.command.user.volume; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -98,7 +99,7 @@ public class MigrateVolumeCmd extends BaseAsyncCmd { this.setResponseObject(response); } } catch (ConcurrentOperationException e) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to migrate volume: "); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to migrate volume: "); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/volume/UploadVolumeCmd.java b/api/src/org/apache/cloudstack/api/command/user/volume/UploadVolumeCmd.java index 4167ffd6460..e2c2c5b6d3a 100644 --- a/api/src/org/apache/cloudstack/api/command/user/volume/UploadVolumeCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/volume/UploadVolumeCmd.java @@ -112,7 +112,7 @@ public class UploadVolumeCmd extends BaseAsyncCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to upload volume"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to upload volume"); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/vpc/CreateStaticRouteCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpc/CreateStaticRouteCmd.java index 96de56a5be5..adeec0d0425 100644 --- a/api/src/org/apache/cloudstack/api/command/user/vpc/CreateStaticRouteCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpc/CreateStaticRouteCmd.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.api.command.user.vpc; import org.apache.cloudstack.api.response.PrivateGatewayResponse; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseAsyncCreateCmd; import org.apache.cloudstack.api.BaseCmd; @@ -71,7 +72,7 @@ public class CreateStaticRouteCmd extends BaseAsyncCreateCmd{ } catch (NetworkRuleConflictException ex) { s_logger.info("Network rule conflict: " + ex.getMessage()); s_logger.trace("Network rule conflict: ", ex); - throw new ServerApiException(BaseCmd.NETWORK_RULE_CONFLICT_ERROR, ex.getMessage()); + throw new ServerApiException(ApiErrorCode.NETWORK_RULE_CONFLICT_ERROR, ex.getMessage()); } } @@ -105,7 +106,7 @@ public class CreateStaticRouteCmd extends BaseAsyncCreateCmd{ } finally { if (!success || route == null) { _vpcService.revokeStaticRoute(getEntityId()); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create static route"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create static route"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/user/vpc/CreateVPCCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpc/CreateVPCCmd.java index 8a2e1f641fb..ccd8675e50d 100644 --- a/api/src/org/apache/cloudstack/api/command/user/vpc/CreateVPCCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpc/CreateVPCCmd.java @@ -24,6 +24,7 @@ import org.apache.cloudstack.api.response.VpcOfferingResponse; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCreateCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -126,7 +127,7 @@ public class CreateVPCCmd extends BaseAsyncCreateCmd{ this.setEntityId(vpc.getId()); this.setEntityUuid(vpc.getUuid()); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create a VPC"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create a VPC"); } } @@ -139,14 +140,14 @@ public class CreateVPCCmd extends BaseAsyncCreateCmd{ } } catch (ResourceUnavailableException ex) { s_logger.warn("Exception: ", ex); - throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); + throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } catch (ConcurrentOperationException ex) { s_logger.warn("Exception: ", ex); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } catch (InsufficientCapacityException ex) { s_logger.info(ex); s_logger.trace(ex); - throw new ServerApiException(BaseCmd.INSUFFICIENT_CAPACITY_ERROR, ex.getMessage()); + throw new ServerApiException(ApiErrorCode.INSUFFICIENT_CAPACITY_ERROR, ex.getMessage()); } if (vpc != null) { @@ -154,7 +155,7 @@ public class CreateVPCCmd extends BaseAsyncCreateCmd{ response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create VPC"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create VPC"); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/vpc/DeleteStaticRouteCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpc/DeleteStaticRouteCmd.java index c9e4463db14..02d342e5c80 100644 --- a/api/src/org/apache/cloudstack/api/command/user/vpc/DeleteStaticRouteCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpc/DeleteStaticRouteCmd.java @@ -95,7 +95,7 @@ public class DeleteStaticRouteCmd extends BaseAsyncCmd{ SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete static route"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete static route"); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/vpc/DeleteVPCCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpc/DeleteVPCCmd.java index ed4e754f736..132556c87b7 100644 --- a/api/src/org/apache/cloudstack/api/command/user/vpc/DeleteVPCCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpc/DeleteVPCCmd.java @@ -71,14 +71,14 @@ public class DeleteVPCCmd extends BaseAsyncCmd{ SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete VPC"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete VPC"); } }catch (ResourceUnavailableException ex) { s_logger.warn("Exception: ", ex); - throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); + throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } catch (ConcurrentOperationException ex) { s_logger.warn("Exception: ", ex); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/vpc/RestartVPCCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpc/RestartVPCCmd.java index 4a23e6e6595..f28c4cb55bb 100644 --- a/api/src/org/apache/cloudstack/api/command/user/vpc/RestartVPCCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpc/RestartVPCCmd.java @@ -78,18 +78,18 @@ public class RestartVPCCmd extends BaseAsyncCmd{ SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to restart VPC"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to restart VPC"); } } catch (ResourceUnavailableException ex) { s_logger.warn("Exception: ", ex); - throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); + throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } catch (ConcurrentOperationException ex) { s_logger.warn("Exception: ", ex); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } catch (InsufficientCapacityException ex) { s_logger.info(ex); s_logger.trace(ex); - throw new ServerApiException(BaseCmd.INSUFFICIENT_CAPACITY_ERROR, ex.getMessage()); + throw new ServerApiException(ApiErrorCode.INSUFFICIENT_CAPACITY_ERROR, ex.getMessage()); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/vpc/UpdateVPCCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpc/UpdateVPCCmd.java index 2dc64dba267..d34f7bf7bf3 100644 --- a/api/src/org/apache/cloudstack/api/command/user/vpc/UpdateVPCCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpc/UpdateVPCCmd.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.api.command.user.vpc; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -92,7 +93,7 @@ public class UpdateVPCCmd extends BaseAsyncCmd{ response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update VPC"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update VPC"); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/vpn/AddVpnUserCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpn/AddVpnUserCmd.java index f2d19a7cce6..479e990494d 100644 --- a/api/src/org/apache/cloudstack/api/command/user/vpn/AddVpnUserCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpn/AddVpnUserCmd.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.api.command.user.vpn; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCreateCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -119,7 +120,7 @@ public class AddVpnUserCmd extends BaseAsyncCreateCmd { VpnUser vpnUser = _entityMgr.findById(VpnUser.class, getEntityId()); Account account = _entityMgr.findById(Account.class, vpnUser.getAccountId()); if (!_ravService.applyVpnUsers(vpnUser.getAccountId(), userName)) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to add vpn user"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add vpn user"); } VpnUsersResponse vpnResponse = new VpnUsersResponse(); @@ -144,7 +145,7 @@ public class AddVpnUserCmd extends BaseAsyncCreateCmd { VpnUser vpnUser = _ravService.addVpnUser(owner.getId(), userName, password); if (vpnUser == null) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to add vpn user"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add vpn user"); } setEntityId(vpnUser.getId()); setEntityUuid(vpnUser.getUuid()); diff --git a/api/src/org/apache/cloudstack/api/command/user/vpn/CreateRemoteAccessVpnCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpn/CreateRemoteAccessVpnCmd.java index b517af883c3..ae09ef79894 100644 --- a/api/src/org/apache/cloudstack/api/command/user/vpn/CreateRemoteAccessVpnCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpn/CreateRemoteAccessVpnCmd.java @@ -148,12 +148,12 @@ public class CreateRemoteAccessVpnCmd extends BaseAsyncCreateCmd { this.setEntityUuid(ipAddr.getUuid()); } } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create remote access vpn"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create remote access vpn"); } } catch (NetworkRuleConflictException e) { s_logger.info("Network rule conflict: " + e.getMessage()); s_logger.trace("Network Rule Conflict: ", e); - throw new ServerApiException(BaseCmd.NETWORK_RULE_CONFLICT_ERROR, e.getMessage()); + throw new ServerApiException(ApiErrorCode.NETWORK_RULE_CONFLICT_ERROR, e.getMessage()); } } @@ -166,11 +166,11 @@ public class CreateRemoteAccessVpnCmd extends BaseAsyncCreateCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create remote access vpn"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create remote access vpn"); } } catch (ResourceUnavailableException ex) { s_logger.warn("Exception: ", ex); - throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); + throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/vpn/CreateVpnConnectionCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpn/CreateVpnConnectionCmd.java index 3dc334d0e2a..327f35b6688 100644 --- a/api/src/org/apache/cloudstack/api/command/user/vpn/CreateVpnConnectionCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpn/CreateVpnConnectionCmd.java @@ -94,12 +94,12 @@ public class CreateVpnConnectionCmd extends BaseAsyncCreateCmd { this.setEntityId(conn.getId()); this.setEntityUuid(conn.getUuid()); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create site to site vpn connection"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create site to site vpn connection"); } } catch (NetworkRuleConflictException e) { s_logger.info("Network rule conflict: " + e.getMessage()); s_logger.trace("Network Rule Conflict: ", e); - throw new ServerApiException(BaseCmd.NETWORK_RULE_CONFLICT_ERROR, e.getMessage()); + throw new ServerApiException(ApiErrorCode.NETWORK_RULE_CONFLICT_ERROR, e.getMessage()); } } @@ -112,11 +112,11 @@ public class CreateVpnConnectionCmd extends BaseAsyncCreateCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create site to site vpn connection"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create site to site vpn connection"); } } catch (ResourceUnavailableException ex) { s_logger.warn("Exception: ", ex); - throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); + throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/vpn/CreateVpnCustomerGatewayCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpn/CreateVpnCustomerGatewayCmd.java index bde98b0b44b..a14a5ec820c 100644 --- a/api/src/org/apache/cloudstack/api/command/user/vpn/CreateVpnCustomerGatewayCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpn/CreateVpnCustomerGatewayCmd.java @@ -20,6 +20,7 @@ import org.apache.cloudstack.api.response.DomainResponse; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -160,7 +161,7 @@ public class CreateVpnCustomerGatewayCmd extends BaseAsyncCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create customer VPN gateway"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create customer VPN gateway"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/user/vpn/CreateVpnGatewayCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpn/CreateVpnGatewayCmd.java index 4b405541a90..2d2150b89b4 100644 --- a/api/src/org/apache/cloudstack/api/command/user/vpn/CreateVpnGatewayCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpn/CreateVpnGatewayCmd.java @@ -20,6 +20,7 @@ import org.apache.cloudstack.api.response.VpcResponse; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -86,7 +87,7 @@ public class CreateVpnGatewayCmd extends BaseAsyncCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create VPN gateway"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create VPN gateway"); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/vpn/DeleteVpnConnectionCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpn/DeleteVpnConnectionCmd.java index 23a7793ef88..06521026bcb 100644 --- a/api/src/org/apache/cloudstack/api/command/user/vpn/DeleteVpnConnectionCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpn/DeleteVpnConnectionCmd.java @@ -86,11 +86,11 @@ public class DeleteVpnConnectionCmd extends BaseAsyncCmd { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete site to site VPN connection"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete site to site VPN connection"); } } catch (ResourceUnavailableException ex) { s_logger.warn("Exception: ", ex); - throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); + throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } } } diff --git a/api/src/org/apache/cloudstack/api/command/user/vpn/DeleteVpnCustomerGatewayCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpn/DeleteVpnCustomerGatewayCmd.java index 181ee3bbc68..854bb9b6ebf 100644 --- a/api/src/org/apache/cloudstack/api/command/user/vpn/DeleteVpnCustomerGatewayCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpn/DeleteVpnCustomerGatewayCmd.java @@ -84,7 +84,7 @@ public class DeleteVpnCustomerGatewayCmd extends BaseAsyncCmd { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete customer VPN gateway"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete customer VPN gateway"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/user/vpn/DeleteVpnGatewayCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpn/DeleteVpnGatewayCmd.java index 9ac27d07664..6c89f7c9b93 100644 --- a/api/src/org/apache/cloudstack/api/command/user/vpn/DeleteVpnGatewayCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpn/DeleteVpnGatewayCmd.java @@ -85,7 +85,7 @@ public class DeleteVpnGatewayCmd extends BaseAsyncCmd { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete customer VPN gateway"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete customer VPN gateway"); } } } diff --git a/api/src/org/apache/cloudstack/api/command/user/vpn/RemoveVpnUserCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpn/RemoveVpnUserCmd.java index bdad7e31dd9..11ca651f6a2 100644 --- a/api/src/org/apache/cloudstack/api/command/user/vpn/RemoveVpnUserCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpn/RemoveVpnUserCmd.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.api.command.user.vpn; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -110,11 +111,11 @@ public class RemoveVpnUserCmd extends BaseAsyncCmd { Account owner = _accountService.getAccount(getEntityOwnerId()); boolean result = _ravService.removeVpnUser(owner.getId(), userName, UserContext.current().getCaller()); if (!result) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to remove vpn user"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to remove vpn user"); } if (!_ravService.applyVpnUsers(owner.getId(), userName)) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to apply vpn user removal"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to apply vpn user removal"); } SuccessResponse response = new SuccessResponse(getCommandName()); setResponseObject(response); diff --git a/api/src/org/apache/cloudstack/api/command/user/vpn/ResetVpnConnectionCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpn/ResetVpnConnectionCmd.java index ed28ea5610f..14e2f8cd853 100644 --- a/api/src/org/apache/cloudstack/api/command/user/vpn/ResetVpnConnectionCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpn/ResetVpnConnectionCmd.java @@ -104,11 +104,11 @@ public class ResetVpnConnectionCmd extends BaseAsyncCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to reset site to site VPN connection"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to reset site to site VPN connection"); } } catch (ResourceUnavailableException ex) { s_logger.warn("Exception: ", ex); - throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); + throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } } } diff --git a/api/src/org/apache/cloudstack/api/command/user/vpn/UpdateVpnCustomerGatewayCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpn/UpdateVpnCustomerGatewayCmd.java index 7564129c38f..27b656d49da 100644 --- a/api/src/org/apache/cloudstack/api/command/user/vpn/UpdateVpnCustomerGatewayCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpn/UpdateVpnCustomerGatewayCmd.java @@ -155,7 +155,7 @@ public class UpdateVpnCustomerGatewayCmd extends BaseAsyncCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update customer VPN gateway"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update customer VPN gateway"); } } } diff --git a/plugins/api/discovery/src/org/apache/cloudstack/api/command/user/discovery/ListApisCmd.java b/plugins/api/discovery/src/org/apache/cloudstack/api/command/user/discovery/ListApisCmd.java index bad7ca7b5f6..18c3976f365 100644 --- a/plugins/api/discovery/src/org/apache/cloudstack/api/command/user/discovery/ListApisCmd.java +++ b/plugins/api/discovery/src/org/apache/cloudstack/api/command/user/discovery/ListApisCmd.java @@ -20,6 +20,7 @@ import com.cloud.user.User; import com.cloud.user.UserContext; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.PlugService; @@ -48,7 +49,7 @@ public class ListApisCmd extends BaseCmd { User user = UserContext.current().getCallerUser(); ListResponse response = (ListResponse) _apiDiscoveryService.listApis(user, name); if (response == null) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Api Discovery plugin was unable to find an api by that name or process any apis"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Api Discovery plugin was unable to find an api by that name or process any apis"); } response.setResponseName(getCommandName()); this.setResponseObject(response); diff --git a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/AssociateLunCmd.java b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/AssociateLunCmd.java index c87c9242010..671b9f49174 100644 --- a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/AssociateLunCmd.java +++ b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/AssociateLunCmd.java @@ -21,6 +21,7 @@ import java.rmi.ServerException; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.Parameter; @@ -39,27 +40,27 @@ public class AssociateLunCmd extends BaseCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - + @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required = true, description="LUN name.") private String lunName; - + @Parameter(name=ApiConstants.IQN, type=CommandType.STRING, required = true, description="Guest IQN to which the LUN associate.") private String guestIqn; - - + + /////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - - + + public String getLunName() { return lunName; } - + public String getGuestIQN() { return guestIqn; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -68,12 +69,12 @@ public class AssociateLunCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public void execute(){ ComponentLocator locator = ComponentLocator.getLocator(ManagementService.Name); NetappManager netappMgr = locator.getManager(NetappManager.class); - + try { AssociateLunCmdResponse response = new AssociateLunCmdResponse(); String returnVals[] = null; @@ -85,9 +86,9 @@ public class AssociateLunCmd extends BaseCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } catch (ServerException e) { - throw new ServerApiException(BaseCmd.PARAM_ERROR, e.toString()); + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, e.toString()); } catch (InvalidParameterValueException e) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.toString()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.toString()); } } @@ -96,5 +97,5 @@ public class AssociateLunCmd extends BaseCmd { // TODO Auto-generated method stub return 0; } - + } diff --git a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/CreateLunCmd.java b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/CreateLunCmd.java index 8c89730b978..fde0dc337f1 100644 --- a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/CreateLunCmd.java +++ b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/CreateLunCmd.java @@ -21,6 +21,7 @@ import java.rmi.ServerException; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.Parameter; @@ -39,21 +40,21 @@ import com.cloud.utils.component.ComponentLocator; public class CreateLunCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(CreateLunCmd.class.getName()); private static final String s_name = "createlunresponse"; - + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - + @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required = true, description="pool name.") private String poolName; - + @Parameter(name=ApiConstants.SIZE, type=CommandType.LONG, required = true, description="LUN size.") private long size; - + public String getPoolName() { return poolName; } - + public long getLunSize() { return size; } @@ -64,7 +65,7 @@ public class CreateLunCmd extends BaseCmd { ConcurrentOperationException, ResourceAllocationException { ComponentLocator locator = ComponentLocator.getLocator(ManagementService.Name); NetappManager netappMgr = locator.getManager(NetappManager.class); - + try { CreateLunCmdResponse response = new CreateLunCmdResponse(); String returnVals[] = null; @@ -76,11 +77,11 @@ public class CreateLunCmd extends BaseCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } catch (ServerException e) { - throw new ServerApiException(BaseCmd.PARAM_ERROR, e.toString()); + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, e.toString()); } catch (InvalidParameterValueException e) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.toString()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.toString()); } - + } @Override @@ -94,5 +95,5 @@ public class CreateLunCmd extends BaseCmd { // TODO Auto-generated method stub return 0; } - + } diff --git a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/CreateVolumeOnFilerCmd.java b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/CreateVolumeOnFilerCmd.java index a2d4b96e6dd..5ca187d84f1 100644 --- a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/CreateVolumeOnFilerCmd.java +++ b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/CreateVolumeOnFilerCmd.java @@ -20,6 +20,7 @@ import java.net.UnknownHostException; import java.rmi.ServerException; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.Parameter; @@ -40,64 +41,64 @@ public class CreateVolumeOnFilerCmd extends BaseCmd { @Parameter(name=ApiConstants.IP_ADDRESS, type=CommandType.STRING, required = true, description="ip address.") private String ipAddress; - + @Parameter(name=ApiConstants.AGGREGATE_NAME, type=CommandType.STRING, required = true, description="aggregate name.") private String aggrName; @Parameter(name=ApiConstants.POOL_NAME, type=CommandType.STRING, required = true, description="pool name.") private String poolName; - + @Parameter(name=ApiConstants.VOLUME_NAME, type=CommandType.STRING, required = true, description="volume name.") private String volName; - + @Parameter(name=ApiConstants.SIZE, type=CommandType.INTEGER, required = true, description="volume size.") private Integer volSize; - + @Parameter(name=ApiConstants.SNAPSHOT_POLICY, type=CommandType.STRING, required = false, description="snapshot policy.") private String snapshotPolicy; - + @Parameter(name=ApiConstants.SNAPSHOT_RESERVATION, type=CommandType.INTEGER, required = false, description="snapshot reservation.") private Integer snapshotReservation; - + @Parameter(name=ApiConstants.USERNAME, type=CommandType.STRING, required = true, description="user name.") private String userName; - + @Parameter(name=ApiConstants.PASSWORD, type=CommandType.STRING, required = true, description="password.") private String password; - + public String getIpAddress() { return ipAddress; } - + public String getAggrName() { return aggrName; } - + public String getPoolName() { return poolName; } - + public String volName() { return volName; } - + public Integer getVolSize() { return volSize; } - + public String getSnapshotPolicy() { return snapshotPolicy; } - + public Integer getSnapshotReservation() { return snapshotReservation; } - + public String getUserName() { return userName; } - + public String getPassword() { return password; } @@ -109,26 +110,26 @@ public class CreateVolumeOnFilerCmd extends BaseCmd { //param checks if(snapshotReservation != null && (snapshotReservation<0 || snapshotReservation>100)) throw new InvalidParameterValueException("Invalid snapshot reservation"); - + ComponentLocator locator = ComponentLocator.getLocator(ManagementService.Name); NetappManager netappMgr = locator.getManager(NetappManager.class); - + StringBuilder s = new StringBuilder(getVolSize().toString()); s.append("g"); - + try { netappMgr.createVolumeOnFiler(ipAddress, aggrName, poolName, volName, s.toString(), snapshotPolicy, snapshotReservation, userName, password); CreateVolumeOnFilerCmdResponse response = new CreateVolumeOnFilerCmdResponse(); response.setResponseName(getCommandName()); this.setResponseObject(response); } catch (ServerException e) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.toString()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.toString()); } catch (InvalidParameterValueException e) { - throw new ServerApiException(BaseCmd.PARAM_ERROR, e.toString()); + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, e.toString()); } catch (UnknownHostException e) { - throw new ServerApiException(BaseCmd.PARAM_ERROR, e.toString()); + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, e.toString()); } - + } @Override @@ -142,5 +143,5 @@ public class CreateVolumeOnFilerCmd extends BaseCmd { // TODO Auto-generated method stub return 0; } - + } diff --git a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/CreateVolumePoolCmd.java b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/CreateVolumePoolCmd.java index 9e38c5fc097..107f6b0583f 100644 --- a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/CreateVolumePoolCmd.java +++ b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/CreateVolumePoolCmd.java @@ -19,6 +19,7 @@ package com.cloud.api.commands.netapp; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.Parameter; @@ -42,11 +43,11 @@ public class CreateVolumePoolCmd extends BaseCmd { private String poolName; @Parameter(name=ApiConstants.ALGORITHM, type=CommandType.STRING, required = true, description="algorithm.") private String algorithm; - + public String getPoolName() { return poolName; } - + public String getAlgorithm() { return algorithm; } @@ -57,16 +58,16 @@ public class CreateVolumePoolCmd extends BaseCmd { ConcurrentOperationException, ResourceAllocationException { ComponentLocator locator = ComponentLocator.getLocator(ManagementService.Name); NetappManager netappMgr = locator.getManager(NetappManager.class); - + try { CreateVolumePoolCmdResponse response = new CreateVolumePoolCmdResponse(); netappMgr.createPool(getPoolName(), getAlgorithm()); response.setResponseName(getCommandName()); this.setResponseObject(response); } catch (InvalidParameterValueException e) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.toString()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.toString()); } - + } @Override @@ -80,5 +81,5 @@ public class CreateVolumePoolCmd extends BaseCmd { // TODO Auto-generated method stub return 0; } - + } diff --git a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/DeleteVolumePoolCmd.java b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/DeleteVolumePoolCmd.java index 1105ea53e9d..a70b6d4a0da 100644 --- a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/DeleteVolumePoolCmd.java +++ b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/DeleteVolumePoolCmd.java @@ -20,6 +20,7 @@ package com.cloud.api.commands.netapp; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.Parameter; @@ -39,7 +40,7 @@ import com.cloud.utils.component.ComponentLocator; public class DeleteVolumePoolCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(DeleteVolumePoolCmd.class.getName()); private static final String s_name = "deletepoolresponse"; - + @Parameter(name=ApiConstants.POOL_NAME, type=CommandType.STRING, required = true, description="pool name.") private String poolName; @@ -55,9 +56,9 @@ public class DeleteVolumePoolCmd extends BaseCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } catch (InvalidParameterValueException e) { - throw new ServerApiException(BaseCmd.PARAM_ERROR, e.toString()); + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, e.toString()); } catch (ResourceInUseException e) { - throw new ServerApiException(BaseCmd.RESOURCE_IN_USE_ERROR, e.toString()); + throw new ServerApiException(ApiErrorCode.RESOURCE_IN_USE_ERROR, e.toString()); } } @@ -72,5 +73,5 @@ public class DeleteVolumePoolCmd extends BaseCmd { // TODO Auto-generated method stub return 0; } - + } diff --git a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/DestroyLunCmd.java b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/DestroyLunCmd.java index c5f7b117f5b..1b3e6bc84a8 100644 --- a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/DestroyLunCmd.java +++ b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/DestroyLunCmd.java @@ -21,6 +21,7 @@ import java.rmi.ServerException; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.Parameter; @@ -37,7 +38,7 @@ import com.cloud.utils.component.ComponentLocator; @APICommand(name = "destroyLunOnFiler", description="Destroy a LUN", responseObject = DeleteLUNCmdResponse.class) public class DestroyLunCmd extends BaseCmd { - + public static final Logger s_logger = Logger.getLogger(DestroyLunCmd.class.getName()); private static final String s_name = "destroylunresponse"; @@ -56,9 +57,9 @@ public class DestroyLunCmd extends BaseCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } catch (InvalidParameterValueException e) { - throw new ServerApiException(BaseCmd.PARAM_ERROR, e.toString()); + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, e.toString()); } catch (ServerException e) { - throw new ServerApiException(BaseCmd.RESOURCE_IN_USE_ERROR, e.toString()); + throw new ServerApiException(ApiErrorCode.RESOURCE_IN_USE_ERROR, e.toString()); } } @@ -73,5 +74,5 @@ public class DestroyLunCmd extends BaseCmd { // TODO Auto-generated method stub return 0; } - + } diff --git a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/DestroyVolumeOnFilerCmd.java b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/DestroyVolumeOnFilerCmd.java index 4ddc0c9f6d0..21e10b0148f 100644 --- a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/DestroyVolumeOnFilerCmd.java +++ b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/DestroyVolumeOnFilerCmd.java @@ -37,17 +37,17 @@ import com.cloud.utils.component.ComponentLocator; public class DestroyVolumeOnFilerCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(DestroyVolumeOnFilerCmd.class.getName()); private static final String s_name = "destroyvolumeresponse"; - + @Parameter(name=ApiConstants.AGGREGATE_NAME, type=CommandType.STRING, required = true, description="aggregate name.") private String aggrName; - + @Parameter(name=ApiConstants.IP_ADDRESS, type=CommandType.STRING, required = true, description="ip address.") private String ipAddr; - + @Parameter(name=ApiConstants.VOLUME_NAME, type=CommandType.STRING, required = true, description="volume name.") private String volumeName; - - + + @Override public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, @@ -60,13 +60,13 @@ public class DestroyVolumeOnFilerCmd extends BaseCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } catch (InvalidParameterValueException e) { - throw new ServerApiException(BaseCmd.PARAM_ERROR, e.toString()); + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, e.toString()); } catch (ResourceInUseException e) { - throw new ServerApiException(BaseCmd.RESOURCE_IN_USE_ERROR, e.toString()); + throw new ServerApiException(ApiErrorCode.RESOURCE_IN_USE_ERROR, e.toString()); } catch (ServerException e) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.toString()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.toString()); } - + } @Override @@ -80,5 +80,5 @@ public class DestroyVolumeOnFilerCmd extends BaseCmd { // TODO Auto-generated method stub return 0; } - + } \ No newline at end of file diff --git a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/DissociateLunCmd.java b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/DissociateLunCmd.java index 0a6c1a70ef1..f373c65bedd 100644 --- a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/DissociateLunCmd.java +++ b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/DissociateLunCmd.java @@ -39,10 +39,10 @@ public class DissociateLunCmd extends BaseCmd { @Parameter(name=ApiConstants.PATH, type=CommandType.STRING, required = true, description="LUN path.") private String path; - + @Parameter(name=ApiConstants.IQN, type=CommandType.STRING, required = true, description="Guest IQN.") private String guestIQN; - + @Override public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, @@ -55,9 +55,9 @@ public class DissociateLunCmd extends BaseCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } catch (InvalidParameterValueException e) { - throw new ServerApiException(BaseCmd.PARAM_ERROR, e.toString()); + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, e.toString()); } catch (ServerException e) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.toString()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.toString()); } } diff --git a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/ListLunsCmd.java b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/ListLunsCmd.java index 630b14994e7..61b81db90c8 100644 --- a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/ListLunsCmd.java +++ b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/ListLunsCmd.java @@ -22,6 +22,7 @@ import java.util.List; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.Parameter; @@ -39,7 +40,7 @@ import com.cloud.server.api.response.netapp.ListLunsCmdResponse; import com.cloud.utils.component.ComponentLocator; @APICommand(name = "listLunsOnFiler", description="List LUN", responseObject = ListLunsCmdResponse.class) -public class ListLunsCmd extends BaseCmd +public class ListLunsCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(ListLunsCmd.class.getName()); private static final String s_name = "listlunresponse"; @@ -70,8 +71,8 @@ public class ListLunsCmd extends BaseCmd listResponse.setResponseName(getCommandName()); this.setResponseObject(listResponse); } catch (InvalidParameterValueException e) { - throw new ServerApiException(BaseCmd.PARAM_ERROR, e.toString()); - } + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, e.toString()); + } } @Override diff --git a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/ListVolumePoolsCmd.java b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/ListVolumePoolsCmd.java index d77f4fad849..882cf1b2b44 100644 --- a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/ListVolumePoolsCmd.java +++ b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/ListVolumePoolsCmd.java @@ -21,6 +21,7 @@ import java.util.List; import org.apache.log4j.Logger; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ServerApiException; @@ -64,9 +65,9 @@ public class ListVolumePoolsCmd extends BaseCmd { listResponse.setResponseName(getCommandName()); this.setResponseObject(listResponse); } catch (InvalidParameterValueException e) { - throw new ServerApiException(BaseCmd.PARAM_ERROR, e.toString()); - } - + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, e.toString()); + } + } @Override diff --git a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/ListVolumesOnFilerCmd.java b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/ListVolumesOnFilerCmd.java index 66a96f3a221..3cc98f43d90 100644 --- a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/ListVolumesOnFilerCmd.java +++ b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/ListVolumesOnFilerCmd.java @@ -39,7 +39,7 @@ import com.cloud.utils.component.ComponentLocator; public class ListVolumesOnFilerCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(ListVolumesOnFilerCmd.class.getName()); private static final String s_name = "listvolumesresponse"; - + @Parameter(name=ApiConstants.POOL_NAME, type=CommandType.STRING, required = true, description="pool name.") private String poolName; @@ -49,7 +49,7 @@ public class ListVolumesOnFilerCmd extends BaseCmd { ConcurrentOperationException, ResourceAllocationException { ComponentLocator locator = ComponentLocator.getLocator(ManagementService.Name); NetappManager netappMgr = locator.getManager(NetappManager.class); - + try { List volumes = netappMgr.listVolumesOnFiler(poolName); ListResponse listResponse = new ListResponse(); @@ -71,9 +71,9 @@ public class ListVolumesOnFilerCmd extends BaseCmd { listResponse.setResponseName(getCommandName()); this.setResponseObject(listResponse); } catch (InvalidParameterValueException e) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.toString()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.toString()); } - + } @Override diff --git a/plugins/hypervisors/simulator/src/com/cloud/api/commands/ConfigureSimulator.java b/plugins/hypervisors/simulator/src/com/cloud/api/commands/ConfigureSimulator.java index df81249538d..e6afcc9f4b4 100755 --- a/plugins/hypervisors/simulator/src/com/cloud/api/commands/ConfigureSimulator.java +++ b/plugins/hypervisors/simulator/src/com/cloud/api/commands/ConfigureSimulator.java @@ -20,6 +20,7 @@ import org.apache.log4j.Logger; import com.cloud.agent.manager.SimulatorManager; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.Parameter; @@ -62,7 +63,7 @@ public class ConfigureSimulator extends BaseCmd { SimulatorManager _simMgr = locator.getManager(SimulatorManager.class); boolean result = _simMgr.configureSimulator(zoneId, podId, clusterId, hostId, command, values); if (!result) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to configure simulator"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to configure simulator"); } SuccessResponse response = new SuccessResponse(getCommandName()); diff --git a/plugins/hypervisors/vmware/src/com/cloud/api/commands/DeleteCiscoNexusVSMCmd.java b/plugins/hypervisors/vmware/src/com/cloud/api/commands/DeleteCiscoNexusVSMCmd.java index 3e45ce2a084..1496f295ccb 100644 --- a/plugins/hypervisors/vmware/src/com/cloud/api/commands/DeleteCiscoNexusVSMCmd.java +++ b/plugins/hypervisors/vmware/src/com/cloud/api/commands/DeleteCiscoNexusVSMCmd.java @@ -20,6 +20,7 @@ package com.cloud.api.commands; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.Parameter; @@ -70,7 +71,7 @@ public class DeleteCiscoNexusVSMCmd extends BaseAsyncCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseAsyncCmd.INTERNAL_ERROR, "Failed to delete Cisco Nexus VSM device"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete Cisco Nexus VSM device"); } } @@ -83,7 +84,7 @@ public class DeleteCiscoNexusVSMCmd extends BaseAsyncCmd { public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public String getEventType() { return EventTypes.EVENT_EXTERNAL_SWITCH_MGMT_DEVICE_DELETE; diff --git a/plugins/hypervisors/vmware/src/com/cloud/api/commands/DisableCiscoNexusVSMCmd.java b/plugins/hypervisors/vmware/src/com/cloud/api/commands/DisableCiscoNexusVSMCmd.java index 9a7f6ada97c..67a74081292 100644 --- a/plugins/hypervisors/vmware/src/com/cloud/api/commands/DisableCiscoNexusVSMCmd.java +++ b/plugins/hypervisors/vmware/src/com/cloud/api/commands/DisableCiscoNexusVSMCmd.java @@ -20,6 +20,7 @@ package com.cloud.api.commands; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.Parameter; @@ -70,7 +71,7 @@ public class DisableCiscoNexusVSMCmd extends BaseAsyncCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseAsyncCmd.INTERNAL_ERROR, "Failed to disable Cisco Nexus VSM device"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to disable Cisco Nexus VSM device"); } } @@ -92,5 +93,5 @@ public class DisableCiscoNexusVSMCmd extends BaseAsyncCmd { @Override public String getEventType() { return EventTypes.EVENT_EXTERNAL_SWITCH_MGMT_DEVICE_DISABLE; - } + } } diff --git a/plugins/hypervisors/vmware/src/com/cloud/api/commands/EnableCiscoNexusVSMCmd.java b/plugins/hypervisors/vmware/src/com/cloud/api/commands/EnableCiscoNexusVSMCmd.java index 5dc67212fd3..5064c9faabc 100644 --- a/plugins/hypervisors/vmware/src/com/cloud/api/commands/EnableCiscoNexusVSMCmd.java +++ b/plugins/hypervisors/vmware/src/com/cloud/api/commands/EnableCiscoNexusVSMCmd.java @@ -66,7 +66,7 @@ public class EnableCiscoNexusVSMCmd extends BaseAsyncCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseAsyncCmd.INTERNAL_ERROR, "Failed to enable Cisco Nexus VSM device"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to enable Cisco Nexus VSM device"); } } diff --git a/plugins/hypervisors/vmware/src/com/cloud/api/commands/ListCiscoNexusVSMsCmd.java b/plugins/hypervisors/vmware/src/com/cloud/api/commands/ListCiscoNexusVSMsCmd.java index ee6a01bdb8a..1ac00f9c6d8 100755 --- a/plugins/hypervisors/vmware/src/com/cloud/api/commands/ListCiscoNexusVSMsCmd.java +++ b/plugins/hypervisors/vmware/src/com/cloud/api/commands/ListCiscoNexusVSMsCmd.java @@ -21,6 +21,7 @@ import org.apache.cloudstack.api.response.ClusterResponse; import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseListCmd; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.Parameter; @@ -44,7 +45,7 @@ public class ListCiscoNexusVSMsCmd extends BaseListCmd { /** * This command returns a list of all the VSMs configured in the management server. - * If a clusterId is specified, it will return a list containing only that VSM + * If a clusterId is specified, it will return a list containing only that VSM * that is associated with that cluster. If a zone is specified, it will pull * up all the clusters of type vmware in that zone, and prepare a list of VSMs * associated with those clusters. @@ -60,7 +61,7 @@ public class ListCiscoNexusVSMsCmd extends BaseListCmd { @Parameter(name=ApiConstants.CLUSTER_ID, type=CommandType.UUID, entityType = ClusterResponse.class, required = false, description="Id of the CloudStack cluster in which the Cisco Nexus 1000v VSM appliance.") private long clusterId; - + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, required = false, description="Id of the CloudStack cluster in which the Cisco Nexus 1000v VSM appliance.") private long zoneId; @@ -68,11 +69,11 @@ public class ListCiscoNexusVSMsCmd extends BaseListCmd { ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public long getClusterId() { return clusterId; } - + public long getZoneId() { return zoneId; } @@ -87,7 +88,7 @@ public class ListCiscoNexusVSMsCmd extends BaseListCmd { @Override public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException { List vsmDeviceList = _ciscoNexusVSMService.getCiscoNexusVSMs(this); - + if (vsmDeviceList.size() > 0) { ListResponse response = new ListResponse(); List vsmResponses = new ArrayList(); @@ -101,10 +102,10 @@ public class ListCiscoNexusVSMsCmd extends BaseListCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseListCmd.INTERNAL_ERROR, "No VSM found."); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "No VSM found."); } } - + @Override public String getCommandName() { return s_name; diff --git a/plugins/network-elements/f5/src/com/cloud/api/commands/AddExternalLoadBalancerCmd.java b/plugins/network-elements/f5/src/com/cloud/api/commands/AddExternalLoadBalancerCmd.java index 69a21fc184c..29a2c0bee68 100644 --- a/plugins/network-elements/f5/src/com/cloud/api/commands/AddExternalLoadBalancerCmd.java +++ b/plugins/network-elements/f5/src/com/cloud/api/commands/AddExternalLoadBalancerCmd.java @@ -21,6 +21,7 @@ import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.Parameter; @@ -38,11 +39,11 @@ import com.cloud.utils.exception.CloudRuntimeException; public class AddExternalLoadBalancerCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(AddExternalLoadBalancerCmd.class.getName()); private static final String s_name = "addexternalloadbalancerresponse"; - + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, required = true, description="Zone in which to add the external load balancer appliance.") private Long zoneId; @@ -59,19 +60,19 @@ public class AddExternalLoadBalancerCmd extends BaseCmd { /////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public Long getZoneId() { return zoneId; } - + public String getUrl() { return url; } - + public String getUsername() { return username; } - + public String getPassword() { return password; } @@ -102,9 +103,9 @@ public class AddExternalLoadBalancerCmd extends BaseCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } catch (InvalidParameterValueException ipve) { - throw new ServerApiException(BaseCmd.PARAM_ERROR, ipve.getMessage()); + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, ipve.getMessage()); } catch (CloudRuntimeException cre) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, cre.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, cre.getMessage()); } } } diff --git a/plugins/network-elements/f5/src/com/cloud/api/commands/AddF5LoadBalancerCmd.java b/plugins/network-elements/f5/src/com/cloud/api/commands/AddF5LoadBalancerCmd.java index a5616e0ee73..839f60f71d6 100644 --- a/plugins/network-elements/f5/src/com/cloud/api/commands/AddF5LoadBalancerCmd.java +++ b/plugins/network-elements/f5/src/com/cloud/api/commands/AddF5LoadBalancerCmd.java @@ -54,7 +54,7 @@ public class AddF5LoadBalancerCmd extends BaseAsyncCmd { @Parameter(name=ApiConstants.USERNAME, type=CommandType.STRING, required = true, description="Credentials to reach F5 BigIP load balancer device") private String username; - + @Parameter(name=ApiConstants.PASSWORD, type=CommandType.STRING, required = true, description="Credentials to reach F5 BigIP load balancer device") private String password; @@ -99,12 +99,12 @@ public class AddF5LoadBalancerCmd extends BaseAsyncCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseAsyncCmd.INTERNAL_ERROR, "Failed to add F5 Big IP load balancer due to internal error."); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add F5 Big IP load balancer due to internal error."); } } catch (InvalidParameterValueException invalidParamExcp) { - throw new ServerApiException(BaseCmd.PARAM_ERROR, invalidParamExcp.getMessage()); + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage()); } catch (CloudRuntimeException runtimeExcp) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, runtimeExcp.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage()); } } @@ -117,7 +117,7 @@ public class AddF5LoadBalancerCmd extends BaseAsyncCmd { public String getEventType() { return EventTypes.EVENT_EXTERNAL_LB_DEVICE_ADD; } - + @Override public String getCommandName() { return s_name; diff --git a/plugins/network-elements/f5/src/com/cloud/api/commands/ConfigureF5LoadBalancerCmd.java b/plugins/network-elements/f5/src/com/cloud/api/commands/ConfigureF5LoadBalancerCmd.java index e796b57cc41..cc7d1be9c78 100644 --- a/plugins/network-elements/f5/src/com/cloud/api/commands/ConfigureF5LoadBalancerCmd.java +++ b/plugins/network-elements/f5/src/com/cloud/api/commands/ConfigureF5LoadBalancerCmd.java @@ -77,12 +77,12 @@ public class ConfigureF5LoadBalancerCmd extends BaseAsyncCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseAsyncCmd.INTERNAL_ERROR, "Failed to configure F5 load balancer due to internal error."); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to configure F5 load balancer due to internal error."); } } catch (InvalidParameterValueException invalidParamExcp) { - throw new ServerApiException(BaseCmd.PARAM_ERROR, invalidParamExcp.getMessage()); + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage()); } catch (CloudRuntimeException runtimeExcp) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, runtimeExcp.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage()); } } diff --git a/plugins/network-elements/f5/src/com/cloud/api/commands/DeleteExternalLoadBalancerCmd.java b/plugins/network-elements/f5/src/com/cloud/api/commands/DeleteExternalLoadBalancerCmd.java index d3015712596..29eaa0c781b 100644 --- a/plugins/network-elements/f5/src/com/cloud/api/commands/DeleteExternalLoadBalancerCmd.java +++ b/plugins/network-elements/f5/src/com/cloud/api/commands/DeleteExternalLoadBalancerCmd.java @@ -32,19 +32,19 @@ import com.cloud.user.Account; public class DeleteExternalLoadBalancerCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(DeleteExternalLoadBalancerCmd.class.getName()); private static final String s_name = "deleteexternalloadbalancerresponse"; - + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = HostResponse.class, required = true, description="Id of the external loadbalancer appliance.") private Long id; - + /////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public Long getId() { return id; } @@ -60,12 +60,12 @@ public class DeleteExternalLoadBalancerCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ try { @@ -75,10 +75,10 @@ public class DeleteExternalLoadBalancerCmd extends BaseCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete external load balancer."); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete external load balancer."); } } catch (InvalidParameterValueException e) { - throw new ServerApiException(BaseCmd.PARAM_ERROR, "Failed to delete external load balancer."); + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Failed to delete external load balancer."); } } } diff --git a/plugins/network-elements/f5/src/com/cloud/api/commands/DeleteF5LoadBalancerCmd.java b/plugins/network-elements/f5/src/com/cloud/api/commands/DeleteF5LoadBalancerCmd.java index 8b53d70f76d..c1ab22ddc30 100644 --- a/plugins/network-elements/f5/src/com/cloud/api/commands/DeleteF5LoadBalancerCmd.java +++ b/plugins/network-elements/f5/src/com/cloud/api/commands/DeleteF5LoadBalancerCmd.java @@ -22,6 +22,7 @@ import org.apache.log4j.Logger; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.Parameter; @@ -74,12 +75,12 @@ public class DeleteF5LoadBalancerCmd extends BaseAsyncCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete F5 load balancer."); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete F5 load balancer."); } } catch (InvalidParameterValueException invalidParamExcp) { - throw new ServerApiException(BaseCmd.PARAM_ERROR, invalidParamExcp.getMessage()); + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage()); } catch (CloudRuntimeException runtimeExcp) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, runtimeExcp.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage()); } } diff --git a/plugins/network-elements/f5/src/com/cloud/api/commands/ListF5LoadBalancerNetworksCmd.java b/plugins/network-elements/f5/src/com/cloud/api/commands/ListF5LoadBalancerNetworksCmd.java index bf1164b4d05..1d276ce10e7 100644 --- a/plugins/network-elements/f5/src/com/cloud/api/commands/ListF5LoadBalancerNetworksCmd.java +++ b/plugins/network-elements/f5/src/com/cloud/api/commands/ListF5LoadBalancerNetworksCmd.java @@ -23,6 +23,7 @@ import java.util.List; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.BaseListCmd; import org.apache.cloudstack.api.APICommand; @@ -86,9 +87,9 @@ public class ListF5LoadBalancerNetworksCmd extends BaseListCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } catch (InvalidParameterValueException invalidParamExcp) { - throw new ServerApiException(BaseCmd.PARAM_ERROR, invalidParamExcp.getMessage()); + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage()); } catch (CloudRuntimeException runtimeExcp) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, runtimeExcp.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage()); } } diff --git a/plugins/network-elements/f5/src/com/cloud/api/commands/ListF5LoadBalancersCmd.java b/plugins/network-elements/f5/src/com/cloud/api/commands/ListF5LoadBalancersCmd.java index c03d55abc0a..deaa2750d25 100644 --- a/plugins/network-elements/f5/src/com/cloud/api/commands/ListF5LoadBalancersCmd.java +++ b/plugins/network-elements/f5/src/com/cloud/api/commands/ListF5LoadBalancersCmd.java @@ -88,9 +88,9 @@ public class ListF5LoadBalancersCmd extends BaseListCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } catch (InvalidParameterValueException invalidParamExcp) { - throw new ServerApiException(BaseCmd.PARAM_ERROR, invalidParamExcp.getMessage()); + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage()); } catch (CloudRuntimeException runtimeExcp) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, runtimeExcp.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage()); } } diff --git a/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/AddExternalFirewallCmd.java b/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/AddExternalFirewallCmd.java index cda27fb8960..deaa6128b93 100644 --- a/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/AddExternalFirewallCmd.java +++ b/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/AddExternalFirewallCmd.java @@ -11,7 +11,7 @@ // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the +// KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package com.cloud.api.commands; @@ -20,6 +20,7 @@ import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.Parameter; @@ -34,30 +35,30 @@ import com.cloud.utils.exception.CloudRuntimeException; @APICommand(name = "addExternalFirewall", description="Adds an external firewall appliance", responseObject = ExternalFirewallResponse.class) public class AddExternalFirewallCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(AddExternalFirewallCmd.class.getName()); - private static final String s_name = "addexternalfirewallresponse"; - + public static final Logger s_logger = Logger.getLogger(AddExternalFirewallCmd.class.getName()); + private static final String s_name = "addexternalfirewallresponse"; + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, required = true, description="Zone in which to add the external firewall appliance.") private Long zoneId; @Parameter(name=ApiConstants.URL, type=CommandType.STRING, required = true, description="URL of the external firewall appliance.") - private String url; - + private String url; + @Parameter(name=ApiConstants.USERNAME, type=CommandType.STRING, required = true, description="Username of the external firewall appliance.") - private String username; - + private String username; + @Parameter(name=ApiConstants.PASSWORD, type=CommandType.STRING, required = true, description="Password of the external firewall appliance.") private String password; - + /////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public Long getZoneId() { return zoneId; } @@ -65,15 +66,15 @@ public class AddExternalFirewallCmd extends BaseCmd { public String getUrl() { return url; } - + public String getUsername() { return username; } - + public String getPassword() { return password; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// @@ -85,12 +86,12 @@ public class AddExternalFirewallCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @SuppressWarnings("deprecation") @Override public void execute(){ @@ -101,9 +102,9 @@ public class AddExternalFirewallCmd extends BaseCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } catch (InvalidParameterValueException ipve) { - throw new ServerApiException(BaseCmd.PARAM_ERROR, ipve.getMessage()); + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, ipve.getMessage()); } catch (CloudRuntimeException cre) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, cre.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, cre.getMessage()); } } } diff --git a/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/AddSrxFirewallCmd.java b/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/AddSrxFirewallCmd.java index a2ad4e5ce2b..9ed6814035e 100644 --- a/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/AddSrxFirewallCmd.java +++ b/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/AddSrxFirewallCmd.java @@ -11,7 +11,7 @@ // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the +// KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package com.cloud.api.commands; @@ -20,6 +20,7 @@ import org.apache.cloudstack.api.response.PhysicalNetworkResponse; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -57,7 +58,7 @@ public class AddSrxFirewallCmd extends BaseAsyncCmd { @Parameter(name=ApiConstants.USERNAME, type=CommandType.STRING, required = true, description="Credentials to reach SRX firewall device") private String username; - + @Parameter(name=ApiConstants.PASSWORD, type=CommandType.STRING, required = true, description="Credentials to reach SRX firewall device") private String password; @@ -102,12 +103,12 @@ public class AddSrxFirewallCmd extends BaseAsyncCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseAsyncCmd.INTERNAL_ERROR, "Failed to add SRX firewall due to internal error."); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add SRX firewall due to internal error."); } } catch (InvalidParameterValueException invalidParamExcp) { - throw new ServerApiException(BaseCmd.PARAM_ERROR, invalidParamExcp.getMessage()); + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage()); } catch (CloudRuntimeException runtimeExcp) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, runtimeExcp.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage()); } } @@ -120,7 +121,7 @@ public class AddSrxFirewallCmd extends BaseAsyncCmd { public String getEventType() { return EventTypes.EVENT_EXTERNAL_FIREWALL_DEVICE_ADD; } - + @Override public String getCommandName() { return s_name; diff --git a/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/ConfigureSrxFirewallCmd.java b/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/ConfigureSrxFirewallCmd.java index 482fcc8c0c7..c9ea7cbe374 100644 --- a/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/ConfigureSrxFirewallCmd.java +++ b/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/ConfigureSrxFirewallCmd.java @@ -11,7 +11,7 @@ // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the +// KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package com.cloud.api.commands; @@ -19,6 +19,7 @@ package com.cloud.api.commands; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -81,12 +82,12 @@ public class ConfigureSrxFirewallCmd extends BaseAsyncCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseAsyncCmd.INTERNAL_ERROR, "Failed to configure SRX firewall device due to internal error."); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to configure SRX firewall device due to internal error."); } } catch (InvalidParameterValueException invalidParamExcp) { - throw new ServerApiException(BaseCmd.PARAM_ERROR, invalidParamExcp.getMessage()); + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage()); } catch (CloudRuntimeException runtimeExcp) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, runtimeExcp.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage()); } } diff --git a/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/DeleteExternalFirewallCmd.java b/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/DeleteExternalFirewallCmd.java index 5cdc9e3c92c..77597898ac0 100644 --- a/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/DeleteExternalFirewallCmd.java +++ b/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/DeleteExternalFirewallCmd.java @@ -11,7 +11,7 @@ // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the +// KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package com.cloud.api.commands; @@ -20,6 +20,7 @@ import org.apache.cloudstack.api.response.HostResponse; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.Parameter; @@ -32,9 +33,9 @@ import com.cloud.user.Account; @APICommand(name = "deleteExternalFirewall", description="Deletes an external firewall appliance.", responseObject = SuccessResponse.class) public class DeleteExternalFirewallCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(DeleteExternalFirewallCmd.class.getName()); - private static final String s_name = "deleteexternalfirewallresponse"; - + public static final Logger s_logger = Logger.getLogger(DeleteExternalFirewallCmd.class.getName()); + private static final String s_name = "deleteexternalfirewallresponse"; + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @@ -42,15 +43,15 @@ public class DeleteExternalFirewallCmd extends BaseCmd { @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = HostResponse.class, required = true, description="Id of the external firewall appliance.") private Long id; - + /////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public Long getId() { return id; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -61,7 +62,7 @@ public class DeleteExternalFirewallCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; @@ -77,10 +78,10 @@ public class DeleteExternalFirewallCmd extends BaseCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete external firewall."); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete external firewall."); } } catch (InvalidParameterValueException e) { - throw new ServerApiException(BaseCmd.PARAM_ERROR, "Failed to delete external firewall."); + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Failed to delete external firewall."); } } } diff --git a/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/DeleteSrxFirewallCmd.java b/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/DeleteSrxFirewallCmd.java index 1dc792a723a..e45fe3180e8 100644 --- a/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/DeleteSrxFirewallCmd.java +++ b/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/DeleteSrxFirewallCmd.java @@ -11,7 +11,7 @@ // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the +// KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package com.cloud.api.commands; @@ -19,6 +19,7 @@ package com.cloud.api.commands; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -72,12 +73,12 @@ public class DeleteSrxFirewallCmd extends BaseAsyncCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete SRX firewall device"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete SRX firewall device"); } } catch (InvalidParameterValueException invalidParamExcp) { - throw new ServerApiException(BaseCmd.PARAM_ERROR, invalidParamExcp.getMessage()); + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage()); } catch (CloudRuntimeException runtimeExcp) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, runtimeExcp.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage()); } } diff --git a/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/ListSrxFirewallNetworksCmd.java b/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/ListSrxFirewallNetworksCmd.java index 9c2b3962a6f..03ae962bff8 100644 --- a/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/ListSrxFirewallNetworksCmd.java +++ b/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/ListSrxFirewallNetworksCmd.java @@ -11,7 +11,7 @@ // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the +// KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package com.cloud.api.commands; @@ -80,9 +80,9 @@ public class ListSrxFirewallNetworksCmd extends BaseListCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } catch (InvalidParameterValueException invalidParamExcp) { - throw new ServerApiException(BaseCmd.PARAM_ERROR, invalidParamExcp.getMessage()); + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage()); } catch (CloudRuntimeException runtimeExcp) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, runtimeExcp.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage()); } } diff --git a/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/ListSrxFirewallsCmd.java b/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/ListSrxFirewallsCmd.java index 6508cc83c7d..5242316a574 100644 --- a/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/ListSrxFirewallsCmd.java +++ b/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/ListSrxFirewallsCmd.java @@ -11,7 +11,7 @@ // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the +// KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package com.cloud.api.commands; @@ -88,9 +88,9 @@ public class ListSrxFirewallsCmd extends BaseListCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } catch (InvalidParameterValueException invalidParamExcp) { - throw new ServerApiException(BaseCmd.PARAM_ERROR, invalidParamExcp.getMessage()); + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage()); } catch (CloudRuntimeException runtimeExcp) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, runtimeExcp.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage()); } } diff --git a/plugins/network-elements/netscaler/src/com/cloud/api/commands/AddNetscalerLoadBalancerCmd.java b/plugins/network-elements/netscaler/src/com/cloud/api/commands/AddNetscalerLoadBalancerCmd.java index 9d902975723..79c657f5210 100644 --- a/plugins/network-elements/netscaler/src/com/cloud/api/commands/AddNetscalerLoadBalancerCmd.java +++ b/plugins/network-elements/netscaler/src/com/cloud/api/commands/AddNetscalerLoadBalancerCmd.java @@ -51,7 +51,7 @@ public class AddNetscalerLoadBalancerCmd extends BaseAsyncCmd { @Parameter(name=ApiConstants.USERNAME, type=CommandType.STRING, required = true, description="Credentials to reach netscaler load balancer device") private String username; - + @Parameter(name=ApiConstants.PASSWORD, type=CommandType.STRING, required = true, description="Credentials to reach netscaler load balancer device") private String password; @@ -96,12 +96,12 @@ public class AddNetscalerLoadBalancerCmd extends BaseAsyncCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseAsyncCmd.INTERNAL_ERROR, "Failed to add netscaler load balancer due to internal error."); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add netscaler load balancer due to internal error."); } } catch (InvalidParameterValueException invalidParamExcp) { - throw new ServerApiException(BaseCmd.PARAM_ERROR, invalidParamExcp.getMessage()); + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage()); } catch (CloudRuntimeException runtimeExcp) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, runtimeExcp.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage()); } } @@ -114,7 +114,7 @@ public class AddNetscalerLoadBalancerCmd extends BaseAsyncCmd { public String getEventType() { return EventTypes.EVENT_EXTERNAL_LB_DEVICE_ADD; } - + @Override public String getCommandName() { return s_name; diff --git a/plugins/network-elements/netscaler/src/com/cloud/api/commands/ConfigureNetscalerLoadBalancerCmd.java b/plugins/network-elements/netscaler/src/com/cloud/api/commands/ConfigureNetscalerLoadBalancerCmd.java index e0ec73ad501..33fe7a2e504 100644 --- a/plugins/network-elements/netscaler/src/com/cloud/api/commands/ConfigureNetscalerLoadBalancerCmd.java +++ b/plugins/network-elements/netscaler/src/com/cloud/api/commands/ConfigureNetscalerLoadBalancerCmd.java @@ -101,12 +101,12 @@ public class ConfigureNetscalerLoadBalancerCmd extends BaseAsyncCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseAsyncCmd.INTERNAL_ERROR, "Failed to configure netscaler load balancer due to internal error."); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to configure netscaler load balancer due to internal error."); } } catch (InvalidParameterValueException invalidParamExcp) { - throw new ServerApiException(BaseCmd.PARAM_ERROR, invalidParamExcp.getMessage()); + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage()); } catch (CloudRuntimeException runtimeExcp) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, runtimeExcp.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage()); } } diff --git a/plugins/network-elements/netscaler/src/com/cloud/api/commands/DeleteNetscalerLoadBalancerCmd.java b/plugins/network-elements/netscaler/src/com/cloud/api/commands/DeleteNetscalerLoadBalancerCmd.java index ec7faab39d4..5f62b802e81 100644 --- a/plugins/network-elements/netscaler/src/com/cloud/api/commands/DeleteNetscalerLoadBalancerCmd.java +++ b/plugins/network-elements/netscaler/src/com/cloud/api/commands/DeleteNetscalerLoadBalancerCmd.java @@ -18,6 +18,7 @@ package com.cloud.api.commands; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -72,12 +73,12 @@ public class DeleteNetscalerLoadBalancerCmd extends BaseAsyncCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete netscaler load balancer."); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete netscaler load balancer."); } } catch (InvalidParameterValueException invalidParamExcp) { - throw new ServerApiException(BaseCmd.PARAM_ERROR, invalidParamExcp.getMessage()); + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage()); } catch (CloudRuntimeException runtimeExcp) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, runtimeExcp.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage()); } } diff --git a/plugins/network-elements/netscaler/src/com/cloud/api/commands/ListNetscalerLoadBalancerNetworksCmd.java b/plugins/network-elements/netscaler/src/com/cloud/api/commands/ListNetscalerLoadBalancerNetworksCmd.java index 52476df8316..ec94c6e7683 100644 --- a/plugins/network-elements/netscaler/src/com/cloud/api/commands/ListNetscalerLoadBalancerNetworksCmd.java +++ b/plugins/network-elements/netscaler/src/com/cloud/api/commands/ListNetscalerLoadBalancerNetworksCmd.java @@ -20,6 +20,7 @@ import java.util.List; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.BaseListCmd; import org.apache.cloudstack.api.APICommand; @@ -83,9 +84,9 @@ public class ListNetscalerLoadBalancerNetworksCmd extends BaseListCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } catch (InvalidParameterValueException invalidParamExcp) { - throw new ServerApiException(BaseCmd.PARAM_ERROR, invalidParamExcp.getMessage()); + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage()); } catch (CloudRuntimeException runtimeExcp) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, runtimeExcp.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage()); } } diff --git a/plugins/network-elements/netscaler/src/com/cloud/api/commands/ListNetscalerLoadBalancersCmd.java b/plugins/network-elements/netscaler/src/com/cloud/api/commands/ListNetscalerLoadBalancersCmd.java index bf679fa51c1..8886218b057 100644 --- a/plugins/network-elements/netscaler/src/com/cloud/api/commands/ListNetscalerLoadBalancersCmd.java +++ b/plugins/network-elements/netscaler/src/com/cloud/api/commands/ListNetscalerLoadBalancersCmd.java @@ -21,6 +21,7 @@ import org.apache.cloudstack.api.response.PhysicalNetworkResponse; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.BaseListCmd; import org.apache.cloudstack.api.APICommand; @@ -91,9 +92,9 @@ public class ListNetscalerLoadBalancersCmd extends BaseListCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } catch (InvalidParameterValueException invalidParamExcp) { - throw new ServerApiException(BaseCmd.PARAM_ERROR, invalidParamExcp.getMessage()); + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage()); } catch (CloudRuntimeException runtimeExcp) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, runtimeExcp.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage()); } } diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/AddNiciraNvpDeviceCmd.java b/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/AddNiciraNvpDeviceCmd.java index 1734ce2ff3d..3bd39b80c9d 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/AddNiciraNvpDeviceCmd.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/AddNiciraNvpDeviceCmd.java @@ -38,7 +38,7 @@ public class AddNiciraNvpDeviceCmd extends BaseAsyncCmd { private static final Logger s_logger = Logger.getLogger(AddNiciraNvpDeviceCmd.class.getName()); private static final String s_name = "addniciranvpdeviceresponse"; @PlugService NiciraNvpElementService _niciraNvpElementService; - + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @@ -52,16 +52,16 @@ public class AddNiciraNvpDeviceCmd extends BaseAsyncCmd { @Parameter(name=ApiConstants.USERNAME, type=CommandType.STRING, required = true, description="Credentials to access the Nicira Controller API") private String username; - + @Parameter(name=ApiConstants.PASSWORD, type=CommandType.STRING, required = true, description="Credentials to access the Nicira Controller API") private String password; - + @Parameter(name=ApiConstants.NICIRA_NVP_TRANSPORT_ZONE_UUID, type=CommandType.STRING, required = true, description="The Transportzone UUID configured on the Nicira Controller") private String transportzoneuuid; - + @Parameter(name=ApiConstants.NICIRA_NVP_GATEWAYSERVICE_UUID, type=CommandType.STRING, required = false, description="The L3 Gateway Service UUID configured on the Nicira Controller") private String l3gatewayserviceuuid; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -81,11 +81,11 @@ public class AddNiciraNvpDeviceCmd extends BaseAsyncCmd { public String getPassword() { return password; } - + public String getTransportzoneUuid() { return transportzoneuuid; } - + public String getL3GatewayServiceUuid() { return l3gatewayserviceuuid; } @@ -104,15 +104,15 @@ public class AddNiciraNvpDeviceCmd extends BaseAsyncCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseAsyncCmd.INTERNAL_ERROR, "Failed to add Nicira NVP device due to internal error."); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add Nicira NVP device due to internal error."); } } catch (InvalidParameterValueException invalidParamExcp) { - throw new ServerApiException(BaseCmd.PARAM_ERROR, invalidParamExcp.getMessage()); + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage()); } catch (CloudRuntimeException runtimeExcp) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, runtimeExcp.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage()); } } - + @Override public String getCommandName() { return s_name; diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/DeleteNiciraNvpDeviceCmd.java b/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/DeleteNiciraNvpDeviceCmd.java index 12544410599..9a10c2879d3 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/DeleteNiciraNvpDeviceCmd.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/DeleteNiciraNvpDeviceCmd.java @@ -20,6 +20,7 @@ import com.cloud.api.response.NiciraNvpDeviceResponse; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; @@ -72,12 +73,12 @@ public class DeleteNiciraNvpDeviceCmd extends BaseAsyncCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete Nicira device."); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete Nicira device."); } } catch (InvalidParameterValueException invalidParamExcp) { - throw new ServerApiException(BaseCmd.PARAM_ERROR, invalidParamExcp.getMessage()); + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage()); } catch (CloudRuntimeException runtimeExcp) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, runtimeExcp.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage()); } } diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/ListNiciraNvpDeviceNetworksCmd.java b/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/ListNiciraNvpDeviceNetworksCmd.java index bea417d3687..70973c0a5a5 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/ListNiciraNvpDeviceNetworksCmd.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/ListNiciraNvpDeviceNetworksCmd.java @@ -23,6 +23,7 @@ import com.cloud.api.response.NiciraNvpDeviceResponse; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.BaseListCmd; import org.apache.cloudstack.api.APICommand; @@ -85,9 +86,9 @@ public class ListNiciraNvpDeviceNetworksCmd extends BaseListCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } catch (InvalidParameterValueException invalidParamExcp) { - throw new ServerApiException(BaseCmd.PARAM_ERROR, invalidParamExcp.getMessage()); + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage()); } catch (CloudRuntimeException runtimeExcp) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, runtimeExcp.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage()); } } diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/ListNiciraNvpDevicesCmd.java b/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/ListNiciraNvpDevicesCmd.java index 04aab2a296a..0d2ca5a2335 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/ListNiciraNvpDevicesCmd.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/ListNiciraNvpDevicesCmd.java @@ -20,6 +20,7 @@ import java.util.ArrayList; import java.util.List; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.BaseListCmd; import org.apache.cloudstack.api.Parameter; @@ -92,9 +93,9 @@ public class ListNiciraNvpDevicesCmd extends BaseListCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } catch (InvalidParameterValueException invalidParamExcp) { - throw new ServerApiException(BaseCmd.PARAM_ERROR, invalidParamExcp.getMessage()); + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage()); } catch (CloudRuntimeException runtimeExcp) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, runtimeExcp.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage()); } } @@ -102,5 +103,5 @@ public class ListNiciraNvpDevicesCmd extends BaseListCmd { public String getCommandName() { return s_name; } - + } diff --git a/server/src/com/cloud/api/ApiDispatcher.java b/server/src/com/cloud/api/ApiDispatcher.java index 55d7f429ca1..04b46e5a579 100755 --- a/server/src/com/cloud/api/ApiDispatcher.java +++ b/server/src/com/cloud/api/ApiDispatcher.java @@ -105,46 +105,13 @@ public class ApiDispatcher { _daoNameMap.put("com.cloud.template.VirtualMachineTemplate", VMTemplateDao.class); } - public void dispatchCreateCmd(BaseAsyncCreateCmd cmd, Map params) { - processParameters(cmd, params); + public void dispatchCreateCmd(BaseAsyncCreateCmd cmd, Map params) throws Exception { + processParameters(cmd, params); + + UserContext ctx = UserContext.current(); + ctx.setAccountId(cmd.getEntityOwnerId()); + cmd.create(); - try { - UserContext ctx = UserContext.current(); - ctx.setAccountId(cmd.getEntityOwnerId()); - cmd.create(); - } catch (Throwable t) { - if (t instanceof InvalidParameterValueException || t instanceof IllegalArgumentException) { - s_logger.info(t.getMessage()); - throw new ServerApiException(BaseCmd.PARAM_ERROR, t.getMessage()); - } else if (t instanceof PermissionDeniedException) { - s_logger.info("PermissionDenied: " + t.getMessage()); - throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, t.getMessage()); - } else if (t instanceof AccountLimitException) { - s_logger.info(t.getMessage()); - throw new ServerApiException(BaseCmd.ACCOUNT_RESOURCE_LIMIT_ERROR, t.getMessage()); - } else if (t instanceof InsufficientCapacityException) { - s_logger.info(t.getMessage()); - throw new ServerApiException(BaseCmd.INSUFFICIENT_CAPACITY_ERROR, t.getMessage()); - } else if (t instanceof ResourceAllocationException) { - s_logger.info(t.getMessage()); - throw new ServerApiException(BaseCmd.RESOURCE_ALLOCATION_ERROR, t.getMessage()); - } else if (t instanceof ResourceUnavailableException) { - s_logger.warn("Exception: ", t); - throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, t.getMessage()); - } else if (t instanceof AsyncCommandQueued) { - throw (AsyncCommandQueued) t; - } else if (t instanceof ServerApiException) { - s_logger.warn(t.getClass() + " : " + ((ServerApiException) t).getDescription()); - throw (ServerApiException) t; - } else { - s_logger.error("Exception while executing " + cmd.getClass().getSimpleName() + ":", t); - if (UserContext.current().getCaller().getType() == Account.ACCOUNT_TYPE_ADMIN) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, t.getMessage()); - } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, BaseCmd.USER_ERROR_MESSAGE); - } - } - } } private void doAccessChecks(BaseCmd cmd, List entitiesToAccess) { @@ -170,164 +137,36 @@ public class ApiDispatcher { } } - public void dispatch(BaseCmd cmd, Map params) { - try { - processParameters(cmd, params); - UserContext ctx = UserContext.current(); - ctx.setAccountId(cmd.getEntityOwnerId()); - if (cmd instanceof BaseAsyncCmd) { + public void dispatch(BaseCmd cmd, Map params) throws Exception { + processParameters(cmd, params); + UserContext ctx = UserContext.current(); + ctx.setAccountId(cmd.getEntityOwnerId()); + if (cmd instanceof BaseAsyncCmd) { - BaseAsyncCmd asyncCmd = (BaseAsyncCmd) cmd; - String startEventId = params.get("ctxStartEventId"); - ctx.setStartEventId(Long.valueOf(startEventId)); + BaseAsyncCmd asyncCmd = (BaseAsyncCmd) cmd; + String startEventId = params.get("ctxStartEventId"); + ctx.setStartEventId(Long.valueOf(startEventId)); - // Synchronise job on the object if needed - if (asyncCmd.getJob() != null && asyncCmd.getSyncObjId() != null && asyncCmd.getSyncObjType() != null) { - Long queueSizeLimit = null; - if (asyncCmd.getSyncObjType() != null && asyncCmd.getSyncObjType().equalsIgnoreCase(BaseAsyncCmd.snapshotHostSyncObject)) { - queueSizeLimit = _createSnapshotQueueSizeLimit; - } else { - queueSizeLimit = 1L; - } + // Synchronise job on the object if needed + if (asyncCmd.getJob() != null && asyncCmd.getSyncObjId() != null && asyncCmd.getSyncObjType() != null) { + Long queueSizeLimit = null; + if (asyncCmd.getSyncObjType() != null && asyncCmd.getSyncObjType().equalsIgnoreCase(BaseAsyncCmd.snapshotHostSyncObject)) { + queueSizeLimit = _createSnapshotQueueSizeLimit; + } else { + queueSizeLimit = 1L; + } - if (queueSizeLimit != null) { - _asyncMgr.syncAsyncJobExecution(asyncCmd.getJob(), asyncCmd.getSyncObjType(), - asyncCmd.getSyncObjId().longValue(), queueSizeLimit); - } else { - s_logger.trace("The queue size is unlimited, skipping the synchronizing"); - } - } - } - - cmd.execute(); - - } catch (Throwable t) { - if (t instanceof InvalidParameterValueException) { - // earlier, we'd log the db id as part of the log message, but now since we've pushed - // the id into a IdentityProxy object, we would need to dump that object alongwith the - // message. - InvalidParameterValueException ref = (InvalidParameterValueException) t; - ServerApiException ex = new ServerApiException(BaseCmd.PARAM_ERROR, t.getMessage()); - // copy over the IdentityProxy information as well and throw the serverapiexception. - ArrayList idList = ref.getIdProxyList(); - if (idList != null) { - // Iterate through entire arraylist and copy over each proxy id. - for (int i = 0 ; i < idList.size(); i++) { - ex.addProxyObject(idList.get(i)); - s_logger.info(t.getMessage() + " uuid: " + idList.get(i)); - } + if (queueSizeLimit != null) { + _asyncMgr + .syncAsyncJobExecution(asyncCmd.getJob(), asyncCmd.getSyncObjType(), asyncCmd.getSyncObjId().longValue(), queueSizeLimit); } else { - s_logger.info(t.getMessage()); + s_logger.trace("The queue size is unlimited, skipping the synchronizing"); } - // Also copy over the cserror code. - ex.setCSErrorCode(ref.getCSErrorCode()); - throw ex; - } else if(t instanceof IllegalArgumentException) { - throw new ServerApiException(BaseCmd.PARAM_ERROR, t.getMessage()); - } else if (t instanceof PermissionDeniedException) { - PermissionDeniedException ref = (PermissionDeniedException)t; - ServerApiException ex = new ServerApiException(BaseCmd.ACCOUNT_ERROR, t.getMessage()); - // copy over the IdentityProxy information as well and throw the serverapiexception. - ArrayList idList = ref.getIdProxyList(); - if (idList != null) { - // Iterate through entire arraylist and copy over each proxy id. - for (int i = 0 ; i < idList.size(); i++) { - ex.addProxyObject(idList.get(i)); - s_logger.info("PermissionDenied: " + t.getMessage() + "uuid: " + idList.get(i)); - } - } else { - s_logger.info("PermissionDenied: " + t.getMessage()); - } - // Also copy over the cserror code. - ex.setCSErrorCode(ref.getCSErrorCode()); - throw ex; - } else if (t instanceof AccountLimitException) { - AccountLimitException ref = (AccountLimitException)t; - ServerApiException ex = new ServerApiException(BaseCmd.ACCOUNT_RESOURCE_LIMIT_ERROR, t.getMessage()); - // copy over the IdentityProxy information as well and throw the serverapiexception. - ArrayList idList = ref.getIdProxyList(); - if (idList != null) { - // Iterate through entire arraylist and copy over each proxy id. - for (int i = 0 ; i < idList.size(); i++) { - ex.addProxyObject(idList.get(i)); - s_logger.info(t.getMessage() + "uuid: " + idList.get(i)); - } - } else { - s_logger.info(t.getMessage()); - } - // Also copy over the cserror code. - ex.setCSErrorCode(ref.getCSErrorCode()); - throw ex; - } else if (t instanceof InsufficientCapacityException) { - InsufficientCapacityException ref = (InsufficientCapacityException)t; - ServerApiException ex = new ServerApiException(BaseCmd.INSUFFICIENT_CAPACITY_ERROR, t.getMessage()); - // copy over the IdentityProxy information as well and throw the serverapiexception. - ArrayList idList = ref.getIdProxyList(); - if (idList != null) { - // Iterate through entire arraylist and copy over each proxy id. - for (int i = 0 ; i < idList.size(); i++) { - ex.addProxyObject(idList.get(i)); - s_logger.info(t.getMessage() + "uuid: " + idList.get(i)); - } - } else { - s_logger.info(t.getMessage()); - } - // Also copy over the cserror code - ex.setCSErrorCode(ref.getCSErrorCode()); - throw ex; - } else if (t instanceof ResourceAllocationException) { - ResourceAllocationException ref = (ResourceAllocationException)t; - ServerApiException ex = new ServerApiException(BaseCmd.RESOURCE_ALLOCATION_ERROR, t.getMessage()); - // copy over the IdentityProxy information as well and throw the serverapiexception. - ArrayList idList = ref.getIdProxyList(); - if (idList != null) { - // Iterate through entire arraylist and copy over each proxy id. - for (int i = 0 ; i < idList.size(); i++) { - String id = idList.get(i); - ex.addProxyObject(id); - s_logger.warn("Exception: " + t.getMessage() + "uuid: " + id); - } - } else { - s_logger.warn("Exception: ", t); - } - // Also copy over the cserror code. - ex.setCSErrorCode(ref.getCSErrorCode()); - throw ex; - } else if (t instanceof ResourceUnavailableException) { - ResourceUnavailableException ref = (ResourceUnavailableException)t; - ServerApiException ex = new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, t.getMessage()); - // copy over the IdentityProxy information as well and throw the serverapiexception. - ArrayList idList = ref.getIdProxyList(); - if (idList != null) { - // Iterate through entire arraylist and copy over each proxy id. - for (int i = 0 ; i < idList.size(); i++) { - String id = idList.get(i); - ex.addProxyObject(id); - s_logger.warn("Exception: " + t.getMessage() + "uuid: " + id); - } - } else { - s_logger.warn("Exception: ", t); - } - // Also copy over the cserror code. - ex.setCSErrorCode(ref.getCSErrorCode()); - throw ex; - } else if (t instanceof AsyncCommandQueued) { - throw (AsyncCommandQueued) t; - } else if (t instanceof ServerApiException) { - s_logger.warn(t.getClass() + " : " + ((ServerApiException) t).getDescription()); - throw (ServerApiException) t; - } else { - s_logger.error("Exception while executing " + cmd.getClass().getSimpleName() + ":", t); - ServerApiException ex; - if (UserContext.current().getCaller().getType() == Account.ACCOUNT_TYPE_ADMIN) { - ex = new ServerApiException(BaseCmd.INTERNAL_ERROR, t.getMessage()); - } else { - ex = new ServerApiException(BaseCmd.INTERNAL_ERROR, BaseCmd.USER_ERROR_MESSAGE); - } - ex.setCSErrorCode(CSExceptionErrorCode.getCSErrCode(ex.getClass().getName())); - throw ex; } } + + cmd.execute(); + } @SuppressWarnings({ "unchecked", "rawtypes" }) @@ -343,11 +182,11 @@ public class ApiDispatcher { } if ((unpackedParams.get(ApiConstants.PAGE) == null) && (pageSize != null && pageSize != BaseListCmd.PAGESIZE_UNLIMITED)) { - ServerApiException ex = new ServerApiException(BaseCmd.PARAM_ERROR, "\"page\" parameter is required when \"pagesize\" is specified"); + ServerApiException ex = new ServerApiException(ApiErrorCode.PARAM_ERROR, "\"page\" parameter is required when \"pagesize\" is specified"); ex.setCSErrorCode(CSExceptionErrorCode.getCSErrCode(ex.getClass().getName())); throw ex; } else if (pageSize == null && (unpackedParams.get(ApiConstants.PAGE) != null)) { - throw new ServerApiException(BaseCmd.PARAM_ERROR, "\"pagesize\" parameter is required when \"page\" is specified"); + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "\"pagesize\" parameter is required when \"page\" is specified"); } } @@ -370,7 +209,7 @@ public class ApiDispatcher { Object paramObj = unpackedParams.get(parameterAnnotation.name()); if (paramObj == null) { if (parameterAnnotation.required()) { - throw new ServerApiException(BaseCmd.PARAM_ERROR, "Unable to execute API command " + cmd.getCommandName().substring(0, cmd.getCommandName().length() - 8) + " due to missing parameter " + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Unable to execute API command " + cmd.getCommandName().substring(0, cmd.getCommandName().length() - 8) + " due to missing parameter " + parameterAnnotation.name()); } continue; @@ -383,23 +222,23 @@ public class ApiDispatcher { if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to execute API command " + cmd.getCommandName() + " due to invalid value " + paramObj + " for parameter " + parameterAnnotation.name()); } - throw new ServerApiException(BaseCmd.PARAM_ERROR, "Unable to execute API command " + cmd.getCommandName().substring(0, cmd.getCommandName().length() - 8) + " due to invalid value " + paramObj + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Unable to execute API command " + cmd.getCommandName().substring(0, cmd.getCommandName().length() - 8) + " due to invalid value " + paramObj + " for parameter " + parameterAnnotation.name()); } catch (ParseException parseEx) { if (s_logger.isDebugEnabled()) { s_logger.debug("Invalid date parameter " + paramObj + " passed to command " + cmd.getCommandName().substring(0, cmd.getCommandName().length() - 8)); } - throw new ServerApiException(BaseCmd.PARAM_ERROR, "Unable to parse date " + paramObj + " for command " + cmd.getCommandName().substring(0, cmd.getCommandName().length() - 8) + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Unable to parse date " + paramObj + " for command " + cmd.getCommandName().substring(0, cmd.getCommandName().length() - 8) + ", please pass dates in the format mentioned in the api documentation"); } catch (InvalidParameterValueException invEx) { - throw new ServerApiException(BaseCmd.PARAM_ERROR, "Unable to execute API command " + cmd.getCommandName().substring(0, cmd.getCommandName().length() - 8) + " due to invalid value. " + invEx.getMessage()); + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Unable to execute API command " + cmd.getCommandName().substring(0, cmd.getCommandName().length() - 8) + " due to invalid value. " + invEx.getMessage()); } catch (CloudRuntimeException cloudEx) { // FIXME: Better error message? This only happens if the API command is not executable, which typically //means // there was // and IllegalAccessException setting one of the parameters. - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Internal error executing API command " + cmd.getCommandName().substring(0, cmd.getCommandName().length() - 8)); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Internal error executing API command " + cmd.getCommandName().substring(0, cmd.getCommandName().length() - 8)); } //check access on the resource this field points to diff --git a/server/src/com/cloud/api/ApiServer.java b/server/src/com/cloud/api/ApiServer.java index 72bed44ca1b..6b1de422269 100755 --- a/server/src/com/cloud/api/ApiServer.java +++ b/server/src/com/cloud/api/ApiServer.java @@ -102,6 +102,8 @@ import org.apache.cloudstack.api.command.user.tag.ListTagsCmd; import com.cloud.api.response.ApiResponseSerializer; import org.apache.cloudstack.api.response.ExceptionResponse; import org.apache.cloudstack.api.response.ListResponse; + +import com.cloud.async.AsyncCommandQueued; import com.cloud.async.AsyncJob; import com.cloud.async.AsyncJobManager; import com.cloud.async.AsyncJobVO; @@ -112,10 +114,14 @@ import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.domain.Domain; import com.cloud.domain.DomainVO; import com.cloud.event.EventUtils; +import com.cloud.exception.AccountLimitException; import com.cloud.exception.CloudAuthenticationException; +import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.PermissionDeniedException; import com.cloud.exception.RequestLimitException; +import com.cloud.exception.ResourceAllocationException; +import com.cloud.exception.ResourceUnavailableException; import com.cloud.server.ManagementServer; import com.cloud.user.Account; import com.cloud.user.AccountManager; @@ -276,8 +282,8 @@ public class ApiServer implements HttpRequestHandler { writeResponse(response, responseText, HttpStatus.SC_OK, responseType, null); } catch (ServerApiException se) { - String responseText = getSerializedApiError(se.getErrorCode(), se.getDescription(), parameterMap, responseType, se); - writeResponse(response, responseText, se.getErrorCode(), responseType, se.getDescription()); + String responseText = getSerializedApiError(se, parameterMap, responseType); + writeResponse(response, responseText, se.getErrorCode().getHttpCode(), responseType, se.getDescription()); sb.append(" " + se.getErrorCode() + " " + se.getDescription()); } catch (RuntimeException e) { // log runtime exception like NullPointerException to help identify the source easier @@ -306,7 +312,7 @@ public class ApiServer implements HttpRequestHandler { s_logger.trace(" key: " + keyStr + ", value: " + ((value == null) ? "'null'" : value[0])); } } - throw new ServerApiException(BaseCmd.UNSUPPORTED_ACTION_ERROR, "Invalid request, no command sent"); + throw new ServerApiException(ApiErrorCode.UNSUPPORTED_ACTION_ERROR, "Invalid request, no command sent"); } else { Map paramMap = new HashMap(); Set keys = params.keySet(); @@ -324,10 +330,10 @@ public class ApiServer implements HttpRequestHandler { decodedValue = URLDecoder.decode(value[0], "UTF-8"); } catch (UnsupportedEncodingException usex) { s_logger.warn(key + " could not be decoded, value = " + value[0]); - throw new ServerApiException(BaseCmd.PARAM_ERROR, key + " could not be decoded, received value " + value[0]); + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, key + " could not be decoded, received value " + value[0]); } catch (IllegalArgumentException iae) { s_logger.warn(key + " could not be decoded, value = " + value[0]); - throw new ServerApiException(BaseCmd.PARAM_ERROR, key + " could not be decoded, received value " + value[0] + " which contains illegal characters eg.%"); + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, key + " could not be decoded, received value " + value[0] + " which contains illegal characters eg.%"); } } else { decodedValue = value[0]; @@ -348,51 +354,81 @@ public class ApiServer implements HttpRequestHandler { String errorString = "Unknown API command: " + ((command == null) ? "null" : command[0]); s_logger.warn(errorString); auditTrailSb.append(" " + errorString); - throw new ServerApiException(BaseCmd.UNSUPPORTED_ACTION_ERROR, errorString); + throw new ServerApiException(ApiErrorCode.UNSUPPORTED_ACTION_ERROR, errorString); } } } - } catch (Exception ex) { - if (ex instanceof InvalidParameterValueException) { - InvalidParameterValueException ref = (InvalidParameterValueException)ex; - ServerApiException e = new ServerApiException(BaseCmd.PARAM_ERROR, ex.getMessage()); - // copy over the IdentityProxy information as well and throw the serverapiexception. - ArrayList idList = ref.getIdProxyList(); - if (idList != null) { - // Iterate through entire arraylist and copy over each proxy id. - for (int i = 0 ; i < idList.size(); i++) { - e.addProxyObject(idList.get(i)); - } - } - // Also copy over the cserror code and the function/layer in which it was thrown. - e.setCSErrorCode(ref.getCSErrorCode()); - throw e; - } else if (ex instanceof PermissionDeniedException) { - PermissionDeniedException ref = (PermissionDeniedException)ex; - ServerApiException e = new ServerApiException(BaseCmd.ACCOUNT_ERROR, ex.getMessage()); - // copy over the IdentityProxy information as well and throw the serverapiexception. - ArrayList idList = ref.getIdProxyList(); - if (idList != null) { - // Iterate through entire arraylist and copy over each proxy id. - for (int i = 0 ; i < idList.size(); i++) { - e.addProxyObject(idList.get(i)); - } - } - e.setCSErrorCode(ref.getCSErrorCode()); - throw e; - } else if (ex instanceof ServerApiException) { - throw (ServerApiException) ex; - } else { - s_logger.error("unhandled exception executing api command: " + ((command == null) ? "null" : command[0]), ex); - ServerApiException e = new ServerApiException(BaseCmd.INTERNAL_ERROR, "Internal server error, unable to execute request."); - e.setCSErrorCode(CSExceptionErrorCode.getCSErrCode("ServerApiException")); - throw e; - } } + catch (InvalidParameterValueException ex){ + s_logger.info(ex.getMessage()); + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, ex.getMessage(), ex); + } + catch (IllegalArgumentException ex){ + s_logger.info(ex.getMessage()); + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, ex.getMessage(), ex); + } + catch (PermissionDeniedException ex){ + ArrayList idList = ex.getIdProxyList(); + if (idList != null) { + s_logger.info("PermissionDenied: " + ex.getMessage() + " on uuids: [" + StringUtils.listToCsvTags(idList) + "]"); + } else { + s_logger.info("PermissionDenied: " + ex.getMessage()); + } + throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, ex.getMessage(), ex); + } + catch (AccountLimitException ex){ + s_logger.info(ex.getMessage()); + throw new ServerApiException(ApiErrorCode.ACCOUNT_RESOURCE_LIMIT_ERROR, ex.getMessage(), ex); + } + catch (InsufficientCapacityException ex){ + s_logger.info(ex.getMessage()); + String errorMsg = ex.getMessage(); + if (UserContext.current().getCaller().getType() != Account.ACCOUNT_TYPE_ADMIN){ + // hide internal details to non-admin user for security reason + errorMsg = BaseCmd.USER_ERROR_MESSAGE; + } + throw new ServerApiException(ApiErrorCode.INSUFFICIENT_CAPACITY_ERROR, errorMsg, ex); + } + catch (ResourceAllocationException ex){ + s_logger.info(ex.getMessage()); + String errorMsg = ex.getMessage(); + if (UserContext.current().getCaller().getType() != Account.ACCOUNT_TYPE_ADMIN){ + // hide internal details to non-admin user for security reason + errorMsg = BaseCmd.USER_ERROR_MESSAGE; + } + throw new ServerApiException(ApiErrorCode.RESOURCE_ALLOCATION_ERROR, errorMsg, ex); + } + catch (ResourceUnavailableException ex){ + s_logger.info(ex.getMessage()); + String errorMsg = ex.getMessage(); + if (UserContext.current().getCaller().getType() != Account.ACCOUNT_TYPE_ADMIN){ + // hide internal details to non-admin user for security reason + errorMsg = BaseCmd.USER_ERROR_MESSAGE; + } + throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, errorMsg, ex); + } + catch (AsyncCommandQueued ex){ + s_logger.error("unhandled exception executing api command: " + ((command == null) ? "null" : command[0]), ex); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Internal server error, unable to execute request."); + } + catch (ServerApiException ex){ + s_logger.info(ex.getDescription()); + throw ex; + } + catch (Exception ex){ + s_logger.error("unhandled exception executing api command: " + ((command == null) ? "null" : command[0]), ex); + String errorMsg = ex.getMessage(); + if (UserContext.current().getCaller().getType() != Account.ACCOUNT_TYPE_ADMIN){ + // hide internal details to non-admin user for security reason + errorMsg = BaseCmd.USER_ERROR_MESSAGE; + } + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, errorMsg, ex); + } + return response; } - private String queueCommand(BaseCmd cmdObj, Map params) { + private String queueCommand(BaseCmd cmdObj, Map params) throws Exception { UserContext ctx = UserContext.current(); Long callerUserId = ctx.getCallerUserId(); Account caller = ctx.getCaller(); @@ -448,7 +484,7 @@ public class ApiServer implements HttpRequestHandler { if (jobId == 0L) { String errorMsg = "Unable to schedule async job for command " + job.getCmd(); s_logger.warn(errorMsg); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, errorMsg); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, errorMsg); } if (objectId != null) { @@ -559,18 +595,18 @@ public class ApiServer implements HttpRequestHandler { } catch (PermissionDeniedException ex){ s_logger.debug("The given command:" + commandName + " does not exist or it is not available for user with id:" + userId); - throw new ServerApiException(BaseCmd.UNSUPPORTED_ACTION_ERROR, "The given command does not exist or it is not available for user"); + throw new ServerApiException(ApiErrorCode.UNSUPPORTED_ACTION_ERROR, "The given command does not exist or it is not available for user"); } catch (RequestLimitException ex){ s_logger.debug(ex.getMessage()); - throw new ServerApiException(BaseCmd.API_LIMIT_EXCEED, ex.getMessage()); + throw new ServerApiException(ApiErrorCode.API_LIMIT_EXCEED, ex.getMessage()); } return true; } else { // check against every available command to see if the command exists or not if (!_apiNameCmdClassMap.containsKey(commandName) && !commandName.equals("login") && !commandName.equals("logout")) { s_logger.debug("The given command:" + commandName + " does not exist or it is not available for user with id:" + userId); - throw new ServerApiException(BaseCmd.UNSUPPORTED_ACTION_ERROR, "The given command does not exist or it is not available for user"); + throw new ServerApiException(ApiErrorCode.UNSUPPORTED_ACTION_ERROR, "The given command does not exist or it is not available for user"); } } @@ -666,7 +702,7 @@ public class ApiServer implements HttpRequestHandler { } catch (PermissionDeniedException ex){ s_logger.debug("The given command:" + commandName + " does not exist or it is not available for user"); - throw new ServerApiException(BaseCmd.UNSUPPORTED_ACTION_ERROR, "The given command:" + commandName + " does not exist or it is not available for user with id:" + userId); + throw new ServerApiException(ApiErrorCode.UNSUPPORTED_ACTION_ERROR, "The given command:" + commandName + " does not exist or it is not available for user with id:" + userId); } // verify secret key exists @@ -940,13 +976,13 @@ public class ApiServer implements HttpRequestHandler { } } - public String getSerializedApiError(int errorCode, String errorText, Map apiCommandParams, String responseType, Exception ex) { + public String getSerializedApiError(int errorCode, String errorText, Map apiCommandParams, String responseType) { String responseName = null; Class cmdClass = null; String responseText = null; try { - if (errorCode == BaseCmd.UNSUPPORTED_ACTION_ERROR || apiCommandParams == null || apiCommandParams.isEmpty()) { + if (apiCommandParams == null || apiCommandParams.isEmpty()) { responseName = "errorresponse"; } else { Object cmdObj = apiCommandParams.get("command"); @@ -965,48 +1001,55 @@ public class ApiServer implements HttpRequestHandler { apiResponse.setErrorCode(errorCode); apiResponse.setErrorText(errorText); apiResponse.setResponseName(responseName); - // Also copy over the IdentityProxy object List into this new apiResponse, from - // the exception caught. When invoked from handle(), the exception here can - // be either ServerApiException, PermissionDeniedException or InvalidParameterValue - // Exception. When invoked from ApiServlet's processRequest(), this can be - // a standard exception like NumberFormatException. We'll leave the standard ones alone. - if (ex != null) { - if (ex instanceof ServerApiException || ex instanceof PermissionDeniedException - || ex instanceof InvalidParameterValueException) { - // Cast the exception appropriately and retrieve the IdentityProxy - if (ex instanceof ServerApiException) { - ServerApiException ref = (ServerApiException) ex; - ArrayList idList = ref.getIdProxyList(); - if (idList != null) { - for (int i=0; i < idList.size(); i++) { - apiResponse.addProxyObject(idList.get(i)); - } - } - // Also copy over the cserror code and the function/layer in which it was thrown. - apiResponse.setCSErrorCode(ref.getCSErrorCode()); - } else if (ex instanceof PermissionDeniedException) { - PermissionDeniedException ref = (PermissionDeniedException) ex; - ArrayList idList = ref.getIdProxyList(); - if (idList != null) { - for (int i=0; i < idList.size(); i++) { - apiResponse.addProxyObject(idList.get(i)); - } - } - // Also copy over the cserror code and the function/layer in which it was thrown. - apiResponse.setCSErrorCode(ref.getCSErrorCode()); - } else if (ex instanceof InvalidParameterValueException) { - InvalidParameterValueException ref = (InvalidParameterValueException) ex; - ArrayList idList = ref.getIdProxyList(); - if (idList != null) { - for (int i=0; i < idList.size(); i++) { - apiResponse.addProxyObject(idList.get(i)); - } - } - // Also copy over the cserror code and the function/layer in which it was thrown. - apiResponse.setCSErrorCode(ref.getCSErrorCode()); - } - } + SerializationContext.current().setUuidTranslation(true); + responseText = ApiResponseSerializer.toSerializedString(apiResponse, responseType); + + } catch (Exception e) { + s_logger.error("Exception responding to http request", e); + } + return responseText; + } + + public String getSerializedApiError(ServerApiException ex, Map apiCommandParams, String responseType) { + String responseName = null; + Class cmdClass = null; + String responseText = null; + + if (ex == null){ + // this call should not be invoked with null exception + return getSerializedApiError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Some internal error happened", apiCommandParams, responseType); + } + try { + if (ex.getErrorCode() == ApiErrorCode.UNSUPPORTED_ACTION_ERROR || apiCommandParams == null || apiCommandParams.isEmpty()) { + responseName = "errorresponse"; + } else { + Object cmdObj = apiCommandParams.get("command"); + // cmd name can be null when "command" parameter is missing in + // the request + if (cmdObj != null) { + String cmdName = ((String[]) cmdObj)[0]; + cmdClass = getCmdClass(cmdName); + if (cmdClass != null) { + responseName = ((BaseCmd) cmdClass.newInstance()).getCommandName(); + } else { + responseName = "errorresponse"; + } + } } + ExceptionResponse apiResponse = new ExceptionResponse(); + apiResponse.setErrorCode(ex.getErrorCode().getHttpCode()); + apiResponse.setErrorText(ex.getDescription()); + apiResponse.setResponseName(responseName); + ArrayList idList = ex.getIdProxyList(); + if (idList != null) { + for (int i = 0; i < idList.size(); i++) { + apiResponse.addProxyObject(idList.get(i)); + } + } + // Also copy over the cserror code and the function/layer in which + // it was thrown. + apiResponse.setCSErrorCode(ex.getCSErrorCode()); + SerializationContext.current().setUuidTranslation(true); responseText = ApiResponseSerializer.toSerializedString(apiResponse, responseType); diff --git a/server/src/com/cloud/api/ApiServlet.java b/server/src/com/cloud/api/ApiServlet.java index 21373cdf17f..0f8924a080c 100755 --- a/server/src/com/cloud/api/ApiServlet.java +++ b/server/src/com/cloud/api/ApiServlet.java @@ -28,6 +28,7 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.ServerApiException; import org.apache.log4j.Logger; @@ -192,7 +193,7 @@ public class ApiServlet extends HttpServlet { s_logger.warn("Invalid domain id entered by user"); auditTrailSb.append(" " + HttpServletResponse.SC_UNAUTHORIZED + " " + "Invalid domain id entered, please enter a valid one"); String serializedResponse = _apiServer.getSerializedApiError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid domain id entered, please enter a valid one", params, - responseType, null); + responseType); writeResponse(resp, serializedResponse, HttpServletResponse.SC_UNAUTHORIZED, responseType); } } @@ -227,10 +228,10 @@ public class ApiServlet extends HttpServlet { } catch (IllegalStateException ise) { } - auditTrailSb.append(" " + BaseCmd.ACCOUNT_ERROR + " " + ex.getMessage() != null ? ex.getMessage() : "failed to authenticate user, check if username/password are correct"); - String serializedResponse = _apiServer.getSerializedApiError(BaseCmd.ACCOUNT_ERROR, ex.getMessage() != null ? ex.getMessage() - : "failed to authenticate user, check if username/password are correct", params, responseType, null); - writeResponse(resp, serializedResponse, BaseCmd.ACCOUNT_ERROR, responseType); + auditTrailSb.append(" " + ApiErrorCode.ACCOUNT_ERROR + " " + ex.getMessage() != null ? ex.getMessage() : "failed to authenticate user, check if username/password are correct"); + String serializedResponse = _apiServer.getSerializedApiError(ApiErrorCode.ACCOUNT_ERROR.getHttpCode(), ex.getMessage() != null ? ex.getMessage() + : "failed to authenticate user, check if username/password are correct", params, responseType); + writeResponse(resp, serializedResponse, ApiErrorCode.ACCOUNT_ERROR.getHttpCode(), responseType); return; } } @@ -257,7 +258,7 @@ public class ApiServlet extends HttpServlet { } catch (IllegalStateException ise) { } auditTrailSb.append(" " + HttpServletResponse.SC_UNAUTHORIZED + " " + "unable to verify user credentials"); - String serializedResponse = _apiServer.getSerializedApiError(HttpServletResponse.SC_UNAUTHORIZED, "unable to verify user credentials", params, responseType, null); + String serializedResponse = _apiServer.getSerializedApiError(HttpServletResponse.SC_UNAUTHORIZED, "unable to verify user credentials", params, responseType); writeResponse(resp, serializedResponse, HttpServletResponse.SC_UNAUTHORIZED, responseType); return; } @@ -269,7 +270,7 @@ public class ApiServlet extends HttpServlet { if (command == null) { s_logger.info("missing command, ignoring request..."); auditTrailSb.append(" " + HttpServletResponse.SC_BAD_REQUEST + " " + "no command specified"); - String serializedResponse = _apiServer.getSerializedApiError(HttpServletResponse.SC_BAD_REQUEST, "no command specified", params, responseType, null); + String serializedResponse = _apiServer.getSerializedApiError(HttpServletResponse.SC_BAD_REQUEST, "no command specified", params, responseType); writeResponse(resp, serializedResponse, HttpServletResponse.SC_BAD_REQUEST, responseType); return; } @@ -283,7 +284,7 @@ public class ApiServlet extends HttpServlet { } auditTrailSb.append(" " + HttpServletResponse.SC_UNAUTHORIZED + " " + "unable to verify user credentials"); - String serializedResponse = _apiServer.getSerializedApiError(HttpServletResponse.SC_UNAUTHORIZED, "unable to verify user credentials", params, responseType, null); + String serializedResponse = _apiServer.getSerializedApiError(HttpServletResponse.SC_UNAUTHORIZED, "unable to verify user credentials", params, responseType); writeResponse(resp, serializedResponse, HttpServletResponse.SC_UNAUTHORIZED, responseType); return; } @@ -317,14 +318,14 @@ public class ApiServlet extends HttpServlet { } auditTrailSb.append(" " + HttpServletResponse.SC_UNAUTHORIZED + " " + "unable to verify user credentials and/or request signature"); - String serializedResponse = _apiServer.getSerializedApiError(HttpServletResponse.SC_UNAUTHORIZED, "unable to verify user credentials and/or request signature", params, responseType, null); + String serializedResponse = _apiServer.getSerializedApiError(HttpServletResponse.SC_UNAUTHORIZED, "unable to verify user credentials and/or request signature", params, responseType); writeResponse(resp, serializedResponse, HttpServletResponse.SC_UNAUTHORIZED, responseType); } } catch (ServerApiException se) { - String serializedResponseText = _apiServer.getSerializedApiError(se.getErrorCode(), se.getDescription(), params, responseType, null); + String serializedResponseText = _apiServer.getSerializedApiError(se, params, responseType); resp.setHeader("X-Description", se.getDescription()); - writeResponse(resp, serializedResponseText, se.getErrorCode(), responseType); + writeResponse(resp, serializedResponseText, se.getErrorCode().getHttpCode(), responseType); auditTrailSb.append(" " + se.getErrorCode() + " " + se.getDescription()); } catch (Exception ex) { s_logger.error("unknown exception writing api response", ex); diff --git a/server/src/com/cloud/api/commands/AddTrafficMonitorCmd.java b/server/src/com/cloud/api/commands/AddTrafficMonitorCmd.java index fdbbbe4ca3c..cdf83ae9ab6 100644 --- a/server/src/com/cloud/api/commands/AddTrafficMonitorCmd.java +++ b/server/src/com/cloud/api/commands/AddTrafficMonitorCmd.java @@ -97,9 +97,9 @@ public class AddTrafficMonitorCmd extends BaseCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } catch (InvalidParameterValueException ipve) { - throw new ServerApiException(BaseCmd.PARAM_ERROR, ipve.getMessage()); + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, ipve.getMessage()); } catch (CloudRuntimeException cre) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, cre.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, cre.getMessage()); } } } diff --git a/server/src/com/cloud/api/commands/DeleteTrafficMonitorCmd.java b/server/src/com/cloud/api/commands/DeleteTrafficMonitorCmd.java index 4c7d3a70546..d39323aa60d 100644 --- a/server/src/com/cloud/api/commands/DeleteTrafficMonitorCmd.java +++ b/server/src/com/cloud/api/commands/DeleteTrafficMonitorCmd.java @@ -20,6 +20,7 @@ import org.apache.cloudstack.api.response.HostResponse; import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.Parameter; @@ -33,25 +34,25 @@ import com.cloud.utils.component.ComponentLocator; @APICommand(name = "deleteTrafficMonitor", description="Deletes an traffic monitor host.", responseObject = SuccessResponse.class) public class DeleteTrafficMonitorCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(DeleteTrafficMonitorCmd.class.getName()); - private static final String s_name = "deletetrafficmonitorresponse"; - + public static final Logger s_logger = Logger.getLogger(DeleteTrafficMonitorCmd.class.getName()); + private static final String s_name = "deletetrafficmonitorresponse"; + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = HostResponse.class, required = true, description="Id of the Traffic Monitor Host.") private Long id; - + /////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public Long getId() { return id; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -60,12 +61,12 @@ public class DeleteTrafficMonitorCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ try { @@ -77,10 +78,10 @@ public class DeleteTrafficMonitorCmd extends BaseCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete traffic monitor."); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete traffic monitor."); } } catch (InvalidParameterValueException e) { - throw new ServerApiException(BaseCmd.PARAM_ERROR, "Failed to delete traffic monitor."); + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Failed to delete traffic monitor."); } } } diff --git a/server/src/com/cloud/api/commands/GenerateUsageRecordsCmd.java b/server/src/com/cloud/api/commands/GenerateUsageRecordsCmd.java index aa3c082ce81..4206cf82885 100644 --- a/server/src/com/cloud/api/commands/GenerateUsageRecordsCmd.java +++ b/server/src/com/cloud/api/commands/GenerateUsageRecordsCmd.java @@ -85,7 +85,7 @@ public class GenerateUsageRecordsCmd extends BaseCmd { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to generate usage records"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to generate usage records"); } } } diff --git a/server/src/com/cloud/async/AsyncJobManagerImpl.java b/server/src/com/cloud/async/AsyncJobManagerImpl.java index 7bf5c5a83cc..05d305eef6e 100644 --- a/server/src/com/cloud/async/AsyncJobManagerImpl.java +++ b/server/src/com/cloud/async/AsyncJobManagerImpl.java @@ -41,6 +41,8 @@ import org.apache.log4j.NDC; import com.cloud.api.ApiDispatcher; import com.cloud.api.ApiGsonHelper; import com.cloud.api.ApiSerializerHelper; + +import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.ServerApiException; @@ -78,13 +80,13 @@ import com.google.gson.reflect.TypeToken; public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListener { public static final Logger s_logger = Logger.getLogger(AsyncJobManagerImpl.class.getName()); private static final int ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_COOPERATION = 3; // 3 seconds - + private static final int MAX_ONETIME_SCHEDULE_SIZE = 50; private static final int HEARTBEAT_INTERVAL = 2000; private static final int GC_INTERVAL = 10000; // 10 seconds - + private String _name; - + private AsyncJobExecutorContext _context; private SyncQueueManager _queueMgr; private ClusterManager _clusterMgr; @@ -93,7 +95,7 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe private AsyncJobDao _jobDao; private long _jobExpireSeconds = 86400; // 1 day private long _jobCancelThresholdSeconds = 3600; // 1 hour (for cancelling the jobs blocking other jobs) - + private ApiDispatcher _dispatcher; private final ScheduledExecutorService _heartbeatScheduler = @@ -104,7 +106,7 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe public AsyncJobExecutorContext getExecutorContext() { return _context; } - + @Override public AsyncJobVO getAsyncJob(long jobId) { return _jobDao.findById(jobId); @@ -119,7 +121,7 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe public List findInstancePendingAsyncJobs(AsyncJob.Type instanceType, Long accountId) { return _jobDao.findInstancePendingAsyncJobs(instanceType, accountId); } - + @Override public long submitAsyncJob(AsyncJobVO job) { return submitAsyncJob(job, false); @@ -155,7 +157,7 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe s_logger.debug("Complete async job-" + jobId + ", jobStatus: " + jobStatus + ", resultCode: " + resultCode + ", result: " + resultObject); } - + Transaction txt = Transaction.currentTxn(); try { txt.start(); @@ -165,7 +167,7 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe s_logger.debug("job-" + jobId + " no longer exists, we just log completion info here. " + jobStatus + ", resultCode: " + resultCode + ", result: " + resultObject); } - + txt.rollback(); return; } @@ -197,7 +199,7 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe s_logger.debug("Update async-job progress, job-" + jobId + ", processStatus: " + processStatus + ", result: " + resultObject); } - + Transaction txt = Transaction.currentTxn(); try { txt.start(); @@ -206,11 +208,11 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe if(s_logger.isDebugEnabled()) { s_logger.debug("job-" + jobId + " no longer exists, we just log progress info here. progress status: " + processStatus); } - + txt.rollback(); return; } - + job.setProcessStatus(processStatus); if(resultObject != null) { job.setResult(ApiSerializerHelper.toSerializedStringOld(resultObject)); @@ -258,7 +260,7 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe if (job.getSyncSource() != null) { return; } - + if(s_logger.isDebugEnabled()) { s_logger.debug("Sync job-" + job.getId() + " execution on object " + syncObjType + "." + syncObjId); } @@ -287,7 +289,7 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe throw new AsyncCommandQueued(queue, "job-" + job.getId() + " queued"); } } - + @Override public AsyncJob queryAsyncJobResult(QueryAsyncJobResultCmd cmd) { Account caller = UserContext.current().getCaller(); @@ -296,10 +298,10 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe if (job == null) { throw new InvalidParameterValueException("Unable to find a job by id " + cmd.getId()); } - + User userJobOwner = _accountMgr.getUserIncludingRemoved(job.getUserId()); Account jobOwner = _accountMgr.getAccount(userJobOwner.getAccountId()); - + //check permissions if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL) { //regular user can see only jobs he owns @@ -309,7 +311,7 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe } else if (caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) { _accountMgr.checkAccess(caller, null, true, jobOwner); } - + //poll the job queryAsyncJobResult(cmd.getId()); return _jobDao.findById(cmd.getId()); @@ -320,10 +322,10 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe if(s_logger.isTraceEnabled()) { s_logger.trace("Query async-job status, job-" + jobId); } - + Transaction txt = Transaction.currentTxn(); AsyncJobResult jobResult = new AsyncJobResult(jobId); - + try { txt.start(); AsyncJobVO job = _jobDao.findById(jobId); @@ -334,10 +336,10 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe jobResult.setResult(job.getResult()); jobResult.setResultCode(job.getResultCode()); jobResult.setUuid(job.getUuid()); - + if(job.getStatus() == AsyncJobResult.STATUS_SUCCEEDED || job.getStatus() == AsyncJobResult.STATUS_FAILED) { - + if(s_logger.isDebugEnabled()) { s_logger.debug("Async job-" + jobId + " completed"); } @@ -349,23 +351,23 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe if(s_logger.isDebugEnabled()) { s_logger.debug("Async job-" + jobId + " does not exist, invalid job id?"); } - + jobResult.setJobStatus(AsyncJobResult.STATUS_FAILED); jobResult.setResult("job-" + jobId + " does not exist"); } txt.commit(); } catch(Exception e) { s_logger.error("Unexpected exception while querying async job-" + jobId + " status: ", e); - + jobResult.setJobStatus(AsyncJobResult.STATUS_FAILED); jobResult.setResult("Exception: " + e.toString()); txt.rollback(); } - + if(s_logger.isTraceEnabled()) { s_logger.trace("Job status: " + jobResult.toString()); } - + return jobResult; } @@ -388,66 +390,66 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe public void run() { try { long jobId = 0; - + try { JmxUtil.registerMBean("AsyncJobManager", "Active Job " + job.getId(), new AsyncJobMBeanImpl(job)); } catch(Exception e) { s_logger.warn("Unable to register active job " + job.getId() + " to JMX monitoring due to exception " + ExceptionUtil.toString(e)); } - + BaseAsyncCmd cmdObj = null; Transaction txn = Transaction.open(Transaction.CLOUD_DB); try { jobId = job.getId(); NDC.push("job-" + jobId); - + if(s_logger.isDebugEnabled()) { s_logger.debug("Executing " + job.getCmd() + " for job-" + jobId); } - + Class cmdClass = Class.forName(job.getCmd()); cmdObj = (BaseAsyncCmd)cmdClass.newInstance(); cmdObj.setJob(job); - + Type mapType = new TypeToken>() {}.getType(); Gson gson = ApiGsonHelper.getBuilder().create(); Map params = gson.fromJson(job.getCmdInfo(), mapType); - + // whenever we deserialize, the UserContext needs to be updated String userIdStr = params.get("ctxUserId"); String acctIdStr = params.get("ctxAccountId"); Long userId = null; Account accountObject = null; - + if (userIdStr != null) { userId = Long.parseLong(userIdStr); } - + if (acctIdStr != null) { accountObject = _accountDao.findById(Long.parseLong(acctIdStr)); } - + UserContext.registerContext(userId, accountObject, null, false); try { // dispatch could ultimately queue the job _dispatcher.dispatch(cmdObj, params); - + // serialize this to the async job table completeAsyncJob(jobId, AsyncJobResult.STATUS_SUCCEEDED, 0, cmdObj.getResponseObject()); } finally { UserContext.unregisterContext(); } - + // commands might need to be queued as part of synchronization here, so they just have to be re-dispatched from the queue mechanism... if (job.getSyncSource() != null) { _queueMgr.purgeItem(job.getSyncSource().getId()); checkQueue(job.getSyncSource().getQueueId()); } - + if (s_logger.isDebugEnabled()) { s_logger.debug("Done executing " + job.getCmd() + " for job-" + jobId); } - + } catch(Throwable e) { if (e instanceof AsyncCommandQueued) { if (s_logger.isDebugEnabled()) { @@ -456,25 +458,25 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe checkQueue(((AsyncCommandQueued)e).getQueue().getId()); } else { String errorMsg = null; - int errorCode = BaseCmd.INTERNAL_ERROR; + int errorCode = ApiErrorCode.INTERNAL_ERROR.getHttpCode(); if (!(e instanceof ServerApiException)) { s_logger.error("Unexpected exception while executing " + job.getCmd(), e); errorMsg = e.getMessage(); } else { ServerApiException sApiEx = (ServerApiException)e; errorMsg = sApiEx.getDescription(); - errorCode = sApiEx.getErrorCode(); + errorCode = sApiEx.getErrorCode().getHttpCode(); } - + ExceptionResponse response = new ExceptionResponse(); response.setErrorCode(errorCode); response.setErrorText(errorMsg); response.setResponseName((cmdObj == null) ? "unknowncommandresponse" : cmdObj.getCommandName()); - - // FIXME: setting resultCode to BaseCmd.INTERNAL_ERROR is not right, usually executors have their exception handling + + // FIXME: setting resultCode to ApiErrorCode.INTERNAL_ERROR is not right, usually executors have their exception handling // and we need to preserve that as much as possible here - completeAsyncJob(jobId, AsyncJobResult.STATUS_FAILED, BaseCmd.INTERNAL_ERROR, response); - + completeAsyncJob(jobId, AsyncJobResult.STATUS_FAILED, ApiErrorCode.INTERNAL_ERROR.getHttpCode(), response); + // need to clean up any queue that happened as part of the dispatching and move on to the next item in the queue try { if (job.getSyncSource() != null) { @@ -486,13 +488,13 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe } } } finally { - + try { JmxUtil.unregisterMBean("AsyncJobManager", "Active Job " + job.getId()); } catch(Exception e) { s_logger.warn("Unable to unregister active job " + job.getId() + " from JMX monitoring"); } - + StackMaid.current().exitCleanup(); txn.close(); NDC.pop(); @@ -516,17 +518,17 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe job.setFromPreviousSession(fromPreviousSession); job.setSyncSource(item); - + job.setCompleteMsid(getMsid()); _jobDao.update(job.getId(), job); - + try { scheduleExecution(job); } catch(RejectedExecutionException e) { s_logger.warn("Execution for job-" + job.getId() + " is rejected, return it to the queue for next turn"); _queueMgr.returnItem(item.getId()); } - + } else { if(s_logger.isDebugEnabled()) { s_logger.debug("Unable to find related job for queue item: " + item.toString()); @@ -544,12 +546,12 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe + executor.getSyncSource().getContentType() + "-" + executor.getSyncSource().getContentId()); } - + _queueMgr.purgeItem(executor.getSyncSource().getId()); checkQueue(executor.getSyncSource().getQueueId()); } } - + private void checkQueue(long queueId) { while(true) { try { @@ -558,7 +560,7 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe if(s_logger.isDebugEnabled()) { s_logger.debug("Executing sync queue item: " + item.toString()); } - + executeQueueItem(item, false); } else { break; @@ -569,7 +571,7 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe } } } - + private Runnable getHeartbeatTask() { return new Runnable() { @Override @@ -592,7 +594,7 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe } }; } - + @DB private Runnable getGCTask() { return new Runnable() { @@ -611,7 +613,7 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe scanLock.releaseRef(); } } - + public void reallyRun() { try { s_logger.trace("Begin cleanup expired async-jobs"); @@ -649,10 +651,10 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe } } - + }; } - + @DB protected void expungeAsyncJob(AsyncJobVO job) { Transaction txn = Transaction.currentTxn(); @@ -667,10 +669,10 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe if(_clusterMgr != null) { return _clusterMgr.getManagementNodeId(); } - + return MacAddress.getMacAddress().toLong(); } - + private void cleanupPendingJobs(List l) { if(l != null && l.size() > 0) { for(SyncQueueItemVO item: l) { @@ -701,7 +703,7 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe if (configDao == null) { throw new ConfigurationException("Unable to get the configuration dao."); } - + int expireMinutes = NumbersUtil.parseInt( configDao.getValue(Config.JobExpireMinutes.key()), 24*60); _jobExpireSeconds = (long)expireMinutes*60; @@ -719,48 +721,48 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe throw new ConfigurationException("Unable to get " + AsyncJobDao.class.getName()); } - + _context = locator.getManager(AsyncJobExecutorContext.class); if (_context == null) { throw new ConfigurationException("Unable to get " + AsyncJobExecutorContext.class.getName()); } - + _queueMgr = locator.getManager(SyncQueueManager.class); if(_queueMgr == null) { throw new ConfigurationException("Unable to get " + SyncQueueManager.class.getName()); } - + _clusterMgr = locator.getManager(ClusterManager.class); - + _accountMgr = locator.getManager(AccountManager.class); _dispatcher = ApiDispatcher.getInstance(); - + try { final File dbPropsFile = PropertiesUtil.findConfigFile("db.properties"); final Properties dbProps = new Properties(); dbProps.load(new FileInputStream(dbPropsFile)); - + final int cloudMaxActive = Integer.parseInt(dbProps.getProperty("db.cloud.maxActive")); - + int poolSize = (cloudMaxActive * 2) / 3; - + s_logger.info("Start AsyncJobManager thread pool in size " + poolSize); _executor = Executors.newFixedThreadPool(poolSize, new NamedThreadFactory("Job-Executor")); } catch (final Exception e) { throw new ConfigurationException("Unable to load db.properties to configure AsyncJobManagerImpl"); } - + return true; } - + @Override public void onManagementNodeJoined(List nodeList, long selfNodeId) { } - + @Override public void onManagementNodeLeft(List nodeList, long selfNodeId) { for(ManagementServerHostVO msHost : nodeList) { @@ -769,7 +771,7 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe txn.start(); List items = _queueMgr.getActiveQueueItems(msHost.getId(), true); cleanupPendingJobs(items); - _jobDao.resetJobProcess(msHost.getId(), BaseCmd.INTERNAL_ERROR, getSerializedErrorMessage("job cancelled because of management server restart")); + _jobDao.resetJobProcess(msHost.getId(), ApiErrorCode.INTERNAL_ERROR.getHttpCode(), getSerializedErrorMessage("job cancelled because of management server restart")); txn.commit(); } catch(Throwable e) { s_logger.warn("Unexpected exception ", e); @@ -779,7 +781,7 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe } } } - + @Override public void onManagementNodeIsolated() { } @@ -789,7 +791,7 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe try { List l = _queueMgr.getActiveQueueItems(getMsid(), false); cleanupPendingJobs(l); - _jobDao.resetJobProcess(getMsid(), BaseCmd.INTERNAL_ERROR, getSerializedErrorMessage("job cancelled because of management server restart")); + _jobDao.resetJobProcess(getMsid(), ApiErrorCode.INTERNAL_ERROR.getHttpCode(), getSerializedErrorMessage("job cancelled because of management server restart")); } catch(Throwable e) { s_logger.error("Unexpected exception " + e.getMessage(), e); } @@ -801,14 +803,14 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe return true; } - + private static ExceptionResponse getResetResultResponse(String errorMessage) { ExceptionResponse resultObject = new ExceptionResponse(); - resultObject.setErrorCode(BaseCmd.INTERNAL_ERROR); + resultObject.setErrorCode(ApiErrorCode.INTERNAL_ERROR.getHttpCode()); resultObject.setErrorText(errorMessage); return resultObject; } - + private static String getSerializedErrorMessage(String errorMessage) { return ApiSerializerHelper.toSerializedStringOld(getResetResultResponse(errorMessage)); } @@ -819,7 +821,7 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe _executor.shutdown(); return true; } - + @Override public String getName() { return _name; diff --git a/utils/src/com/cloud/utils/exception/CSExceptionErrorCode.java b/utils/src/com/cloud/utils/exception/CSExceptionErrorCode.java index 8f402336ba3..e794ea5d9c4 100755 --- a/utils/src/com/cloud/utils/exception/CSExceptionErrorCode.java +++ b/utils/src/com/cloud/utils/exception/CSExceptionErrorCode.java @@ -37,15 +37,12 @@ public class CSExceptionErrorCode { try { ExceptionErrorCodeMap = new HashMap(); ExceptionErrorCodeMap.put("com.cloud.utils.exception.CloudRuntimeException", 4250); - ExceptionErrorCodeMap.put("com.cloud.utils.exception.ExceptionUtil", 4255); ExceptionErrorCodeMap.put("com.cloud.utils.exception.ExecutionException", 4260); ExceptionErrorCodeMap.put("com.cloud.utils.exception.HypervisorVersionChangedException", 4265); - ExceptionErrorCodeMap.put("com.cloud.utils.exception.RuntimeCloudException", 4270); ExceptionErrorCodeMap.put("com.cloud.exception.CloudException", 4275); ExceptionErrorCodeMap.put("com.cloud.exception.AccountLimitException", 4280); ExceptionErrorCodeMap.put("com.cloud.exception.AgentUnavailableException", 4285); ExceptionErrorCodeMap.put("com.cloud.exception.CloudAuthenticationException", 4290); - ExceptionErrorCodeMap.put("com.cloud.exception.CloudExecutionException", 4295); ExceptionErrorCodeMap.put("com.cloud.exception.ConcurrentOperationException", 4300); ExceptionErrorCodeMap.put("com.cloud.exception.ConflictingNetworkSettingsException", 4305); ExceptionErrorCodeMap.put("com.cloud.exception.DiscoveredWithErrorException", 4310); @@ -66,35 +63,6 @@ public class CSExceptionErrorCode { ExceptionErrorCodeMap.put("com.cloud.exception.StorageUnavailableException", 4385); ExceptionErrorCodeMap.put("com.cloud.exception.UnsupportedServiceException", 4390); ExceptionErrorCodeMap.put("com.cloud.exception.VirtualMachineMigrationException", 4395); - - ExceptionErrorCodeMap.put("com.cloud.exception.AccountLimitException", 4400); - ExceptionErrorCodeMap.put("com.cloud.exception.AgentUnavailableException", 4405); - ExceptionErrorCodeMap.put("com.cloud.exception.CloudAuthenticationException", 4410); - ExceptionErrorCodeMap.put("com.cloud.exception.CloudException", 4415); - ExceptionErrorCodeMap.put("com.cloud.exception.CloudExecutionException", 4420); - ExceptionErrorCodeMap.put("com.cloud.exception.ConcurrentOperationException", 4425); - ExceptionErrorCodeMap.put("com.cloud.exception.ConflictingNetworkSettingsException", 4430); - ExceptionErrorCodeMap.put("com.cloud.exception.ConnectionException", 4435); - ExceptionErrorCodeMap.put("com.cloud.exception.DiscoveredWithErrorException", 4440); - ExceptionErrorCodeMap.put("com.cloud.exception.DiscoveryException", 4445); - ExceptionErrorCodeMap.put("com.cloud.exception.HAStateException", 4450); - ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientAddressCapacityException", 4455); - ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientCapacityException", 4460); - ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientNetworkCapacityException", 4465); - ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientServerCapacityException", 4470); - ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientStorageCapacityException", 4475); - ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientVirtualNetworkCapcityException", 4480); - ExceptionErrorCodeMap.put("com.cloud.exception.InternalErrorException", 4485); - ExceptionErrorCodeMap.put("com.cloud.exception.InvalidParameterValueException", 4490); - ExceptionErrorCodeMap.put("com.cloud.exception.ManagementServerException", 4495); - ExceptionErrorCodeMap.put("com.cloud.exception.NetworkRuleConflictException", 4500); - ExceptionErrorCodeMap.put("com.cloud.exception.PermissionDeniedException", 4505); - ExceptionErrorCodeMap.put("com.cloud.exception.ResourceAllocationException", 4510); - ExceptionErrorCodeMap.put("com.cloud.exception.ResourceInUseException", 4515); - ExceptionErrorCodeMap.put("com.cloud.exception.ResourceUnavailableException", 4520); - ExceptionErrorCodeMap.put("com.cloud.exception.StorageUnavailableException", 4525); - ExceptionErrorCodeMap.put("com.cloud.exception.UnsupportedServiceException", 4530); - ExceptionErrorCodeMap.put("com.cloud.exception.VirtualMachineMigrationException", 4535); ExceptionErrorCodeMap.put("com.cloud.async.AsyncCommandQueued", 4540); ExceptionErrorCodeMap.put("com.cloud.exception.RequestLimitException", 4545); From 06fa338d4257beaeb1fa54644f56c5222f3510bb Mon Sep 17 00:00:00 2001 From: Min Chen Date: Wed, 16 Jan 2013 21:56:25 -0800 Subject: [PATCH 24/80] Add some tests for api rate limit plugin. --- .../admin/ratelimit/ResetApiLimitCmd.java | 15 ++-- .../ratelimit/ApiRateLimitTest.java | 2 +- server/test/com/cloud/api/ListPerfTest.java | 75 ++++++++++++++++++- 3 files changed, 85 insertions(+), 7 deletions(-) diff --git a/plugins/api/rate-limit/src/org/apache/cloudstack/api/command/admin/ratelimit/ResetApiLimitCmd.java b/plugins/api/rate-limit/src/org/apache/cloudstack/api/command/admin/ratelimit/ResetApiLimitCmd.java index 771b63a9e78..58cab186570 100644 --- a/plugins/api/rate-limit/src/org/apache/cloudstack/api/command/admin/ratelimit/ResetApiLimitCmd.java +++ b/plugins/api/rate-limit/src/org/apache/cloudstack/api/command/admin/ratelimit/ResetApiLimitCmd.java @@ -16,14 +16,19 @@ // under the License. package org.apache.cloudstack.api.command.admin.ratelimit; -import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.ACL; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.PlugService; +import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.AccountResponse; import org.apache.cloudstack.api.response.ApiLimitResponse; import org.apache.cloudstack.api.response.SuccessResponse; -import org.apache.log4j.Logger; - -import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.ratelimit.ApiRateLimitService; +import org.apache.log4j.Logger; import com.cloud.user.Account; import com.cloud.user.UserContext; @@ -88,7 +93,7 @@ public class ResetApiLimitCmd extends BaseCmd { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to reset api limit counter"); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to reset api limit counter"); } } } diff --git a/plugins/api/rate-limit/test/org/apache/cloudstack/ratelimit/ApiRateLimitTest.java b/plugins/api/rate-limit/test/org/apache/cloudstack/ratelimit/ApiRateLimitTest.java index 850182d8f03..85eeaaf4223 100644 --- a/plugins/api/rate-limit/test/org/apache/cloudstack/ratelimit/ApiRateLimitTest.java +++ b/plugins/api/rate-limit/test/org/apache/cloudstack/ratelimit/ApiRateLimitTest.java @@ -100,7 +100,7 @@ public class ApiRateLimitTest { @Test public void canDoReasonableNumberOfApiAccessPerSecond() throws Exception { - int allowedRequests = 50000; + int allowedRequests = 200; _limitService.setMaxAllowed(allowedRequests); _limitService.setTimeToLive(1); diff --git a/server/test/com/cloud/api/ListPerfTest.java b/server/test/com/cloud/api/ListPerfTest.java index 350dde88b1c..c6fda9bf4eb 100644 --- a/server/test/com/cloud/api/ListPerfTest.java +++ b/server/test/com/cloud/api/ListPerfTest.java @@ -171,7 +171,73 @@ public class ListPerfTest extends APITest { } @Test - public void testMultiListAccounts() throws Exception { + public void testNoApiLimitOnRootAdmin() throws Exception { + // issue list Accounts calls + final HashMap params = new HashMap(); + params.put("response", "json"); + params.put("listAll", "true"); + params.put("sessionkey", sessionKey); + // assuming ApiRateLimitService set api.throttling.max = 25 + int clientCount = 26; + Runnable[] clients = new Runnable[clientCount]; + final boolean[] isUsable = new boolean[clientCount]; + + final CountDownLatch startGate = new CountDownLatch(1); + + final CountDownLatch endGate = new CountDownLatch(clientCount); + + + for (int i = 0; i < isUsable.length; ++i) { + final int j = i; + clients[j] = new Runnable() { + + /** + * {@inheritDoc} + */ + @Override + public void run() { + try { + startGate.await(); + + sendRequest("listAccounts", params); + + isUsable[j] = true; + + } catch (CloudRuntimeException e){ + isUsable[j] = false; + e.printStackTrace(); + } catch (InterruptedException e) { + e.printStackTrace(); + } finally { + endGate.countDown(); + } + } + }; + } + + ExecutorService executor = Executors.newFixedThreadPool(clientCount); + + for (Runnable runnable : clients) { + executor.execute(runnable); + } + + startGate.countDown(); + + endGate.await(); + + int rejectCount = 0; + for ( int i = 0; i < isUsable.length; ++i){ + if ( !isUsable[i]) + rejectCount++; + } + + assertEquals("No request should be rejected!", 0, rejectCount); + + } + + + @Test + public void testApiLimitOnUser() throws Exception { // log in using normal user login("demo", "password"); // issue list Accounts calls @@ -235,6 +301,13 @@ public class ListPerfTest extends APITest { assertEquals("Only one request should be rejected!", 1, rejectCount); + // issue get api limit calls + final HashMap params2 = new HashMap(); + params2.put("response", "json"); + params2.put("sessionkey", sessionKey); + String getResult = sendRequest("getApiLimit", params2); + //ApiLimitResponse loginResp = (ApiLimitResponse)fromSerializedString(getResult, ApiLimitResponse.class); + } } From 86ada92ffa20d7624ff3c411ac24ea9dbd9e0196 Mon Sep 17 00:00:00 2001 From: Min Chen Date: Thu, 17 Jan 2013 15:13:51 -0800 Subject: [PATCH 25/80] Fix some bugs and add java integration test for api rate limit plugin. --- client/tomcatconf/components.xml.in | 2 +- plugins/api/rate-limit/pom.xml | 22 ++ .../user/ratelimit/GetApiLimitCmd.java | 3 +- .../ratelimit/integration/APITest.java | 211 +++++++++++++++++ .../ratelimit/integration/LoginResponse.java | 142 ++++++++++++ .../integration/RateLimitIntegrationTest.java | 214 ++++++++++++++++++ server/test/com/cloud/api/APITest.java | 41 +++- server/test/com/cloud/api/ListPerfTest.java | 140 ------------ 8 files changed, 623 insertions(+), 152 deletions(-) create mode 100644 plugins/api/rate-limit/test/org/apache/cloudstack/ratelimit/integration/APITest.java create mode 100644 plugins/api/rate-limit/test/org/apache/cloudstack/ratelimit/integration/LoginResponse.java create mode 100644 plugins/api/rate-limit/test/org/apache/cloudstack/ratelimit/integration/RateLimitIntegrationTest.java diff --git a/client/tomcatconf/components.xml.in b/client/tomcatconf/components.xml.in index e19b4186122..81570512c3e 100755 --- a/client/tomcatconf/components.xml.in +++ b/client/tomcatconf/components.xml.in @@ -185,7 +185,7 @@ under the License. - + diff --git a/plugins/api/rate-limit/pom.xml b/plugins/api/rate-limit/pom.xml index 416c901cf8a..1f0330916a9 100644 --- a/plugins/api/rate-limit/pom.xml +++ b/plugins/api/rate-limit/pom.xml @@ -26,4 +26,26 @@ 4.1.0-SNAPSHOT ../../pom.xml + + install + src + test + + + test/resources + + + + + org.apache.maven.plugins + maven-surefire-plugin + + -Xmx1024m + + org/apache/cloudstack/ratelimit/integration/* + + + + + diff --git a/plugins/api/rate-limit/src/org/apache/cloudstack/api/command/user/ratelimit/GetApiLimitCmd.java b/plugins/api/rate-limit/src/org/apache/cloudstack/api/command/user/ratelimit/GetApiLimitCmd.java index ad1fb286c6e..2b7b8e6dbc1 100644 --- a/plugins/api/rate-limit/src/org/apache/cloudstack/api/command/user/ratelimit/GetApiLimitCmd.java +++ b/plugins/api/rate-limit/src/org/apache/cloudstack/api/command/user/ratelimit/GetApiLimitCmd.java @@ -46,7 +46,7 @@ import com.cloud.user.UserContext; import com.cloud.utils.exception.CloudRuntimeException; @APICommand(name = "getApiLimit", responseObject=ApiLimitResponse.class, description="Get API limit count for the caller") -public class GetApiLimitCmd extends BaseListCmd { +public class GetApiLimitCmd extends BaseCmd { private static final Logger s_logger = Logger.getLogger(GetApiLimitCmd.class.getName()); private static final String s_name = "getapilimitresponse"; @@ -81,6 +81,7 @@ public class GetApiLimitCmd extends BaseListCmd { Account caller = UserContext.current().getCaller(); ApiLimitResponse response = _apiLimitService.searchApiLimit(caller); response.setResponseName(getCommandName()); + response.setObjectName("apilimit"); this.setResponseObject(response); } } diff --git a/plugins/api/rate-limit/test/org/apache/cloudstack/ratelimit/integration/APITest.java b/plugins/api/rate-limit/test/org/apache/cloudstack/ratelimit/integration/APITest.java new file mode 100644 index 00000000000..7701b1515b0 --- /dev/null +++ b/plugins/api/rate-limit/test/org/apache/cloudstack/ratelimit/integration/APITest.java @@ -0,0 +1,211 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.ratelimit.integration; + +import java.io.BufferedReader; +import java.io.EOFException; +import java.io.InputStreamReader; +import java.math.BigInteger; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLEncoder; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HashMap; +import java.util.Iterator; + +import org.apache.cloudstack.api.response.SuccessResponse; + +import com.cloud.api.ApiGsonHelper; +import com.cloud.utils.exception.CloudRuntimeException; +import com.google.gson.Gson; + +/** + * Base class for API Test + * + * @author Min Chen + * + */ +public abstract class APITest { + + protected String rootUrl = "http://localhost:8080/client/api"; + protected String sessionKey = null; + protected String cookieToSent = null; + + + /** + * Sending an api request through Http GET + * @param command command name + * @param params command query parameters in a HashMap + * @return http request response string + */ + protected String sendRequest(String command, HashMap params){ + try { + // Construct query string + StringBuilder sBuilder = new StringBuilder(); + sBuilder.append("command="); + sBuilder.append(command); + if ( params != null && params.size() > 0){ + Iterator keys = params.keySet().iterator(); + while (keys.hasNext()){ + String key = keys.next(); + sBuilder.append("&"); + sBuilder.append(key); + sBuilder.append("="); + sBuilder.append(URLEncoder.encode(params.get(key), "UTF-8")); + } + } + + // Construct request url + String reqUrl = rootUrl + "?" + sBuilder.toString(); + + // Send Http GET request + URL url = new URL(reqUrl); + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); + conn.setRequestMethod("GET"); + + if ( !command.equals("login") && cookieToSent != null){ + // add the cookie to a request + conn.setRequestProperty("Cookie", cookieToSent); + } + conn.connect(); + + + if ( command.equals("login")){ + // if it is login call, store cookie + String headerName=null; + for (int i=1; (headerName = conn.getHeaderFieldKey(i))!=null; i++) { + if (headerName.equals("Set-Cookie")) { + String cookie = conn.getHeaderField(i); + cookie = cookie.substring(0, cookie.indexOf(";")); + String cookieName = cookie.substring(0, cookie.indexOf("=")); + String cookieValue = cookie.substring(cookie.indexOf("=") + 1, cookie.length()); + cookieToSent = cookieName + "=" + cookieValue; + } + } + } + + // Get the response + StringBuilder response = new StringBuilder(); + BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); + String line; + try { + while ((line = rd.readLine()) != null) { + response.append(line); + } + } catch (EOFException ex) { + // ignore this exception + System.out.println("EOF exception due to java bug"); + } + rd.close(); + + + + return response.toString(); + + } catch (Exception e) { + throw new CloudRuntimeException("Problem with sending api request", e); + } + } + + protected String createMD5String(String password) { + MessageDigest md5; + try { + md5 = MessageDigest.getInstance("MD5"); + } catch (NoSuchAlgorithmException e) { + throw new CloudRuntimeException("Error", e); + } + + md5.reset(); + BigInteger pwInt = new BigInteger(1, md5.digest(password.getBytes())); + + // make sure our MD5 hash value is 32 digits long... + StringBuffer sb = new StringBuffer(); + String pwStr = pwInt.toString(16); + int padding = 32 - pwStr.length(); + for (int i = 0; i < padding; i++) { + sb.append('0'); + } + sb.append(pwStr); + return sb.toString(); + } + + + protected Object fromSerializedString(String result, Class repCls) { + try { + if (result != null && !result.isEmpty()) { + // get real content + int start; + int end; + if (repCls == LoginResponse.class || repCls == SuccessResponse.class) { + + start = result.indexOf('{', result.indexOf('{') + 1); // find + // the + // second + // { + + end = result.lastIndexOf('}', result.lastIndexOf('}') - 1); // find + // the + // second + // } + // backwards + + } else { + // get real content + start = result.indexOf('{', result.indexOf('{', result.indexOf('{') + 1) + 1); // find + // the + // third + // { + end = result.lastIndexOf('}', result.lastIndexOf('}', result.lastIndexOf('}') - 1) - 1); // find + // the + // third + // } + // backwards + } + if (start < 0 || end < 0) { + throw new CloudRuntimeException("Response format is wrong: " + result); + } + String content = result.substring(start, end + 1); + Gson gson = ApiGsonHelper.getBuilder().create(); + return gson.fromJson(content, repCls); + } + return null; + } catch (RuntimeException e) { + throw new CloudRuntimeException("Caught runtime exception when doing GSON deserialization on: " + result, e); + } + } + + /** + * Login call + * @param username user name + * @param password password (plain password, we will do MD5 hash here for you) + * @return login response string + */ + protected void login(String username, String password) + { + //String md5Psw = createMD5String(password); + // send login request + HashMap params = new HashMap(); + params.put("response", "json"); + params.put("username", username); + params.put("password", password); + String result = this.sendRequest("login", params); + LoginResponse loginResp = (LoginResponse)fromSerializedString(result, LoginResponse.class); + sessionKey = loginResp.getSessionkey(); + + } +} diff --git a/plugins/api/rate-limit/test/org/apache/cloudstack/ratelimit/integration/LoginResponse.java b/plugins/api/rate-limit/test/org/apache/cloudstack/ratelimit/integration/LoginResponse.java new file mode 100644 index 00000000000..719f39c0a5e --- /dev/null +++ b/plugins/api/rate-limit/test/org/apache/cloudstack/ratelimit/integration/LoginResponse.java @@ -0,0 +1,142 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.ratelimit.integration; + +import org.apache.cloudstack.api.BaseResponse; + +import com.cloud.serializer.Param; +import com.google.gson.annotations.SerializedName; + +/** + * Login Response object + * + * @author Min Chen + * + */ +public class LoginResponse extends BaseResponse { + + @SerializedName("timeout") + @Param(description = "session timeout period") + private String timeout; + + @SerializedName("sessionkey") + @Param(description = "login session key") + private String sessionkey; + + @SerializedName("username") + @Param(description = "login username") + private String username; + + @SerializedName("userid") + @Param(description = "login user internal uuid") + private String userid; + + @SerializedName("firstname") + @Param(description = "login user firstname") + private String firstname; + + @SerializedName("lastname") + @Param(description = "login user lastname") + private String lastname; + + @SerializedName("account") + @Param(description = "login user account type") + private String account; + + @SerializedName("domainid") + @Param(description = "login user domain id") + private String domainid; + + @SerializedName("type") + @Param(description = "login user type") + private int type; + + public String getTimeout() { + return timeout; + } + + public void setTimeout(String timeout) { + this.timeout = timeout; + } + + public String getSessionkey() { + return sessionkey; + } + + public void setSessionkey(String sessionkey) { + this.sessionkey = sessionkey; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getUserid() { + return userid; + } + + public void setUserid(String userid) { + this.userid = userid; + } + + public String getFirstname() { + return firstname; + } + + public void setFirstname(String firstname) { + this.firstname = firstname; + } + + public String getLastname() { + return lastname; + } + + public void setLastname(String lastname) { + this.lastname = lastname; + } + + public String getAccount() { + return account; + } + + public void setAccount(String account) { + this.account = account; + } + + public String getDomainid() { + return domainid; + } + + public void setDomainid(String domainid) { + this.domainid = domainid; + } + + public int getType() { + return type; + } + + public void setType(int type) { + this.type = type; + } + + + +} diff --git a/plugins/api/rate-limit/test/org/apache/cloudstack/ratelimit/integration/RateLimitIntegrationTest.java b/plugins/api/rate-limit/test/org/apache/cloudstack/ratelimit/integration/RateLimitIntegrationTest.java new file mode 100644 index 00000000000..72d354c6c77 --- /dev/null +++ b/plugins/api/rate-limit/test/org/apache/cloudstack/ratelimit/integration/RateLimitIntegrationTest.java @@ -0,0 +1,214 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.ratelimit.integration; + +import static org.junit.Assert.*; + +import java.util.HashMap; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import org.apache.cloudstack.api.response.ApiLimitResponse; +import org.apache.cloudstack.api.response.SuccessResponse; +import org.junit.Before; +import org.junit.Test; + +import com.cloud.utils.exception.CloudRuntimeException; + + +/** + * Test fixture to do integration rate limit test. + * Currently we commented out this test suite since it requires a real MS and Db running. + * + * @author Min Chen + * + */ +public class RateLimitIntegrationTest extends APITest { + + private static int apiMax = 25; // assuming ApiRateLimitService set api.throttling.max = 25 + + @Before + public void setup(){ + // always reset count for each testcase + login("admin", "password"); + + // issue reset api limit calls + final HashMap params = new HashMap(); + params.put("response", "json"); + params.put("sessionkey", sessionKey); + String resetResult = sendRequest("resetApiLimit", params); + assertNotNull("Reset count failed!", fromSerializedString(resetResult, SuccessResponse.class)); + + } + + + @Test + public void testNoApiLimitOnRootAdmin() throws Exception { + // issue list Accounts calls + final HashMap params = new HashMap(); + params.put("response", "json"); + params.put("listAll", "true"); + params.put("sessionkey", sessionKey); + // assuming ApiRateLimitService set api.throttling.max = 25 + int clientCount = 26; + Runnable[] clients = new Runnable[clientCount]; + final boolean[] isUsable = new boolean[clientCount]; + + final CountDownLatch startGate = new CountDownLatch(1); + + final CountDownLatch endGate = new CountDownLatch(clientCount); + + + for (int i = 0; i < isUsable.length; ++i) { + final int j = i; + clients[j] = new Runnable() { + + /** + * {@inheritDoc} + */ + @Override + public void run() { + try { + startGate.await(); + + sendRequest("listAccounts", params); + + isUsable[j] = true; + + } catch (CloudRuntimeException e){ + isUsable[j] = false; + e.printStackTrace(); + } catch (InterruptedException e) { + e.printStackTrace(); + } finally { + endGate.countDown(); + } + } + }; + } + + ExecutorService executor = Executors.newFixedThreadPool(clientCount); + + for (Runnable runnable : clients) { + executor.execute(runnable); + } + + startGate.countDown(); + + endGate.await(); + + int rejectCount = 0; + for ( int i = 0; i < isUsable.length; ++i){ + if ( !isUsable[i]) + rejectCount++; + } + + assertEquals("No request should be rejected!", 0, rejectCount); + + } + + + @Test + public void testApiLimitOnUser() throws Exception { + // log in using normal user + login("demo", "password"); + // issue list Accounts calls + final HashMap params = new HashMap(); + params.put("response", "json"); + params.put("listAll", "true"); + params.put("sessionkey", sessionKey); + + int clientCount = apiMax + 1; + Runnable[] clients = new Runnable[clientCount]; + final boolean[] isUsable = new boolean[clientCount]; + + final CountDownLatch startGate = new CountDownLatch(1); + + final CountDownLatch endGate = new CountDownLatch(clientCount); + + + for (int i = 0; i < isUsable.length; ++i) { + final int j = i; + clients[j] = new Runnable() { + + /** + * {@inheritDoc} + */ + @Override + public void run() { + try { + startGate.await(); + + sendRequest("listAccounts", params); + + isUsable[j] = true; + + } catch (CloudRuntimeException e){ + isUsable[j] = false; + e.printStackTrace(); + } catch (InterruptedException e) { + e.printStackTrace(); + } finally { + endGate.countDown(); + } + } + }; + } + + ExecutorService executor = Executors.newFixedThreadPool(clientCount); + + for (Runnable runnable : clients) { + executor.execute(runnable); + } + + startGate.countDown(); + + endGate.await(); + + int rejectCount = 0; + for ( int i = 0; i < isUsable.length; ++i){ + if ( !isUsable[i]) + rejectCount++; + } + + assertEquals("Only one request should be rejected!", 1, rejectCount); + + } + + @Test + public void testGetApiLimitOnUser() throws Exception { + // log in using normal user + login("demo", "password"); + + // issue an api call + HashMap params = new HashMap(); + params.put("response", "json"); + params.put("listAll", "true"); + params.put("sessionkey", sessionKey); + sendRequest("listAccounts", params); + + // issue get api limit calls + final HashMap params2 = new HashMap(); + params2.put("response", "json"); + params2.put("sessionkey", sessionKey); + String getResult = sendRequest("getApiLimit", params2); + ApiLimitResponse getLimitResp = (ApiLimitResponse)fromSerializedString(getResult, ApiLimitResponse.class); + assertEquals("Issued api count is incorrect!", 2, getLimitResp.getApiIssued() ); // should be 2 apis issues plus this getlimit api + assertEquals("Allowed api count is incorrect!", apiMax -2, getLimitResp.getApiAllowed()); + } +} diff --git a/server/test/com/cloud/api/APITest.java b/server/test/com/cloud/api/APITest.java index 69c488f5a10..0b040abc3f5 100644 --- a/server/test/com/cloud/api/APITest.java +++ b/server/test/com/cloud/api/APITest.java @@ -19,17 +19,17 @@ package com.cloud.api; import java.io.BufferedReader; import java.io.EOFException; import java.io.InputStreamReader; -import java.io.OutputStreamWriter; import java.math.BigInteger; import java.net.HttpURLConnection; import java.net.URL; -import java.net.URLConnection; import java.net.URLEncoder; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.HashMap; import java.util.Iterator; +import org.apache.cloudstack.api.response.SuccessResponse; + import com.cloud.utils.exception.CloudRuntimeException; import com.google.gson.Gson; @@ -147,17 +147,38 @@ public abstract class APITest { protected Object fromSerializedString(String result, Class repCls) { try { if (result != null && !result.isEmpty()) { - // get real content - int start = result.indexOf('{', result.indexOf('{') + 1); // find the second { - if ( start < 0 ){ + int start; + int end; + if (repCls == LoginResponse.class || repCls == SuccessResponse.class) { + + start = result.indexOf('{', result.indexOf('{') + 1); // find + // the + // second + // { + + end = result.lastIndexOf('}', result.lastIndexOf('}') - 1); // find + // the + // second + // } + // backwards + + } else { + // get real content + start = result.indexOf('{', result.indexOf('{', result.indexOf('{') + 1) + 1); // find + // the + // third + // { + end = result.lastIndexOf('}', result.lastIndexOf('}', result.lastIndexOf('}') - 1) - 1); // find + // the + // third + // } + // backwards + } + if (start < 0 || end < 0) { throw new CloudRuntimeException("Response format is wrong: " + result); } - int end = result.lastIndexOf('}', result.lastIndexOf('}')-1); // find the second } backwards - if ( end < 0 ){ - throw new CloudRuntimeException("Response format is wrong: " + result); - } - String content = result.substring(start, end+1); + String content = result.substring(start, end + 1); Gson gson = ApiGsonHelper.getBuilder().create(); return gson.fromJson(content, repCls); } diff --git a/server/test/com/cloud/api/ListPerfTest.java b/server/test/com/cloud/api/ListPerfTest.java index c6fda9bf4eb..b8cb97eb8f0 100644 --- a/server/test/com/cloud/api/ListPerfTest.java +++ b/server/test/com/cloud/api/ListPerfTest.java @@ -170,144 +170,4 @@ public class ListPerfTest extends APITest { } - @Test - public void testNoApiLimitOnRootAdmin() throws Exception { - // issue list Accounts calls - final HashMap params = new HashMap(); - params.put("response", "json"); - params.put("listAll", "true"); - params.put("sessionkey", sessionKey); - // assuming ApiRateLimitService set api.throttling.max = 25 - int clientCount = 26; - Runnable[] clients = new Runnable[clientCount]; - final boolean[] isUsable = new boolean[clientCount]; - - final CountDownLatch startGate = new CountDownLatch(1); - - final CountDownLatch endGate = new CountDownLatch(clientCount); - - - for (int i = 0; i < isUsable.length; ++i) { - final int j = i; - clients[j] = new Runnable() { - - /** - * {@inheritDoc} - */ - @Override - public void run() { - try { - startGate.await(); - - sendRequest("listAccounts", params); - - isUsable[j] = true; - - } catch (CloudRuntimeException e){ - isUsable[j] = false; - e.printStackTrace(); - } catch (InterruptedException e) { - e.printStackTrace(); - } finally { - endGate.countDown(); - } - } - }; - } - - ExecutorService executor = Executors.newFixedThreadPool(clientCount); - - for (Runnable runnable : clients) { - executor.execute(runnable); - } - - startGate.countDown(); - - endGate.await(); - - int rejectCount = 0; - for ( int i = 0; i < isUsable.length; ++i){ - if ( !isUsable[i]) - rejectCount++; - } - - assertEquals("No request should be rejected!", 0, rejectCount); - - } - - - @Test - public void testApiLimitOnUser() throws Exception { - // log in using normal user - login("demo", "password"); - // issue list Accounts calls - final HashMap params = new HashMap(); - params.put("response", "json"); - params.put("listAll", "true"); - params.put("sessionkey", sessionKey); - // assuming ApiRateLimitService set api.throttling.max = 25 - int clientCount = 26; - Runnable[] clients = new Runnable[clientCount]; - final boolean[] isUsable = new boolean[clientCount]; - - final CountDownLatch startGate = new CountDownLatch(1); - - final CountDownLatch endGate = new CountDownLatch(clientCount); - - - for (int i = 0; i < isUsable.length; ++i) { - final int j = i; - clients[j] = new Runnable() { - - /** - * {@inheritDoc} - */ - @Override - public void run() { - try { - startGate.await(); - - sendRequest("listAccounts", params); - - isUsable[j] = true; - - } catch (CloudRuntimeException e){ - isUsable[j] = false; - e.printStackTrace(); - } catch (InterruptedException e) { - e.printStackTrace(); - } finally { - endGate.countDown(); - } - } - }; - } - - ExecutorService executor = Executors.newFixedThreadPool(clientCount); - - for (Runnable runnable : clients) { - executor.execute(runnable); - } - - startGate.countDown(); - - endGate.await(); - - int rejectCount = 0; - for ( int i = 0; i < isUsable.length; ++i){ - if ( !isUsable[i]) - rejectCount++; - } - - assertEquals("Only one request should be rejected!", 1, rejectCount); - - // issue get api limit calls - final HashMap params2 = new HashMap(); - params2.put("response", "json"); - params2.put("sessionkey", sessionKey); - String getResult = sendRequest("getApiLimit", params2); - //ApiLimitResponse loginResp = (ApiLimitResponse)fromSerializedString(getResult, ApiLimitResponse.class); - - } - } From 805261a93f73928a3ce47c89f50bea21964d861b Mon Sep 17 00:00:00 2001 From: Min Chen Date: Thu, 17 Jan 2013 15:16:50 -0800 Subject: [PATCH 26/80] Change a debug message to TRACE level. --- .../apache/cloudstack/ratelimit/ApiRateLimitServiceImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/api/rate-limit/src/org/apache/cloudstack/ratelimit/ApiRateLimitServiceImpl.java b/plugins/api/rate-limit/src/org/apache/cloudstack/ratelimit/ApiRateLimitServiceImpl.java index 1e9b9adf41c..303b92da5ed 100644 --- a/plugins/api/rate-limit/src/org/apache/cloudstack/ratelimit/ApiRateLimitServiceImpl.java +++ b/plugins/api/rate-limit/src/org/apache/cloudstack/ratelimit/ApiRateLimitServiceImpl.java @@ -158,7 +158,7 @@ public class ApiRateLimitServiceImpl extends AdapterBase implements APIChecker, int current = entry.incrementAndGet(); if (current <= maxAllowed) { - s_logger.info("current count = " + current); + s_logger.trace("account (" + account.getAccountId() + "," + account.getAccountName() + ") has current count = " + current); return true; } else { long expireAfter = entry.getExpireDuration(); From 77bc04b90f134a6da89369ec3118f5cf041c7c95 Mon Sep 17 00:00:00 2001 From: Jessica Wang Date: Fri, 18 Jan 2013 10:38:38 -0800 Subject: [PATCH 27/80] CLOUDSTACK-537: cloudstack UI - Advanced SG-enabled zone - Instance wizard UI: Support advanced zone with security groups For advanced zones with SG enabled, show both the add guest network step as well as the add security group step. reviewed-by: jessica --- ui/index.jsp | 2 +- ui/scripts/instanceWizard.js | 31 ++++++++++++++++++++------ ui/scripts/ui-custom/instanceWizard.js | 19 ++++++++++++++-- 3 files changed, 42 insertions(+), 10 deletions(-) diff --git a/ui/index.jsp b/ui/index.jsp index a9b83e6fdd5..3fe6bad5f4a 100644 --- a/ui/index.jsp +++ b/ui/index.jsp @@ -220,7 +220,7 @@ under the License. -
+

diff --git a/ui/scripts/instanceWizard.js b/ui/scripts/instanceWizard.js index e4b1f31d427..65ec33fe0bf 100644 --- a/ui/scripts/instanceWizard.js +++ b/ui/scripts/instanceWizard.js @@ -268,25 +268,30 @@ } if (selectedZoneObj.networktype == "Advanced") { //Advanced zone. Show network list. - var $networkStep = $(".step.network:visible .nothing-to-select"); + var $networkStep = $(".step.network:visible .nothing-to-select"); + var $networkStepContainer = $('.step.network:visible'); + if(args.initArgs.pluginForm != null && args.initArgs.pluginForm.name == "vpcTierInstanceWizard") { //from VPC Tier chart step5ContainerType = 'nothing-to-select'; $networkStep.find("#from_instance_page_1").hide(); $networkStep.find("#from_instance_page_2").hide(); $networkStep.find("#from_vpc_tier").text("tier " + args.context.networks[0].name); $networkStep.find("#from_vpc_tier").show(); - } - else { //from Instance page + } else { //from Instance page if(selectedZoneObj.securitygroupsenabled != true) { // Advanced SG-disabled zone step5ContainerType = 'select-network'; $networkStep.find("#from_instance_page_1").show(); $networkStep.find("#from_instance_page_2").show(); $networkStep.find("#from_vpc_tier").text(""); $networkStep.find("#from_vpc_tier").hide(); + } else { // Advanced SG-enabled zone + step5ContainerType = 'select-advanced-sg'; } - else { // Advanced SG-enabled zone - step5ContainerType = 'select-security-group'; - } + + if ($networkStepContainer.hasClass('next-use-security-groups')) { + $networkStepContainer.removeClass('repeat next-use-security-groups loaded'); + step5ContainerType = 'select-security-group'; + } } } else { //Basic zone. Show securigy group list or nothing(when no SecurityGroup service in guest network) @@ -320,7 +325,7 @@ } //step5ContainerType = 'nothing-to-select'; //for testing only, comment it out before checking in - if(step5ContainerType == 'select-network') { + if(step5ContainerType == 'select-network' || step5ContainerType == 'select-advanced-sg') { var defaultNetworkArray = [], optionalNetworkArray = []; var networkData = { zoneId: args.currentData.zoneid @@ -379,6 +384,9 @@ }); //get network offerings (end) *** + if (step5ContainerType == 'select-advanced-sg') { + $networkStepContainer.addClass('repeat next-use-security-groups'); + } args.response.success({ type: 'select-network', @@ -449,6 +457,15 @@ // Create a new VM!!!! var array1 = []; + // + // @jessica + // If using an advanced security group zone, get the guest networks like this + // + // var myNetworks = $('.multi-wizard:visible form').data('my-networks'); + // + // -- and get the security groups from args.data['security-groups'] + // + //step 1 : select zone array1.push("&zoneId=" + args.data.zoneid); diff --git a/ui/scripts/ui-custom/instanceWizard.js b/ui/scripts/ui-custom/instanceWizard.js index d2724a524f3..f2cfd9ced53 100644 --- a/ui/scripts/ui-custom/instanceWizard.js +++ b/ui/scripts/ui-custom/instanceWizard.js @@ -598,6 +598,8 @@ response: { success: function(args) { var vpcs = args.data.vpcs; + var addClass = args.addClass; + var removeClass = args.removeClass; // Populate VPC drop-down $vpcSelect.html(''); @@ -753,7 +755,8 @@ ) ); - $targetStep.addClass('loaded'); + if (!$targetStep.hasClass('repeat') && + !$targetStep.hasClass('always-load')) $targetStep.addClass('loaded'); } // Show launch vm button if last step @@ -806,6 +809,14 @@ //step 5 - select network if($activeStep.find('.wizard-step-conditional.select-network:visible').size() > 0) { + var data = $activeStep.data('my-networks'); + + if (!data) { + $activeStep.closest('form').data('my-networks', cloudStack.serializeForm( + $activeStep.closest('form') + )['my-networks']); + } + if($activeStep.find('input[type=checkbox]:checked').size() == 0) { //if no checkbox is checked cloudStack.dialog.notice({ message: 'message.step.4.continue' }); return false; @@ -828,7 +839,11 @@ } } - showStep($steps.filter(':visible').index() + 2); + if ($activeStep.hasClass('repeat')) { + showStep($steps.filter(':visible').index() + 1); + } else { + showStep($steps.filter(':visible').index() + 2); + } return false; } From c9921ea0773d7b06933c74d03024fabd62943013 Mon Sep 17 00:00:00 2001 From: Jessica Wang Date: Fri, 18 Jan 2013 10:44:44 -0800 Subject: [PATCH 28/80] CLOUDSTACK-537: cloudstack UI - Advanced SG-enabled zone - VM Wizard - step 5 - show network list first, then security group list. reviewed-by: Brian --- ui/scripts/instanceWizard.js | 70 +++++++++++++++--------------------- 1 file changed, 29 insertions(+), 41 deletions(-) diff --git a/ui/scripts/instanceWizard.js b/ui/scripts/instanceWizard.js index 65ec33fe0bf..b98147b2056 100644 --- a/ui/scripts/instanceWizard.js +++ b/ui/scripts/instanceWizard.js @@ -457,15 +457,6 @@ // Create a new VM!!!! var array1 = []; - // - // @jessica - // If using an advanced security group zone, get the guest networks like this - // - // var myNetworks = $('.multi-wizard:visible form').data('my-networks'); - // - // -- and get the security groups from args.data['security-groups'] - // - //step 1 : select zone array1.push("&zoneId=" + args.data.zoneid); @@ -562,41 +553,38 @@ if(checkedSecurityGroupIdArray.length > 0) array1.push("&securitygroupids=" + checkedSecurityGroupIdArray.join(",")); - - /* - if(selectedZoneObj.networktype == "Advanced" && selectedZoneObj.securitygroupsenabled == true) { // Advanced SG-enabled zone - var networkData = { - zoneId: selectedZoneObj.id, - type: 'Shared', - supportedServices: 'SecurityGroup' - }; - if (!(cloudStack.context.projects && cloudStack.context.projects[0])) { - networkData.domainid = g_domainid; - networkData.account = g_account; - } + + if(selectedZoneObj.networktype == "Advanced" && selectedZoneObj.securitygroupsenabled == true) { // Advanced SG-enabled zone + var array2 = []; + var myNetworks = $('.multi-wizard:visible form').data('my-networks'); //widget limitation: If using an advanced security group zone, get the guest networks like this + var defaultNetworkId = $('.multi-wizard:visible form').find('input[name=defaultNetwork]:checked').val(); + + var checkedNetworkIdArray; + if(typeof(myNetworks) == "object" && myNetworks.length != null) { //myNetworks is an array of string, e.g. ["203", "202"], + checkedNetworkIdArray = myNetworks; + } + else if(typeof(myNetworks) == "string" && myNetworks.length > 0) { //myNetworks is a string, e.g. "202" + checkedNetworkIdArray = []; + checkedNetworkIdArray.push(myNetworks); + } + else { // typeof(myNetworks) == null + checkedNetworkIdArray = []; + } - var selectedNetworkObj = null; - $.ajax({ - url: createURL('listNetworks'), - data: networkData, - async: false, - success: function(json) { - var networks = json.listnetworksresponse.network; - if(networks != null && networks.length > 0) { - selectedNetworkObj = networks[0]; //each Advanced SG-enabled zone has only one guest network that is Shared and has SecurityGroup service - } + //add default network first + if(defaultNetworkId != null && defaultNetworkId.length > 0 && defaultNetworkId != 'new-network') + array2.push(defaultNetworkId); + + //then, add other checked networks + if(checkedNetworkIdArray.length > 0) { + for(var i=0; i < checkedNetworkIdArray.length; i++) { + if(checkedNetworkIdArray[i] != defaultNetworkId) //exclude defaultNetworkId that has been added to array2 + array2.push(checkedNetworkIdArray[i]); } - }); - if(selectedNetworkObj != null) { - array1.push("&networkIds=" + selectedNetworkObj.id); } - else { - alert('unable to find any Shared network with SecurityGroup service. Therefore, unable to deploy VM in this Advanced SecurityGroup-enabled zone.'); - return; - } - } - */ - + + array1.push("&networkIds=" + array2.join(",")); + } } else if (step5ContainerType == 'nothing-to-select') { if(args.context.networks != null) { //from VPC tier From a5ac88db88837c6b123ae59491318c94a75d6ceb Mon Sep 17 00:00:00 2001 From: Sheng Yang Date: Fri, 18 Jan 2013 11:00:18 -0800 Subject: [PATCH 29/80] CLOUDSTACK-938: Add missing checkbatchs2svpn.sh --- .../config/opt/cloud/bin/checkbatchs2svpn.sh | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100755 patches/systemvm/debian/config/opt/cloud/bin/checkbatchs2svpn.sh 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..80e3213753b --- /dev/null +++ b/patches/systemvm/debian/config/opt/cloud/bin/checkbatchs2svpn.sh @@ -0,0 +1,25 @@ +#!/bin/bash +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +for i in $* +do + info=`/opt/cloud/bin/checks2svpn.sh $i` + ret=$? + echo -n "$i:$ret:$info&" +done + From e8c0c1a8ee27070d0062ac4ada71b55ff8488254 Mon Sep 17 00:00:00 2001 From: Min Chen Date: Fri, 18 Jan 2013 11:36:09 -0800 Subject: [PATCH 30/80] Avoid some m2e error in eclipse for imported project. --- pom.xml | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/pom.xml b/pom.xml index e09472f9869..35d6520ce6b 100644 --- a/pom.xml +++ b/pom.xml @@ -358,6 +358,36 @@ + + + org.eclipse.m2e + lifecycle-mapping + 1.0.0 + + + + + + + org.apache.maven.plugins + + + maven-antrun-plugin + + [1.7,) + + run + + + + + + + + + + From 2955d5897644a846755ceb9e7568eb65c6f9faa8 Mon Sep 17 00:00:00 2001 From: Min Chen Date: Fri, 18 Jan 2013 13:55:11 -0800 Subject: [PATCH 31/80] Fix "Count" for listSnapshotPoliciesCmd. --- .../storage/snapshot/SnapshotService.java | 2 +- .../snapshot/ListSnapshotPoliciesCmd.java | 7 +- .../cloud/storage/dao/SnapshotPolicyDao.java | 3 + .../storage/dao/SnapshotPolicyDaoImpl.java | 30 ++++-- .../storage/snapshot/SnapshotManagerImpl.java | 96 ++++++++++--------- 5 files changed, 79 insertions(+), 59 deletions(-) diff --git a/api/src/com/cloud/storage/snapshot/SnapshotService.java b/api/src/com/cloud/storage/snapshot/SnapshotService.java index 79041c47b69..18b85071668 100644 --- a/api/src/com/cloud/storage/snapshot/SnapshotService.java +++ b/api/src/com/cloud/storage/snapshot/SnapshotService.java @@ -82,7 +82,7 @@ public interface SnapshotService { * the command that specifies the volume criteria * @return list of snapshot policies */ - List listPoliciesforVolume(ListSnapshotPoliciesCmd cmd); + Pair, Integer> listPoliciesforVolume(ListSnapshotPoliciesCmd cmd); boolean deleteSnapshotPolicies(DeleteSnapshotPoliciesCmd cmd); diff --git a/api/src/org/apache/cloudstack/api/command/user/snapshot/ListSnapshotPoliciesCmd.java b/api/src/org/apache/cloudstack/api/command/user/snapshot/ListSnapshotPoliciesCmd.java index 647c503a445..7c78bb76dbf 100644 --- a/api/src/org/apache/cloudstack/api/command/user/snapshot/ListSnapshotPoliciesCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/snapshot/ListSnapshotPoliciesCmd.java @@ -29,6 +29,7 @@ import org.apache.cloudstack.api.response.ListResponse; import org.apache.cloudstack.api.response.SnapshotPolicyResponse; import org.apache.cloudstack.api.response.VolumeResponse; import com.cloud.storage.snapshot.SnapshotPolicy; +import com.cloud.utils.Pair; @APICommand(name = "listSnapshotPolicies", description="Lists snapshot policies.", responseObject=SnapshotPolicyResponse.class) public class ListSnapshotPoliciesCmd extends BaseListCmd { @@ -63,15 +64,15 @@ public class ListSnapshotPoliciesCmd extends BaseListCmd { @Override public void execute(){ - List result = _snapshotService.listPoliciesforVolume(this); + Pair, Integer> result = _snapshotService.listPoliciesforVolume(this); ListResponse response = new ListResponse(); List policyResponses = new ArrayList(); - for (SnapshotPolicy policy : result) { + for (SnapshotPolicy policy : result.first()) { SnapshotPolicyResponse policyResponse = _responseGenerator.createSnapshotPolicyResponse(policy); policyResponse.setObjectName("snapshotpolicy"); policyResponses.add(policyResponse); } - response.setResponses(policyResponses); + response.setResponses(policyResponses, result.second()); response.setResponseName(getCommandName()); this.setResponseObject(response); } diff --git a/server/src/com/cloud/storage/dao/SnapshotPolicyDao.java b/server/src/com/cloud/storage/dao/SnapshotPolicyDao.java index 9f8d170e797..467d491d779 100644 --- a/server/src/com/cloud/storage/dao/SnapshotPolicyDao.java +++ b/server/src/com/cloud/storage/dao/SnapshotPolicyDao.java @@ -20,6 +20,7 @@ import java.util.List; import com.cloud.storage.SnapshotPolicyVO; import com.cloud.utils.DateUtil.IntervalType; +import com.cloud.utils.Pair; import com.cloud.utils.db.Filter; import com.cloud.utils.db.GenericDao; @@ -29,6 +30,8 @@ import com.cloud.utils.db.GenericDao; public interface SnapshotPolicyDao extends GenericDao { List listByVolumeId(long volumeId); List listByVolumeId(long volumeId, Filter filter); + Pair, Integer> listAndCountByVolumeId(long volumeId); + Pair, Integer> listAndCountByVolumeId(long volumeId, Filter filter); SnapshotPolicyVO findOneByVolumeInterval(long volumeId, IntervalType intvType); List listActivePolicies(); SnapshotPolicyVO findOneByVolume(long volumeId); diff --git a/server/src/com/cloud/storage/dao/SnapshotPolicyDaoImpl.java b/server/src/com/cloud/storage/dao/SnapshotPolicyDaoImpl.java index 10eaaea7f41..100d53b996d 100644 --- a/server/src/com/cloud/storage/dao/SnapshotPolicyDaoImpl.java +++ b/server/src/com/cloud/storage/dao/SnapshotPolicyDaoImpl.java @@ -23,6 +23,7 @@ import javax.ejb.Local; import com.cloud.storage.SnapshotPolicyVO; import com.cloud.utils.DateUtil.IntervalType; +import com.cloud.utils.Pair; import com.cloud.utils.db.Filter; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.SearchBuilder; @@ -33,7 +34,7 @@ public class SnapshotPolicyDaoImpl extends GenericDaoBase VolumeIdSearch; private final SearchBuilder VolumeIdIntervalSearch; private final SearchBuilder ActivePolicySearch; - + @Override public SnapshotPolicyVO findOneByVolumeInterval(long volumeId, IntervalType intvType) { SearchCriteria sc = VolumeIdIntervalSearch.create(); @@ -41,7 +42,7 @@ public class SnapshotPolicyDaoImpl extends GenericDaoBase sc = VolumeIdSearch.create(); @@ -49,12 +50,12 @@ public class SnapshotPolicyDaoImpl extends GenericDaoBase listByVolumeId(long volumeId) { return listByVolumeId(volumeId, null); } - + @Override public List listByVolumeId(long volumeId, Filter filter) { SearchCriteria sc = VolumeIdSearch.create(); @@ -62,18 +63,31 @@ public class SnapshotPolicyDaoImpl extends GenericDaoBase, Integer> listAndCountByVolumeId(long volumeId) { + return listAndCountByVolumeId(volumeId, null); + } + + @Override + public Pair, Integer> listAndCountByVolumeId(long volumeId, Filter filter) { + SearchCriteria sc = VolumeIdSearch.create(); + sc.setParameters("volumeId", volumeId); + sc.setParameters("active", true); + return searchAndCount(sc, filter); + } + protected SnapshotPolicyDaoImpl() { VolumeIdSearch = createSearchBuilder(); VolumeIdSearch.and("volumeId", VolumeIdSearch.entity().getVolumeId(), SearchCriteria.Op.EQ); VolumeIdSearch.and("active", VolumeIdSearch.entity().isActive(), SearchCriteria.Op.EQ); VolumeIdSearch.done(); - + VolumeIdIntervalSearch = createSearchBuilder(); VolumeIdIntervalSearch.and("volumeId", VolumeIdIntervalSearch.entity().getVolumeId(), SearchCriteria.Op.EQ); VolumeIdIntervalSearch.and("interval", VolumeIdIntervalSearch.entity().getInterval(), SearchCriteria.Op.EQ); VolumeIdIntervalSearch.done(); - + ActivePolicySearch = createSearchBuilder(); ActivePolicySearch.and("active", ActivePolicySearch.entity().isActive(), SearchCriteria.Op.EQ); ActivePolicySearch.done(); @@ -84,5 +98,5 @@ public class SnapshotPolicyDaoImpl extends GenericDaoBase sc = ActivePolicySearch.create(); sc.setParameters("active", true); return listIncludingRemovedBy(sc); - } + } } \ No newline at end of file diff --git a/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java b/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java index 6a0f71d1f6f..15d8c53d06f 100755 --- a/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java +++ b/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java @@ -69,6 +69,7 @@ import com.cloud.exception.StorageUnavailableException; import com.cloud.host.HostVO; import com.cloud.host.dao.HostDao; import com.cloud.hypervisor.Hypervisor.HypervisorType; +import com.cloud.network.PhysicalNetworkTrafficType; import com.cloud.org.Grouping; import com.cloud.projects.Project.ListProjectResourcesCriteria; import com.cloud.resource.ResourceManager; @@ -177,7 +178,7 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma private SwiftManager _swiftMgr; @Inject private S3Manager _s3Mgr; - @Inject + @Inject private SecondaryStorageVmManager _ssvmMgr; @Inject private ResourceManager _resourceMgr; @@ -187,7 +188,7 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma private VolumeDao _volumeDao; @Inject private ResourceTagDao _resourceTagDao; - + String _name; private int _totalRetries; private int _pauseInterval; @@ -197,15 +198,15 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma protected SearchBuilder PolicySnapshotSearch; protected SearchBuilder PoliciesForSnapSearch; - - + + protected Answer sendToPool(Volume vol, Command cmd) { StoragePool pool = _storagePoolDao.findById(vol.getPoolId()); - + long[] hostIdsToTryFirst = null; - + Long vmHostId = getHostIdForSnapshotOperation(vol); - + if (vmHostId != null) { hostIdsToTryFirst = new long[] { vmHostId }; } @@ -280,7 +281,7 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma } ManageSnapshotCommand cmd = new ManageSnapshotCommand(snapshotId, volume.getPath(), srcPool, preSnapshotPath, snapshot.getName(), vmName); - + ManageSnapshotAnswer answer = (ManageSnapshotAnswer) sendToPool(volume, cmd); // Update the snapshot in the database if ((answer != null) && answer.getResult()) { @@ -298,7 +299,7 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma _snapshotDao.update(snapshotId, snapshot); } else { long preSnapshotId = 0; - + if (preSnapshotVO != null && preSnapshotVO.getBackupSnapshotId() != null) { preSnapshotId = preId; // default delta snap number is 16 @@ -322,7 +323,7 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma preSnapshotId = 0; } } - + //If the volume is moved around, backup a full snapshot to secondary storage if (volume.getLastPoolId() != null && !volume.getLastPoolId().equals(volume.getPoolId())) { preSnapshotId = 0; @@ -359,24 +360,24 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma @DB @ActionEvent(eventType = EventTypes.EVENT_SNAPSHOT_CREATE, eventDescription = "creating snapshot", async = true) public SnapshotVO createSnapshot(Long volumeId, Long policyId, Long snapshotId, Account snapshotOwner) { - VolumeVO volume = _volsDao.findById(volumeId); + VolumeVO volume = _volsDao.findById(volumeId); if (volume == null) { throw new InvalidParameterValueException("No such volume exist"); } - + if (volume.getState() != Volume.State.Ready) { throw new InvalidParameterValueException("Volume is not in ready state"); } - + SnapshotVO snapshot = null; - + boolean backedUp = false; UserVmVO uservm = null; // does the caller have the authority to act on this volume _accountMgr.checkAccess(UserContext.current().getCaller(), null, true, volume); - + try { - + Long poolId = volume.getPoolId(); if (poolId == null) { throw new CloudRuntimeException("You cannot take a snapshot of a volume until it has been attached to an instance"); @@ -387,7 +388,7 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma if (uservm != null && uservm.getType() != VirtualMachine.Type.User) { throw new CloudRuntimeException("Can't take a snapshot on system vm "); } - + StoragePoolVO storagePool = _storagePoolDao.findById(volume.getPoolId()); ClusterVO cluster = _clusterDao.findById(storagePool.getClusterId()); List hosts = _resourceMgr.listAllHostsInCluster(cluster.getId()); @@ -407,7 +408,7 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma throw new CloudRuntimeException("Creating snapshot failed due to volume:" + volumeId + " is associated with vm:" + userVm.getInstanceName() + " is in " + userVm.getState().toString() + " state"); } - + if(userVm.getHypervisorType() == HypervisorType.VMware || userVm.getHypervisorType() == HypervisorType.KVM) { List activeSnapshots = _snapshotDao.listByInstanceId(volume.getInstanceId(), Snapshot.Status.Creating, Snapshot.Status.CreatedOnPrimary, Snapshot.Status.BackingUp); if(activeSnapshots.size() > 1) @@ -560,7 +561,7 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma } catch (Exception e) { throw new CloudRuntimeException("downloadSnapshotsFromSwift failed due to " + e.toString()); } - + } private List determineBackupUuids(final SnapshotVO snapshot) { @@ -630,9 +631,9 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma Long dcId = volume.getDataCenterId(); Long accountId = volume.getAccountId(); - + HostVO secHost = getSecHost(volumeId, volume.getDataCenterId()); - + String secondaryStoragePoolUrl = secHost.getStorageUrl(); String snapshotUuid = snapshot.getPath(); // In order to verify that the snapshot is not empty, @@ -647,12 +648,12 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma S3TO s3 = _s3Mgr.getS3TO(); checkObjectStorageConfiguration(swift, s3); - + long prevSnapshotId = snapshot.getPrevSnapshotId(); if (prevSnapshotId > 0) { prevSnapshot = _snapshotDao.findByIdIncludingRemoved(prevSnapshotId); if ( prevSnapshot.getBackupSnapshotId() != null && swift == null) { - if (prevSnapshot.getVersion() != null && prevSnapshot.getVersion().equals("2.2")) { + if (prevSnapshot.getVersion() != null && prevSnapshot.getVersion().equals("2.2")) { prevBackupUuid = prevSnapshot.getBackupSnapshotId(); prevSnapshotUuid = prevSnapshot.getPath(); } @@ -724,7 +725,7 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma private HostVO getSecHost(long volumeId, long dcId) { Long id = _snapshotDao.getSecHostId(volumeId); - if ( id != null) { + if ( id != null) { return _hostDao.findById(id); } return _storageMgr.getSecondaryStorageHost(dcId); @@ -743,7 +744,7 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma public void postCreateSnapshot(Long volumeId, Long snapshotId, Long policyId, boolean backedUp) { Long userId = getSnapshotUserId(); SnapshotVO snapshot = _snapshotDao.findById(snapshotId); - + if (snapshot != null && snapshot.isRecursive()) { postCreateRecurringSnapshotForPolicy(userId, volumeId, snapshotId, policyId); } @@ -783,13 +784,13 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma if (snapshotCheck == null) { throw new InvalidParameterValueException("unable to find a snapshot with id " + snapshotId); } - + _accountMgr.checkAccess(caller, null, true, snapshotCheck); - + if( !Status.BackedUp.equals(snapshotCheck.getStatus() ) ) { throw new InvalidParameterValueException("Can't delete snapshotshot " + snapshotId + " due to it is not in BackedUp Status"); } - + return deleteSnapshotInternal(snapshotId); } @@ -943,7 +944,7 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma String snapshotTypeStr = cmd.getSnapshotType(); String intervalTypeStr = cmd.getIntervalType(); Map tags = cmd.getTags(); - + Account caller = UserContext.current().getCaller(); List permittedAccounts = new ArrayList(); @@ -959,8 +960,8 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), false); Long domainId = domainIdRecursiveListProject.first(); Boolean isRecursive = domainIdRecursiveListProject.second(); - ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); - + ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); + Filter searchFilter = new Filter(SnapshotVO.class, "created", false, cmd.getStartIndex(), cmd.getPageSizeVal()); SearchBuilder sb = _snapshotDao.createSearchBuilder(); _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); @@ -971,7 +972,7 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); sb.and("snapshotTypeEQ", sb.entity().getsnapshotType(), SearchCriteria.Op.IN); sb.and("snapshotTypeNEQ", sb.entity().getsnapshotType(), SearchCriteria.Op.NEQ); - + if (tags != null && !tags.isEmpty()) { SearchBuilder tagSearch = _resourceTagDao.createSearchBuilder(); for (int count=0; count < tags.size(); count++) { @@ -990,7 +991,7 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma if (volumeId != null) { sc.setParameters("volumeId", volumeId); } - + if (tags != null && !tags.isEmpty()) { int count = 0; sc.setJoinParameters("tagSearch", "resourceType", TaggedResourceType.Snapshot.toString()); @@ -1133,9 +1134,9 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma if (volume == null) { throw new InvalidParameterValueException("Failed to create snapshot policy, unable to find a volume with id " + volumeId); } - + _accountMgr.checkAccess(UserContext.current().getCaller(), null, true, volume); - + if (volume.getState() != Volume.State.Ready) { throw new InvalidParameterValueException("VolumeId: " + volumeId + " is not in " + Volume.State.Ready + " state but " + volume.getState() + ". Cannot take snapshot."); } @@ -1191,7 +1192,7 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma if (owner.getType() == Account.ACCOUNT_TYPE_PROJECT) { message = "domain/project"; } - + throw new InvalidParameterValueException("Max number of snapshots shouldn't exceed the " + message + " level snapshot limit"); } @@ -1227,14 +1228,15 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma } @Override - public List listPoliciesforVolume(ListSnapshotPoliciesCmd cmd) { + public Pair, Integer> listPoliciesforVolume(ListSnapshotPoliciesCmd cmd) { Long volumeId = cmd.getVolumeId(); VolumeVO volume = _volsDao.findById(volumeId); if (volume == null) { throw new InvalidParameterValueException("Unable to find a volume with id " + volumeId); } _accountMgr.checkAccess(UserContext.current().getCaller(), null, true, volume); - return listPoliciesforVolume(cmd.getVolumeId()); + Pair, Integer> result = _snapshotPolicyDao.listAndCountByVolumeId(volumeId); + return new Pair, Integer>(result.first(), result.second()); } @Override @@ -1352,7 +1354,7 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma @Override public SnapshotVO allocSnapshot(Long volumeId, Long policyId) throws ResourceAllocationException { Account caller = UserContext.current().getCaller(); - + VolumeVO volume = _volsDao.findById(volumeId); if (volume == null) { throw new InvalidParameterValueException("Creating snapshot failed due to volume:" + volumeId + " doesn't exist"); @@ -1361,11 +1363,11 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma if (zone == null) { throw new InvalidParameterValueException("Can't find zone by id " + volume.getDataCenterId()); } - + if (Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getType())) { throw new PermissionDeniedException("Cannot perform this operation, Zone is currently disabled: " + zone.getName()); } - + if (volume.getState() != Volume.State.Ready) { throw new InvalidParameterValueException("VolumeId: " + volumeId + " is not in " + Volume.State.Ready + " state but " + volume.getState() + ". Cannot take snapshot."); } @@ -1376,7 +1378,7 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma throw new InvalidParameterValueException("VolumeId: " + volumeId + " is for System VM , Creating snapshot against System VM volumes is not supported"); } } - + StoragePoolVO storagePoolVO = _storagePoolDao.findById(volume.getPoolId()); if (storagePoolVO == null) { throw new InvalidParameterValueException("VolumeId: " + volumeId + " please attach this volume to a VM before create snapshot for it"); @@ -1386,7 +1388,7 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma if (cluster != null && cluster.getHypervisorType() == HypervisorType.Ovm) { throw new InvalidParameterValueException("Ovm won't support taking snapshot"); } - + // Verify permissions _accountMgr.checkAccess(caller, null, true, volume); Type snapshotType = getSnapshotType(policyId); @@ -1397,7 +1399,7 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma if (snapshotType != Type.MANUAL){ String msg = "Snapshot resource limit exceeded for account id : " + owner.getId() + ". Failed to create recurring snapshots"; s_logger.warn(msg); - _alertMgr.sendAlert(AlertManager.ALERT_TYPE_UPDATE_RESOURCE_COUNT, 0L, 0L, msg, + _alertMgr.sendAlert(AlertManager.ALERT_TYPE_UPDATE_RESOURCE_COUNT, 0L, 0L, msg, "Snapshot resource limit exceeded for account id : " + owner.getId() + ". Failed to create recurring snapshots; please use updateResourceLimit to increase the limit"); } throw e; @@ -1415,7 +1417,7 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma String snapshotName = vmDisplayName + "_" + volume.getName() + "_" + timeString; // Create the Snapshot object and save it so we can return it to the - // user + // user HypervisorType hypervisorType = this._volsDao.getHypervisorType(volumeId); SnapshotVO snapshotVO = new SnapshotVO(volume.getDataCenterId(), volume.getAccountId(), volume.getDomainId(), volume.getId(), volume.getDiskOfferingId(), null, snapshotName, (short) snapshotType.ordinal(), snapshotType.name(), volume.getSize(), hypervisorType); @@ -1436,7 +1438,7 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma if (configDao == null) { throw new ConfigurationException("Unable to get the configuration dao."); } - + String value = configDao.getValue(Config.BackupSnapshotWait.toString()); _backupsnapshotwait = NumbersUtil.parseInt(value, Integer.parseInt(Config.BackupSnapshotWait.getDefaultValue())); @@ -1533,7 +1535,7 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma } return false; } - + @Override public boolean canOperateOnVolume(VolumeVO volume) { List snapshots = _snapshotDao.listByStatus(volume.getId(), Status.Creating, Status.CreatedOnPrimary, Status.BackingUp); From 189c20b6653498a8ee8c2e398c5f2e44ab4b840a Mon Sep 17 00:00:00 2001 From: Edison Su Date: Fri, 18 Jan 2013 14:22:53 -0800 Subject: [PATCH 32/80] umount loop device. If patch disk created from loop, then need to umount it in loop device, otherwise, you can only create 7 routers on one kvm host --- scripts/vm/hypervisor/kvm/rundomrpre.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/vm/hypervisor/kvm/rundomrpre.sh b/scripts/vm/hypervisor/kvm/rundomrpre.sh index f3019dc2d0a..dc783749815 100755 --- a/scripts/vm/hypervisor/kvm/rundomrpre.sh +++ b/scripts/vm/hypervisor/kvm/rundomrpre.sh @@ -71,7 +71,7 @@ umount_raw_disk() { sync while [ $retry -gt 0 ] do - umount $path &>/dev/null + umount -d $path &>/dev/null if [ $? -gt 0 ] then sleep 5 From d13d67bdd9b6424d5fde8861a383c45c06314e2c Mon Sep 17 00:00:00 2001 From: Jessica Wang Date: Fri, 18 Jan 2013 15:03:07 -0800 Subject: [PATCH 33/80] CLOUDSTACK-459: cloudstack UI - create network offering dialog - update comment in code. --- ui/scripts/configuration.js | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/ui/scripts/configuration.js b/ui/scripts/configuration.js index dc5f8f004c3..30c850ffe06 100644 --- a/ui/scripts/configuration.js +++ b/ui/scripts/configuration.js @@ -1293,11 +1293,11 @@ } } //hide/show service fields ***** (end) ***** - - - //show LB InlineMode dropdown only when (1)LB Service is checked (2)Service Provider is F5 - if((args.$form.find('.form-item[rel=\"service.Lb.isEnabled\"]').find('input[type=checkbox]').is(':checked') == true) - &&(args.$form.find('.form-item[rel=\"service.Lb.provider\"]').find('select').val() == 'F5BigIp') && ( args.$form.find('.form-item[rel=\"service.Firewall.isEnabled\"]').find('input[type=checkbox]').is(':checked') == true) && (args.$form.find('.form-item[rel=\"service.Firewall.provider\"]').find('select').val() == 'JuniperSRX')) { + + //show LB InlineMode dropdown only when (1)LB service is checked and LB service provider is F5BigIp (2)Firewall service is checked and Firewall service provider is JuniperSRX + if((args.$form.find('.form-item[rel=\"service.Lb.isEnabled\"]').find('input[type=checkbox]').is(':checked') == true) && (args.$form.find('.form-item[rel=\"service.Lb.provider\"]').find('select').val() == 'F5BigIp') && + (args.$form.find('.form-item[rel=\"service.Firewall.isEnabled\"]').find('input[type=checkbox]').is(':checked') == true) && (args.$form.find('.form-item[rel=\"service.Firewall.provider\"]').find('select').val() == 'JuniperSRX')) + { args.$form.find('.form-item[rel=\"service.Lb.inlineModeDropdown\"]').css('display', 'inline-block'); } else { From 98a289020faab3b6e8825aeb7d924c6493c66548 Mon Sep 17 00:00:00 2001 From: Jessica Wang Date: Fri, 18 Jan 2013 16:03:33 -0800 Subject: [PATCH 34/80] CLOUDSTACK-652: cloudstack UI - create network offering dialog - for both Isolated network and Shared network, show Elastic IP dropdown when StaticNAT is checked and StaticNAT provider is Netscaler. --- ui/scripts/configuration.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ui/scripts/configuration.js b/ui/scripts/configuration.js index 30c850ffe06..0fbea2d7335 100644 --- a/ui/scripts/configuration.js +++ b/ui/scripts/configuration.js @@ -1325,10 +1325,10 @@ args.$form.find('.form-item[rel=\"service.Lb.elasticLbCheckbox\"]').find('input[type=checkbox]').attr('checked', false); } - //show Elastic IP checkbox only when (1)StaticNat Service is checked (2)Service Provider is Netscaler (3)Guest IP Type is Shared + //show Elastic IP checkbox only when (1)StaticNat service is checked (2)StaticNat service provider is Netscaler if((args.$form.find('.form-item[rel=\"service.StaticNat.isEnabled\"]').find('input[type=checkbox]').is(':checked') == true) &&(args.$form.find('.form-item[rel=\"service.StaticNat.provider\"]').find('select').val() == 'Netscaler') - &&(args.$form.find('.form-item[rel=\"guestIpType\"]').find('select').val() == 'Shared')) { + ) { args.$form.find('.form-item[rel=\"service.StaticNat.elasticIpCheckbox\"]').css('display', 'inline-block'); } else { From a65b584d188002caaf9c60914c02fba8ef1bda7c Mon Sep 17 00:00:00 2001 From: Marcus Sorensen Date: Fri, 18 Jan 2013 18:28:08 -0700 Subject: [PATCH 35/80] Summary: Fix bridge parsing when bridge names are subsets of others Detail: There are several places in the code that do a "brctl show | grep bridgeName" or similar, which causes all sorts of problems when you have for example a cloudVirBr50 and a cloudVirBr5000. This patch attempts to stop relying on the output of brctl, instead favoring sysfs and /sys/devices/virtual/net. It cuts a lot of bash out altogether by using java File. It was tested in my devcloud-kvm against current 4.0, as well as by the customer reporting initial bug. BUG-ID: CLOUDSTACK-938 Fix-For: 4.0.1 Signed-off-by: Marcus Sorensen --- .../kvm/resource/BridgeVifDriver.java | 13 ++- .../resource/LibvirtComputingResource.java | 82 +++++++++++++------ 2 files changed, 62 insertions(+), 33 deletions(-) diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/BridgeVifDriver.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/BridgeVifDriver.java index e6f2f7f376a..51849f123ed 100644 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/BridgeVifDriver.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/BridgeVifDriver.java @@ -33,6 +33,7 @@ import org.libvirt.LibvirtException; import javax.naming.ConfigurationException; import java.net.URI; import java.util.Map; +import java.io.File; public class BridgeVifDriver extends VifDriverBase { @@ -206,15 +207,11 @@ public class BridgeVifDriver extends VifDriverBase { } private boolean isBridgeExists(String bridgeName) { - Script command = new Script("/bin/sh", _timeout); - command.add("-c"); - command.add("brctl show|grep " + bridgeName); - final OutputInterpreter.OneLineParser parser = new OutputInterpreter.OneLineParser(); - String result = command.execute(parser); - if (result != null || parser.getLine() == null) { - return false; - } else { + File f = new File("/sys/devices/virtual/net/" + bridgeName); + if (f.exists()) { return true; + } else { + return false; } } } diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java index eac60f4df41..a269e8ab732 100755 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java @@ -788,10 +788,19 @@ public class LibvirtComputingResource extends ServerResourceBase implements } private void getPifs() { - /* gather all available bridges and find their pifs, so that we can match them against traffic labels later */ - String cmdout = Script.runSimpleBashScript("brctl show | tail -n +2 | grep -v \"^\\s\"|awk '{print $1}'|sed '{:q;N;s/\\n/%/g;t q}'"); - s_logger.debug("cmdout was " + cmdout); - List bridges = Arrays.asList(cmdout.split("%")); + File dir = new File("/sys/devices/virtual/net"); + File[] netdevs = dir.listFiles(); + List bridges = new ArrayList(); + for (int i = 0; i < netdevs.length; i++) { + File isbridge = new File(netdevs[i].getAbsolutePath() + "/bridge"); + String netdevName = netdevs[i].getName(); + s_logger.debug("looking in file " + netdevs[i].getAbsolutePath() + "/bridge"); + if (isbridge.exists()) { + s_logger.debug("Found bridge " + netdevName); + bridges.add(netdevName); + } + } + for (String bridge : bridges) { s_logger.debug("looking for pif for bridge " + bridge); String pif = getPif(bridge); @@ -807,24 +816,53 @@ public class LibvirtComputingResource extends ServerResourceBase implements } private String getPif(String bridge) { - String pif = Script.runSimpleBashScript("brctl show | grep " + bridge + " | awk '{print $4}'"); - String vlan = Script.runSimpleBashScript("ls /proc/net/vlan/" + pif); + String pif = matchPifFileInDirectory(bridge); + File vlanfile = new File("/proc/net/vlan" + pif); - if (vlan != null && !vlan.isEmpty()) { - pif = Script.runSimpleBashScript("grep ^Device\\: /proc/net/vlan/" + pif + " | awk {'print $2'}"); + if (vlanfile.isFile()) { + pif = Script.runSimpleBashScript("grep ^Device\\: /proc/net/vlan/" + + pif + " | awk {'print $2'}"); } return pif; } + private String matchPifFileInDirectory(String bridgeName){ + File f = new File("/sys/devices/virtual/net/" + bridgeName + "/brif"); + + if (! f.isDirectory()){ + s_logger.debug("failing to get physical interface from bridge" + + bridgeName + ", does " + f.getAbsolutePath() + + "exist?"); + return ""; + } + + File[] interfaces = f.listFiles(); + + for (int i = 0; i < interfaces.length; i++) { + String fname = interfaces[i].getName(); + s_logger.debug("matchPifFileInDirectory: file name '"+fname+"'"); + if (fname.startsWith("eth") || fname.startsWith("bond") + || fname.startsWith("vlan")) { + return fname; + } + } + + s_logger.debug("failing to get physical interface from bridge" + + bridgeName + ", did not find an eth*, bond*, or vlan* in " + + f.getAbsolutePath()); + return ""; + } + + private boolean checkNetwork(String networkName) { if (networkName == null) { return true; } - String name = Script.runSimpleBashScript("brctl show | grep " - + networkName + " | awk '{print $4}'"); - if (name == null) { + String name = matchPifFileInDirectory(networkName); + + if (name == null || name.isEmpty()) { return false; } else { return true; @@ -1381,20 +1419,15 @@ public class LibvirtComputingResource extends ServerResourceBase implements } private String getVlanIdFromBridge(String brName) { - OutputInterpreter.OneLineParser vlanIdParser = new OutputInterpreter.OneLineParser(); - final Script cmd = new Script("/bin/bash", s_logger); - cmd.add("-c"); - cmd.add("vlanid=$(brctl show |grep " + brName - + " |awk '{print $4}' | cut -s -d. -f 2);echo $vlanid"); - String result = cmd.execute(vlanIdParser); - if (result != null) { - return null; - } - String vlanId = vlanIdParser.getLine(); - if (vlanId.equalsIgnoreCase("")) { - return null; + String pif= matchPifFileInDirectory(brName); + String[] pifparts = pif.split("\\."); + + if(pifparts.length == 2) { + return pifparts[1]; } else { - return vlanId; + s_logger.debug("failed to get vlan id from bridge " + brName + + "attached to physical interface" + pif); + return ""; } } @@ -1632,7 +1665,6 @@ public class LibvirtComputingResource extends ServerResourceBase implements } for (IpAddressTO ip : ips) { - String ipVlan = ip.getVlanId(); String nicName = "eth" + vlanToNicNum.get(ip.getVlanId()); String netmask = Long.toString(NetUtils.getCidrSize(ip.getVlanNetmask())); String subnet = NetUtils.getSubNet(ip.getPublicIp(), ip.getVlanNetmask()); From 04d93ef0aafcbea363f23d365a33a1ce4efeacd4 Mon Sep 17 00:00:00 2001 From: Hugo Trippaers Date: Mon, 21 Jan 2013 11:56:53 +0100 Subject: [PATCH 36/80] Use the user.home property instead of a bash thing. See http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html --- server/src/com/cloud/server/ConfigurationServerImpl.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/server/src/com/cloud/server/ConfigurationServerImpl.java b/server/src/com/cloud/server/ConfigurationServerImpl.java index 74fba896753..b0abd043371 100755 --- a/server/src/com/cloud/server/ConfigurationServerImpl.java +++ b/server/src/com/cloud/server/ConfigurationServerImpl.java @@ -553,8 +553,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { return; } String already = _configDao.getValue("ssh.privatekey"); - String homeDir = null; - homeDir = Script.runSimpleBashScript("echo ~" + username); + String homeDir = System.getProperty("user.home"); if (homeDir == null) { throw new CloudRuntimeException("Cannot get home directory for account: " + username); } From a8fcc4f3d3252291943f016f6f1674d80f96eef6 Mon Sep 17 00:00:00 2001 From: Hugo Trippaers Date: Tue, 15 Jan 2013 17:53:40 +0100 Subject: [PATCH 37/80] Summary: Add documentation for the KVM support for OpenVswitch Modified the KVM installation instructions with an example on how to use the openvswitch bridges. Modified the Nicira NVP plugin documentation with support for KVM Updated the Nicira NVP docs to mention that it can be configured using the UI now. --- docs/en-US/host-add-xenserver-kvm-ovm.xml | 5 + ...visor-host-install-network-openvswitch.xml | 116 ++++++++++++++++++ .../en-US/hypervisor-host-install-network.xml | 3 +- docs/en-US/hypervisor-kvm-install-flow.xml | 3 +- docs/en-US/hypervisor-kvm-requirements.xml | 7 +- docs/en-US/plugin-niciranvp-features.xml | 8 +- docs/en-US/plugin-niciranvp-preparations.xml | 4 +- docs/en-US/plugin-niciranvp-ui.xml | 26 ++++ docs/en-US/plugin-niciranvp-usage.xml | 1 + 9 files changed, 167 insertions(+), 6 deletions(-) create mode 100644 docs/en-US/hypervisor-host-install-network-openvswitch.xml create mode 100644 docs/en-US/plugin-niciranvp-ui.xml diff --git a/docs/en-US/host-add-xenserver-kvm-ovm.xml b/docs/en-US/host-add-xenserver-kvm-ovm.xml index 4bbeefcbed4..1f13e72d4c3 100644 --- a/docs/en-US/host-add-xenserver-kvm-ovm.xml +++ b/docs/en-US/host-add-xenserver-kvm-ovm.xml @@ -83,6 +83,11 @@ Make sure the new host has the same network configuration (guest, private, and public network) as other hosts in the cluster. + + If you are using OpenVswitch bridges edit the file agent.properties on the KVM host + and set the parameter network.bridge.type to + openvswitch before adding the host to &PRODUCT; + + +
+ Configure the network using OpenVswitch + This is a very important section, please make sure you read this thoroughly. + In order to forward traffic to your instances you will need at least two bridges: public and private. + By default these bridges are called cloudbr0 and cloudbr1, but you do have to make sure they are available on each hypervisor. + The most important factor is that you keep the configuration consistent on all your hypervisors. +
+ Preparing + To make sure that the native bridge module will not interfere with openvswitch the bridge module should be added to the blacklist. See the modprobe documentation for your distribution on where to find the blacklist. Make sure the module is not loaded either by rebooting or executing rmmod bridge before executing next steps. + The network configurations below depend on the ifup-ovs and ifdown-ovs scripts which are part of the openvswitch installation. They should be installed in /etc/sysconfig/network-scripts/ +
+
+ Network example + There are many ways to configure your network. In the Basic networking mode you should have two (V)LAN's, one for your private network and one for the public network. + We assume that the hypervisor has one NIC (eth0) with three tagged VLAN's: + + VLAN 100 for management of the hypervisor + VLAN 200 for public network of the instances (cloudbr0) + VLAN 300 for private network of the instances (cloudbr1) + + On VLAN 100 we give the Hypervisor the IP-Address 192.168.42.11/24 with the gateway 192.168.42.1 + The Hypervisor and Management server don't have to be in the same subnet! +
+
+ Configuring the network bridges + It depends on the distribution you are using how to configure these, below you'll find + examples for RHEL/CentOS. + The goal is to have three bridges called 'mgmt0', 'cloudbr0' and 'cloudbr1' after this + section. This should be used as a guideline only. The exact configuration will + depend on your network layout. +
+ Configure OpenVswitch + The network interfaces using OpenVswitch are created using the ovs-vsctl command. This command will configure the interfaces and persist them to the OpenVswitch database. + First we create a main bridge connected to the eth0 interface. Next we create three fake bridges, each connected to a specific vlan tag. + +
+
+ Configure in RHEL or CentOS + The required packages were installed when openvswitch and libvirt were installed, + we can proceed to configuring the network. + First we configure eth0 + vi /etc/sysconfig/network-scripts/ifcfg-eth0 + Make sure it looks similair to: + + We have to configure the base bridge with the trunk. + vi /etc/sysconfig/network-scripts/ifcfg-cloudbr + + We now have to configure the three VLAN bridges: + vi /etc/sysconfig/network-scripts/ifcfg-mgmt0 + + vi /etc/sysconfig/network-scripts/ifcfg-cloudbr0 + + vi /etc/sysconfig/network-scripts/ifcfg-cloudbr1 + + With this configuration you should be able to restart the network, although a reboot is recommended to see if everything works properly. + Make sure you have an alternative way like IPMI or ILO to reach the machine in case you made a configuration error and the network stops functioning! +
+
+
diff --git a/docs/en-US/hypervisor-host-install-network.xml b/docs/en-US/hypervisor-host-install-network.xml index 8f6a10cdd69..3a6dfac48bd 100644 --- a/docs/en-US/hypervisor-host-install-network.xml +++ b/docs/en-US/hypervisor-host-install-network.xml @@ -25,6 +25,7 @@
Configure the network bridges This is a very important section, please make sure you read this thoroughly. + This section details how to configure bridges using the native implementation in Linux. Please refer to the next section if you intend to use OpenVswitch In order to forward traffic to your instances you will need at least two bridges: public and private. By default these bridges are called cloudbr0 and cloudbr1, but you do have to make sure they are available on each hypervisor. The most important factor is that you keep the configuration consistent on all your hypervisors. @@ -146,4 +147,4 @@ iface cloudbr1 inet manual Make sure you have an alternative way like IPMI or ILO to reach the machine in case you made a configuration error and the network stops functioning!
- \ No newline at end of file + diff --git a/docs/en-US/hypervisor-kvm-install-flow.xml b/docs/en-US/hypervisor-kvm-install-flow.xml index 76e03ef7919..6cc73e4fdfa 100644 --- a/docs/en-US/hypervisor-kvm-install-flow.xml +++ b/docs/en-US/hypervisor-kvm-install-flow.xml @@ -1,5 +1,5 @@ - %BOOK_ENTITIES; ]> @@ -31,6 +31,7 @@ + diff --git a/docs/en-US/hypervisor-kvm-requirements.xml b/docs/en-US/hypervisor-kvm-requirements.xml index c42db86a2b8..cdfc808e490 100644 --- a/docs/en-US/hypervisor-kvm-requirements.xml +++ b/docs/en-US/hypervisor-kvm-requirements.xml @@ -1,5 +1,5 @@ - %BOOK_ENTITIES; ]> @@ -35,6 +35,11 @@ libvirt: 0.9.4 or higher Qemu/KVM: 1.0 or higher + The default bridge in &PRODUCT; is the Linux native bridge implementation (bridge module). &PRODUCT; includes an option to work with OpenVswitch, the requirements are listed below + + libvirt: 0.9.11 or higher + openvswitch: 1.7.1 or higher + In addition, the following hardware requirements apply: Within a single cluster, the hosts must be of the same distribution version. diff --git a/docs/en-US/plugin-niciranvp-features.xml b/docs/en-US/plugin-niciranvp-features.xml index b67323d56d2..b71e67f4199 100644 --- a/docs/en-US/plugin-niciranvp-features.xml +++ b/docs/en-US/plugin-niciranvp-features.xml @@ -24,6 +24,10 @@ Features of the Nicira NVP Plugin In CloudStack release 4.0.0-incubating this plugin supports the Connectivity service. This service is responsible for creating Layer 2 networks supporting the networks created by Guests. In other words when an tennant creates a new network, instead of the traditional VLAN a logical network will be created by sending the appropriate calls to the Nicira NVP Controller. The plugin has been tested with Nicira NVP versions 2.1.0, 2.2.0 and 2.2.1 - In CloudStack 4.0.0-incubating only the XenServer hypervisor is supported for use in combination with Nicira NVP - In CloudStack 4.0.0-incubating the UI components for this plugin are not complete, configuration is done by sending commands to the API + In CloudStack 4.0.0-incubating only the XenServer hypervisor is supported for use in + combination with Nicira NVP. + In CloudStack 4.1.0-incubating both KVM and XenServer hypervisors are + supported. + In CloudStack 4.0.0-incubating the UI components for this plugin are not complete, + configuration is done by sending commands to the API. diff --git a/docs/en-US/plugin-niciranvp-preparations.xml b/docs/en-US/plugin-niciranvp-preparations.xml index 95a25bdca26..86b795ccd0b 100644 --- a/docs/en-US/plugin-niciranvp-preparations.xml +++ b/docs/en-US/plugin-niciranvp-preparations.xml @@ -24,7 +24,9 @@ Prerequisites Before enabling the Nicira NVP plugin the NVP Controller needs to be configured. Please review the NVP User Guide on how to do that. CloudStack needs to have at least one physical network with the isolation method set to "STT". This network should be enabled for the Guest traffic type. - The Guest traffic type should be configured with the traffic label that matches the name of the Integration Bridge on XenServer. See the Nicira NVP User Guide for more details on how to set this up in XenServer. + The Guest traffic type should be configured with the traffic label that matches the name of + the Integration Bridge on the hypervisor. See the Nicira NVP User Guide for more details + on how to set this up in XenServer or KVM. Make sure you have the following information ready: The IP address of the NVP Controller diff --git a/docs/en-US/plugin-niciranvp-ui.xml b/docs/en-US/plugin-niciranvp-ui.xml new file mode 100644 index 00000000000..8b1bbad8395 --- /dev/null +++ b/docs/en-US/plugin-niciranvp-ui.xml @@ -0,0 +1,26 @@ + + +%BOOK_ENTITIES; + +%xinclude; +]> + +
+ Configuring the Nicira NVP plugin from the UI + In CloudStack 4.1.0-incubating the Nicira NVP plugin and its resources can be configured in the infrastructure tab of the UI. Navigate to the physical network with STT isolation and configure the network elements. The NiciraNvp is listed here. +
diff --git a/docs/en-US/plugin-niciranvp-usage.xml b/docs/en-US/plugin-niciranvp-usage.xml index 17413387ea4..76f9a0b5b05 100644 --- a/docs/en-US/plugin-niciranvp-usage.xml +++ b/docs/en-US/plugin-niciranvp-usage.xml @@ -24,6 +24,7 @@ Using the Nicira NVP Plugin + From a0373fe1ff2001c5a9deee537d6862327f8818cc Mon Sep 17 00:00:00 2001 From: Hugo Trippaers Date: Mon, 21 Jan 2013 12:34:20 +0100 Subject: [PATCH 38/80] Summary: Apply feedback from Wido Better checking on VlanID Correct speling mistake --- .../com/cloud/hypervisor/kvm/resource/BridgeVifDriver.java | 4 ++-- .../src/com/cloud/hypervisor/kvm/resource/LibvirtVMDef.java | 2 +- .../src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/BridgeVifDriver.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/BridgeVifDriver.java index bde4da268b6..b897df2ecf3 100644 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/BridgeVifDriver.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/BridgeVifDriver.java @@ -176,7 +176,7 @@ public class BridgeVifDriver extends VifDriverBase { createControlNetwork(_bridges.get("linklocal")); } - private void deletExitingLinkLocalRoutTable(String linkLocalBr) { + private void deleteExitingLinkLocalRouteTable(String linkLocalBr) { Script command = new Script("/bin/bash", _timeout); command.add("-c"); command.add("ip route | grep " + NetUtils.getLinkLocalCIDR()); @@ -201,7 +201,7 @@ public class BridgeVifDriver extends VifDriverBase { } private void createControlNetwork(String privBrName) { - deletExitingLinkLocalRoutTable(privBrName); + deleteExitingLinkLocalRouteTable(privBrName); if (!isBridgeExists(privBrName)) { Script.runSimpleBashScript("brctl addbr " + privBrName + "; ifconfig " + privBrName + " up; ifconfig " + privBrName + " 169.254.0.1", _timeout); diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtVMDef.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtVMDef.java index c02d8fc175a..acfd9cf1fe8 100644 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtVMDef.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtVMDef.java @@ -748,7 +748,7 @@ public class LibvirtVMDef { } netBuilder.append("\n"); } - if (_vlanTag != -1) { + if (_vlanTag > 0 && _vlanTag < 4095) { netBuilder.append("\n\n"); } netBuilder.append("\n"); diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java index 04c29a856e0..37761aa5555 100644 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java @@ -143,7 +143,7 @@ public class OvsVifDriver extends VifDriverBase { return brName; } - private void deleteExitingLinkLocalRoutTable(String linkLocalBr) { + private void deleteExitingLinkLocalRouteTable(String linkLocalBr) { Script command = new Script("/bin/bash", _timeout); command.add("-c"); command.add("ip route | grep " + NetUtils.getLinkLocalCIDR()); @@ -168,7 +168,7 @@ public class OvsVifDriver extends VifDriverBase { } private void createControlNetwork(String privBrName) { - deleteExitingLinkLocalRoutTable(privBrName); + deleteExitingLinkLocalRouteTable(privBrName); if (!isBridgeExists(privBrName)) { Script.runSimpleBashScript("ovs-vsctl add-br " + privBrName + "; ifconfig " + privBrName + " up; ifconfig " + privBrName + " 169.254.0.1", _timeout); From 6db719d58b996034773a0f10dcb4945d85adb719 Mon Sep 17 00:00:00 2001 From: Min Chen Date: Mon, 21 Jan 2013 10:48:03 -0800 Subject: [PATCH 39/80] CLOUDSTACK-355: Create DB view to fix count issue for listDiskOfferingsCmd. --- .../com/cloud/server/ManagementService.java | 11 +- .../user/offering/ListDiskOfferingsCmd.java | 11 +- .../apache/cloudstack/query/QueryService.java | 4 + server/src/com/cloud/api/ApiDBUtils.java | 14 ++ .../src/com/cloud/api/ApiResponseHelper.java | 21 +- server/src/com/cloud/api/ApiServer.java | 2 + .../com/cloud/api/query/QueryManagerImpl.java | 177 ++++++++++++- .../cloud/api/query/ViewResponseHelper.java | 10 + .../api/query/dao/DiskOfferingJoinDao.java | 29 +++ .../query/dao/DiskOfferingJoinDaoImpl.java | 101 ++++++++ .../api/query/vo/DiskOfferingJoinVO.java | 233 ++++++++++++++++++ .../DefaultComponentLibrary.java | 2 + .../cloud/server/ManagementServerImpl.java | 195 +-------------- setup/db/create-schema-view.sql | 25 +- setup/db/db/schema-40to410.sql | 24 ++ 15 files changed, 627 insertions(+), 232 deletions(-) create mode 100644 server/src/com/cloud/api/query/dao/DiskOfferingJoinDao.java create mode 100644 server/src/com/cloud/api/query/dao/DiskOfferingJoinDaoImpl.java create mode 100644 server/src/com/cloud/api/query/vo/DiskOfferingJoinVO.java diff --git a/api/src/com/cloud/server/ManagementService.java b/api/src/com/cloud/server/ManagementService.java index 5302daa493b..99355652a2d 100755 --- a/api/src/com/cloud/server/ManagementService.java +++ b/api/src/com/cloud/server/ManagementService.java @@ -144,7 +144,7 @@ public interface ManagementService { /** * Searches for servers by the specified search criteria Can search by: "name", "type", "state", "dataCenterId", * "podId" - * + * * @param cmd * @return List of Hosts */ @@ -243,15 +243,6 @@ public interface ManagementService { */ Set> listTemplates(ListTemplatesCmd cmd); - /** - * Search for disk offerings based on search criteria - * - * @param cmd - * the command containing the criteria to use for searching for disk offerings - * @return a list of disk offerings that match the given criteria - */ - List searchForDiskOfferings(ListDiskOfferingsCmd cmd); - /** * List system VMs by the given search criteria diff --git a/api/src/org/apache/cloudstack/api/command/user/offering/ListDiskOfferingsCmd.java b/api/src/org/apache/cloudstack/api/command/user/offering/ListDiskOfferingsCmd.java index 7209429cfa0..1fc7978f0d5 100644 --- a/api/src/org/apache/cloudstack/api/command/user/offering/ListDiskOfferingsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/offering/ListDiskOfferingsCmd.java @@ -25,6 +25,7 @@ import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.BaseListCmd; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.AsyncJobResponse; import org.apache.cloudstack.api.response.DiskOfferingResponse; import org.apache.cloudstack.api.response.DomainResponse; import org.apache.cloudstack.api.response.ListResponse; @@ -78,16 +79,8 @@ public class ListDiskOfferingsCmd extends BaseListCmd { @Override public void execute(){ - List result = _mgr.searchForDiskOfferings(this); - ListResponse response = new ListResponse(); - List diskOfferingResponses = new ArrayList(); - for (DiskOffering offering : result) { - DiskOfferingResponse diskOffResp = _responseGenerator.createDiskOfferingResponse(offering); - diskOffResp.setObjectName("diskoffering"); - diskOfferingResponses.add(diskOffResp); - } - response.setResponses(diskOfferingResponses); + ListResponse response = _queryService.searchForDiskOfferings(this); response.setResponseName(getCommandName()); this.setResponseObject(response); } diff --git a/api/src/org/apache/cloudstack/query/QueryService.java b/api/src/org/apache/cloudstack/query/QueryService.java index b03a7fc0062..f2b0d3232a2 100644 --- a/api/src/org/apache/cloudstack/query/QueryService.java +++ b/api/src/org/apache/cloudstack/query/QueryService.java @@ -26,6 +26,7 @@ import org.apache.cloudstack.api.command.user.account.ListAccountsCmd; import org.apache.cloudstack.api.command.user.account.ListProjectAccountsCmd; import org.apache.cloudstack.api.command.user.event.ListEventsCmd; import org.apache.cloudstack.api.command.user.job.ListAsyncJobsCmd; +import org.apache.cloudstack.api.command.user.offering.ListDiskOfferingsCmd; import org.apache.cloudstack.api.command.user.project.ListProjectInvitationsCmd; import org.apache.cloudstack.api.command.user.project.ListProjectsCmd; import org.apache.cloudstack.api.command.user.securitygroup.ListSecurityGroupsCmd; @@ -35,6 +36,7 @@ import org.apache.cloudstack.api.command.user.vmgroup.ListVMGroupsCmd; import org.apache.cloudstack.api.command.user.volume.ListVolumesCmd; import org.apache.cloudstack.api.response.AccountResponse; import org.apache.cloudstack.api.response.AsyncJobResponse; +import org.apache.cloudstack.api.response.DiskOfferingResponse; import org.apache.cloudstack.api.response.DomainRouterResponse; import org.apache.cloudstack.api.response.EventResponse; import org.apache.cloudstack.api.response.HostResponse; @@ -92,4 +94,6 @@ public interface QueryService { public ListResponse searchForAccounts(ListAccountsCmd cmd); public ListResponse searchForAsyncJobs(ListAsyncJobsCmd cmd); + + public ListResponse searchForDiskOfferings(ListDiskOfferingsCmd cmd); } diff --git a/server/src/com/cloud/api/ApiDBUtils.java b/server/src/com/cloud/api/ApiDBUtils.java index dfdeb9c0957..3f2f0bb3a63 100755 --- a/server/src/com/cloud/api/ApiDBUtils.java +++ b/server/src/com/cloud/api/ApiDBUtils.java @@ -26,6 +26,7 @@ import org.apache.cloudstack.api.ApiConstants.HostDetails; import org.apache.cloudstack.api.ApiConstants.VMDetails; import org.apache.cloudstack.api.response.AccountResponse; import org.apache.cloudstack.api.response.AsyncJobResponse; +import org.apache.cloudstack.api.response.DiskOfferingResponse; import org.apache.cloudstack.api.response.DomainRouterResponse; import org.apache.cloudstack.api.response.EventResponse; import org.apache.cloudstack.api.response.HostResponse; @@ -42,6 +43,7 @@ import org.apache.cloudstack.api.response.VolumeResponse; import com.cloud.api.query.dao.AccountJoinDao; import com.cloud.api.query.dao.AsyncJobJoinDao; +import com.cloud.api.query.dao.DiskOfferingJoinDao; import com.cloud.api.query.dao.DomainRouterJoinDao; import com.cloud.api.query.dao.HostJoinDao; import com.cloud.api.query.dao.InstanceGroupJoinDao; @@ -56,6 +58,7 @@ import com.cloud.api.query.dao.UserVmJoinDao; import com.cloud.api.query.dao.VolumeJoinDao; import com.cloud.api.query.vo.AccountJoinVO; import com.cloud.api.query.vo.AsyncJobJoinVO; +import com.cloud.api.query.vo.DiskOfferingJoinVO; import com.cloud.api.query.vo.DomainRouterJoinVO; import com.cloud.api.query.vo.EventJoinVO; import com.cloud.api.query.vo.HostJoinVO; @@ -163,6 +166,7 @@ import com.cloud.network.vpc.VpcVO; import com.cloud.network.vpc.dao.StaticRouteDao; import com.cloud.network.vpc.dao.VpcGatewayDao; import com.cloud.network.vpc.dao.VpcOfferingDao; +import com.cloud.offering.DiskOffering; import com.cloud.offering.NetworkOffering; import com.cloud.offering.ServiceOffering; import com.cloud.offerings.NetworkOfferingVO; @@ -333,6 +337,7 @@ public class ApiDBUtils { private static StoragePoolJoinDao _poolJoinDao; private static AccountJoinDao _accountJoinDao; private static AsyncJobJoinDao _jobJoinDao; + private static DiskOfferingJoinDao _diskOfferingJoinDao; private static PhysicalNetworkTrafficTypeDao _physicalNetworkTrafficTypeDao; private static PhysicalNetworkServiceProviderDao _physicalNetworkServiceProviderDao; @@ -437,6 +442,7 @@ public class ApiDBUtils { _vpcOfferingDao = locator.getDao(VpcOfferingDao.class); _snapshotPolicyDao = locator.getDao(SnapshotPolicyDao.class); _asyncJobDao = locator.getDao(AsyncJobDao.class); + _diskOfferingJoinDao = locator.getDao(DiskOfferingJoinDao.class); // Note: stats collector should already have been initialized by this time, otherwise a null instance is returned _statsCollector = StatsCollector.getInstance(); @@ -1399,4 +1405,12 @@ public class ApiDBUtils { public static AsyncJobJoinVO newAsyncJobView(AsyncJob e){ return _jobJoinDao.newAsyncJobView(e); } + + public static DiskOfferingResponse newDiskOfferingResponse(DiskOfferingJoinVO offering) { + return _diskOfferingJoinDao.newDiskOfferingResponse(offering); + } + + public static DiskOfferingJoinVO newDiskOfferingView(DiskOffering offering){ + return _diskOfferingJoinDao.newDiskOfferingView(offering); + } } diff --git a/server/src/com/cloud/api/ApiResponseHelper.java b/server/src/com/cloud/api/ApiResponseHelper.java index c346a6b86f1..07646d89497 100755 --- a/server/src/com/cloud/api/ApiResponseHelper.java +++ b/server/src/com/cloud/api/ApiResponseHelper.java @@ -44,6 +44,7 @@ import com.cloud.api.query.ViewResponseHelper; import com.cloud.api.query.vo.AccountJoinVO; import com.cloud.api.query.vo.AsyncJobJoinVO; import com.cloud.api.query.vo.ControlledViewEntity; +import com.cloud.api.query.vo.DiskOfferingJoinVO; import com.cloud.api.query.vo.DomainRouterJoinVO; import com.cloud.api.query.vo.EventJoinVO; import com.cloud.api.query.vo.HostJoinVO; @@ -298,24 +299,8 @@ public class ApiResponseHelper implements ResponseGenerator { @Override public DiskOfferingResponse createDiskOfferingResponse(DiskOffering offering) { - DiskOfferingResponse diskOfferingResponse = new DiskOfferingResponse(); - diskOfferingResponse.setId(offering.getUuid()); - diskOfferingResponse.setName(offering.getName()); - diskOfferingResponse.setDisplayText(offering.getDisplayText()); - diskOfferingResponse.setCreated(offering.getCreated()); - diskOfferingResponse.setDiskSize(offering.getDiskSize() / (1024 * 1024 * 1024)); - if (offering.getDomainId() != null) { - Domain domain = ApiDBUtils.findDomainById(offering.getDomainId()); - if (domain != null) { - diskOfferingResponse.setDomain(domain.getName()); - diskOfferingResponse.setDomainId(domain.getUuid()); - } - } - diskOfferingResponse.setTags(offering.getTags()); - diskOfferingResponse.setCustomized(offering.isCustomized()); - diskOfferingResponse.setStorageType(offering.getUseLocalStorage() ? ServiceOffering.StorageType.local.toString() : ServiceOffering.StorageType.shared.toString()); - diskOfferingResponse.setObjectName("diskoffering"); - return diskOfferingResponse; + DiskOfferingJoinVO vOffering = ApiDBUtils.newDiskOfferingView(offering); + return ApiDBUtils.newDiskOfferingResponse(vOffering); } @Override diff --git a/server/src/com/cloud/api/ApiServer.java b/server/src/com/cloud/api/ApiServer.java index ac1ba0a651a..19c88514b04 100755 --- a/server/src/com/cloud/api/ApiServer.java +++ b/server/src/com/cloud/api/ApiServer.java @@ -95,6 +95,7 @@ import org.apache.cloudstack.api.command.admin.host.ListHostsCmd; import org.apache.cloudstack.api.command.admin.router.ListRoutersCmd; import org.apache.cloudstack.api.command.admin.storage.ListStoragePoolsCmd; import org.apache.cloudstack.api.command.admin.user.ListUsersCmd; +import org.apache.cloudstack.api.command.user.offering.ListDiskOfferingsCmd; import org.apache.cloudstack.api.command.user.project.ListProjectInvitationsCmd; import org.apache.cloudstack.api.command.user.project.ListProjectsCmd; import org.apache.cloudstack.api.command.user.securitygroup.ListSecurityGroupsCmd; @@ -514,6 +515,7 @@ public class ApiServer implements HttpRequestHandler { && !(cmdObj instanceof ListUsersCmd) && !(cmdObj instanceof ListAccountsCmd) && !(cmdObj instanceof ListStoragePoolsCmd) + && !(cmdObj instanceof ListDiskOfferingsCmd) ) { buildAsyncListResponse((BaseListCmd) cmdObj, caller); } diff --git a/server/src/com/cloud/api/query/QueryManagerImpl.java b/server/src/com/cloud/api/query/QueryManagerImpl.java index b61f10a1ade..c38603ff3ca 100644 --- a/server/src/com/cloud/api/query/QueryManagerImpl.java +++ b/server/src/com/cloud/api/query/QueryManagerImpl.java @@ -32,6 +32,7 @@ import org.apache.cloudstack.api.command.user.account.ListAccountsCmd; import org.apache.cloudstack.api.command.user.account.ListProjectAccountsCmd; import org.apache.cloudstack.api.command.user.event.ListEventsCmd; import org.apache.cloudstack.api.command.user.job.ListAsyncJobsCmd; +import org.apache.cloudstack.api.command.user.offering.ListDiskOfferingsCmd; import org.apache.cloudstack.api.command.user.project.ListProjectInvitationsCmd; import org.apache.cloudstack.api.command.user.project.ListProjectsCmd; import org.apache.cloudstack.api.command.user.securitygroup.ListSecurityGroupsCmd; @@ -41,6 +42,7 @@ import org.apache.cloudstack.api.command.user.vmgroup.ListVMGroupsCmd; import org.apache.cloudstack.api.command.user.volume.ListVolumesCmd; import org.apache.cloudstack.api.response.AccountResponse; import org.apache.cloudstack.api.response.AsyncJobResponse; +import org.apache.cloudstack.api.response.DiskOfferingResponse; import org.apache.cloudstack.api.response.DomainRouterResponse; import org.apache.cloudstack.api.response.EventResponse; import org.apache.cloudstack.api.response.HostResponse; @@ -60,6 +62,7 @@ import org.apache.log4j.Logger; import com.cloud.api.query.dao.AccountJoinDao; import com.cloud.api.query.dao.AsyncJobJoinDao; +import com.cloud.api.query.dao.DiskOfferingJoinDao; import com.cloud.api.query.dao.DomainRouterJoinDao; import com.cloud.api.query.dao.HostJoinDao; import com.cloud.api.query.dao.InstanceGroupJoinDao; @@ -74,6 +77,7 @@ import com.cloud.api.query.dao.UserVmJoinDao; import com.cloud.api.query.dao.VolumeJoinDao; import com.cloud.api.query.vo.AccountJoinVO; import com.cloud.api.query.vo.AsyncJobJoinVO; +import com.cloud.api.query.vo.DiskOfferingJoinVO; import com.cloud.api.query.vo.DomainRouterJoinVO; import com.cloud.api.query.vo.EventJoinVO; import com.cloud.api.query.vo.HostJoinVO; @@ -87,10 +91,12 @@ import com.cloud.api.query.vo.StoragePoolJoinVO; import com.cloud.api.query.vo.UserAccountJoinVO; import com.cloud.api.query.vo.UserVmJoinVO; import com.cloud.api.query.vo.VolumeJoinVO; +import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.domain.Domain; import com.cloud.domain.DomainVO; import com.cloud.domain.dao.DomainDao; import com.cloud.event.dao.EventJoinDao; +import com.cloud.exception.CloudAuthenticationException; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.PermissionDeniedException; import com.cloud.ha.HighAvailabilityManager; @@ -104,6 +110,7 @@ import com.cloud.projects.ProjectManager; import com.cloud.projects.dao.ProjectAccountDao; import com.cloud.projects.dao.ProjectDao; import com.cloud.server.Criteria; +import com.cloud.storage.DiskOfferingVO; import com.cloud.storage.StoragePool; import com.cloud.storage.StoragePoolVO; import com.cloud.storage.Volume; @@ -199,6 +206,9 @@ public class QueryManagerImpl implements QueryService, Manager { @Inject private AccountDao _accountDao; + @Inject + private ConfigurationDao _configDao; + @Inject private AccountJoinDao _accountJoinDao; @@ -208,6 +218,9 @@ public class QueryManagerImpl implements QueryService, Manager { @Inject private StoragePoolJoinDao _poolJoinDao; + @Inject + private DiskOfferingJoinDao _diskOfferingJoinDao; + @Inject private HighAvailabilityManager _haMgr; @@ -1603,7 +1616,7 @@ public class QueryManagerImpl implements QueryService, Manager { } - public Pair, Integer> searchForAccountsInternal(ListAccountsCmd cmd) { + private Pair, Integer> searchForAccountsInternal(ListAccountsCmd cmd) { Account caller = UserContext.current().getCaller(); Long domainId = cmd.getDomainId(); Long accountId = cmd.getId(); @@ -1729,7 +1742,7 @@ public class QueryManagerImpl implements QueryService, Manager { } - public Pair, Integer> searchForAsyncJobsInternal(ListAsyncJobsCmd cmd) { + private Pair, Integer> searchForAsyncJobsInternal(ListAsyncJobsCmd cmd) { Account caller = UserContext.current().getCaller(); @@ -1808,7 +1821,7 @@ public class QueryManagerImpl implements QueryService, Manager { return response; } - public Pair, Integer> searchForStoragePoolsInternal(ListStoragePoolsCmd cmd) { + private Pair, Integer> searchForStoragePoolsInternal(ListStoragePoolsCmd cmd) { Long zoneId = _accountMgr.checkAccessAndSpecifyAuthority(UserContext.current().getCaller(), cmd.getZoneId()); Object id = cmd.getId(); @@ -1888,5 +1901,163 @@ public class QueryManagerImpl implements QueryService, Manager { } + @Override + public ListResponse searchForDiskOfferings(ListDiskOfferingsCmd cmd) { + Pair, Integer> result = searchForDiskOfferingsInternal(cmd); + ListResponse response = new ListResponse(); + List offeringResponses = ViewResponseHelper.createDiskOfferingResponse(result.first().toArray(new DiskOfferingJoinVO[result.first().size()])); + response.setResponses(offeringResponses, result.second()); + return response; + } + private Pair, Integer> searchForDiskOfferingsInternal(ListDiskOfferingsCmd cmd) { + // Note + // The list method for offerings is being modified in accordance with + // discussion with Will/Kevin + // For now, we will be listing the following based on the usertype + // 1. For root, we will list all offerings + // 2. For domainAdmin and regular users, we will list everything in + // their domains+parent domains ... all the way + // till + // root + + Boolean isAscending = Boolean.parseBoolean(_configDao.getValue("sortkey.algorithm")); + isAscending = (isAscending == null ? true : isAscending); + Filter searchFilter = new Filter(DiskOfferingJoinVO.class, "sortKey", isAscending, cmd.getStartIndex(), cmd.getPageSizeVal()); + SearchBuilder sb = _diskOfferingJoinDao.createSearchBuilder(); + + + Account account = UserContext.current().getCaller(); + Object name = cmd.getDiskOfferingName(); + Object id = cmd.getId(); + Object keyword = cmd.getKeyword(); + Long domainId = cmd.getDomainId(); + // Keeping this logic consistent with domain specific zones + // if a domainId is provided, we just return the disk offering + // associated with this domain + if (domainId != null) { + if (account.getType() == Account.ACCOUNT_TYPE_ADMIN || isPermissible(account.getDomainId(), domainId) ) { + // check if the user's domain == do's domain || user's domain is + // a child of so's domain for non-root users + sb.and("domainId", sb.entity().getDomainId(), SearchCriteria.Op.EQ); + SearchCriteria sc = sb.create(); + sc.setParameters("domainId", domainId); + return _diskOfferingJoinDao.searchAndCount(sc, searchFilter); + } else { + throw new PermissionDeniedException("The account:" + account.getAccountName() + + " does not fall in the same domain hierarchy as the disk offering"); + } + } + + sb.and("name", sb.entity().getName(), SearchCriteria.Op.LIKE); + sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); + + + boolean includePublicOfferings = false; + List domainIds = null; + // For non-root users, only return all offerings for the user's domain, and everything above till root + if ((account.getType() == Account.ACCOUNT_TYPE_NORMAL || account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) + || account.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) { + // find all domain Id up to root domain for this account + domainIds = new ArrayList(); + DomainVO domainRecord = _domainDao.findById(account.getDomainId()); + if ( domainRecord == null ){ + s_logger.error("Could not find the domainId for account:" + account.getAccountName()); + throw new CloudAuthenticationException("Could not find the domainId for account:" + account.getAccountName()); + } + domainIds.add(domainRecord.getId()); + while (domainRecord.getParent() != null ){ + domainRecord = _domainDao.findById(domainRecord.getParent()); + domainIds.add(domainRecord.getId()); + } + sb.and("domainIdIn", sb.entity().getDomainId(), SearchCriteria.Op.IN); + + // include also public offering if no keyword, name and id specified + if ( keyword == null && name == null && id == null ){ + includePublicOfferings = true; + } + } + + SearchCriteria sc = sb.create(); + if (keyword != null) { + SearchCriteria ssc = _diskOfferingJoinDao.createSearchCriteria(); + ssc.addOr("displayText", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + + sc.addAnd("name", SearchCriteria.Op.SC, ssc); + } + + if (name != null) { + sc.setParameters("name", "%" + name + "%"); + } + + if (id != null) { + sc.setParameters("id", id); + } + + if (domainIds != null ){ + sc.setParameters("domainIdIn", domainIds); + } + + if (includePublicOfferings){ + SearchCriteria spc = _diskOfferingJoinDao.createSearchCriteria(); + spc.addAnd("domainId", SearchCriteria.Op.NULL); + spc.addAnd("systemUse", SearchCriteria.Op.EQ, false); + + sc.addOr("systemUse", SearchCriteria.Op.SC, spc); + } + + // FIXME: disk offerings should search back up the hierarchy for + // available disk offerings... + /* + * sb.addAnd("domainId", sb.entity().getDomainId(), + * SearchCriteria.Op.EQ); if (domainId != null) { + * SearchBuilder domainSearch = + * _domainDao.createSearchBuilder(); domainSearch.addAnd("path", + * domainSearch.entity().getPath(), SearchCriteria.Op.LIKE); + * sb.join("domainSearch", domainSearch, sb.entity().getDomainId(), + * domainSearch.entity().getId()); } + */ + + // FIXME: disk offerings should search back up the hierarchy for + // available disk offerings... + /* + * if (domainId != null) { sc.setParameters("domainId", domainId); // + * //DomainVO domain = _domainDao.findById((Long)domainId); // // I want + * to join on user_vm.domain_id = domain.id where domain.path like + * 'foo%' //sc.setJoinParameters("domainSearch", "path", + * domain.getPath() + "%"); // } + */ + + return _diskOfferingJoinDao.searchAndCount(sc, searchFilter); + } + + + // This method is used for permissions check for both disk and service + // offerings + private boolean isPermissible(Long accountDomainId, Long offeringDomainId) { + + if (accountDomainId == offeringDomainId) { + return true; // account and service offering in same domain + } + + DomainVO domainRecord = _domainDao.findById(accountDomainId); + + if (domainRecord != null) { + while (true) { + if (domainRecord.getId() == offeringDomainId) { + return true; + } + + // try and move on to the next domain + if (domainRecord.getParent() != null) { + domainRecord = _domainDao.findById(domainRecord.getParent()); + } else { + break; + } + } + } + + return false; + } } diff --git a/server/src/com/cloud/api/query/ViewResponseHelper.java b/server/src/com/cloud/api/query/ViewResponseHelper.java index 39c108eb932..9c761d4f91c 100644 --- a/server/src/com/cloud/api/query/ViewResponseHelper.java +++ b/server/src/com/cloud/api/query/ViewResponseHelper.java @@ -25,6 +25,7 @@ import org.apache.cloudstack.api.ApiConstants.HostDetails; import org.apache.cloudstack.api.ApiConstants.VMDetails; import org.apache.cloudstack.api.response.AccountResponse; import org.apache.cloudstack.api.response.AsyncJobResponse; +import org.apache.cloudstack.api.response.DiskOfferingResponse; import org.apache.cloudstack.api.response.DomainRouterResponse; import org.apache.cloudstack.api.response.EventResponse; import org.apache.cloudstack.api.response.HostResponse; @@ -43,6 +44,7 @@ import org.apache.log4j.Logger; import com.cloud.api.ApiDBUtils; import com.cloud.api.query.vo.AccountJoinVO; import com.cloud.api.query.vo.AsyncJobJoinVO; +import com.cloud.api.query.vo.DiskOfferingJoinVO; import com.cloud.api.query.vo.DomainRouterJoinVO; import com.cloud.api.query.vo.EventJoinVO; import com.cloud.api.query.vo.HostJoinVO; @@ -274,4 +276,12 @@ public class ViewResponseHelper { } return respList; } + + public static List createDiskOfferingResponse(DiskOfferingJoinVO... offerings) { + List respList = new ArrayList(); + for (DiskOfferingJoinVO vt : offerings){ + respList.add(ApiDBUtils.newDiskOfferingResponse(vt)); + } + return respList; + } } diff --git a/server/src/com/cloud/api/query/dao/DiskOfferingJoinDao.java b/server/src/com/cloud/api/query/dao/DiskOfferingJoinDao.java new file mode 100644 index 00000000000..30758d12268 --- /dev/null +++ b/server/src/com/cloud/api/query/dao/DiskOfferingJoinDao.java @@ -0,0 +1,29 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api.query.dao; + +import org.apache.cloudstack.api.response.DiskOfferingResponse; +import com.cloud.api.query.vo.DiskOfferingJoinVO; +import com.cloud.offering.DiskOffering; +import com.cloud.utils.db.GenericDao; + +public interface DiskOfferingJoinDao extends GenericDao { + + DiskOfferingResponse newDiskOfferingResponse(DiskOfferingJoinVO dof); + + DiskOfferingJoinVO newDiskOfferingView(DiskOffering dof); +} diff --git a/server/src/com/cloud/api/query/dao/DiskOfferingJoinDaoImpl.java b/server/src/com/cloud/api/query/dao/DiskOfferingJoinDaoImpl.java new file mode 100644 index 00000000000..d8773815659 --- /dev/null +++ b/server/src/com/cloud/api/query/dao/DiskOfferingJoinDaoImpl.java @@ -0,0 +1,101 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api.query.dao; + +import java.util.List; + +import javax.ejb.Local; + +import org.apache.log4j.Logger; + +import com.cloud.api.query.vo.DiskOfferingJoinVO; +import org.apache.cloudstack.api.response.DiskOfferingResponse; +import com.cloud.offering.DiskOffering; +import com.cloud.offering.ServiceOffering; +import com.cloud.storage.DiskOfferingVO; +import com.cloud.storage.DiskOfferingVO.Type; +import com.cloud.utils.db.Attribute; +import com.cloud.utils.db.Filter; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; +import com.cloud.utils.db.SearchCriteria.Op; + + +@Local(value={DiskOfferingJoinDao.class}) +public class DiskOfferingJoinDaoImpl extends GenericDaoBase implements DiskOfferingJoinDao { + public static final Logger s_logger = Logger.getLogger(DiskOfferingJoinDaoImpl.class); + + + private SearchBuilder dofIdSearch; + private final Attribute _typeAttr; + + protected DiskOfferingJoinDaoImpl() { + + dofIdSearch = createSearchBuilder(); + dofIdSearch.and("id", dofIdSearch.entity().getId(), SearchCriteria.Op.EQ); + dofIdSearch.done(); + + _typeAttr = _allAttributes.get("type"); + + this._count = "select count(distinct id) from disk_offering_view WHERE "; + } + + + + @Override + public DiskOfferingResponse newDiskOfferingResponse(DiskOfferingJoinVO offering) { + + DiskOfferingResponse diskOfferingResponse = new DiskOfferingResponse(); + diskOfferingResponse.setId(offering.getUuid()); + diskOfferingResponse.setName(offering.getName()); + diskOfferingResponse.setDisplayText(offering.getDisplayText()); + diskOfferingResponse.setCreated(offering.getCreated()); + diskOfferingResponse.setDiskSize(offering.getDiskSize() / (1024 * 1024 * 1024)); + + diskOfferingResponse.setDomain(offering.getDomainName()); + diskOfferingResponse.setDomainId(offering.getDomainUuid()); + + diskOfferingResponse.setTags(offering.getTags()); + diskOfferingResponse.setCustomized(offering.isCustomized()); + diskOfferingResponse.setStorageType(offering.isUseLocalStorage() ? ServiceOffering.StorageType.local.toString() : ServiceOffering.StorageType.shared.toString()); + diskOfferingResponse.setObjectName("diskoffering"); + return diskOfferingResponse; + } + + + @Override + public DiskOfferingJoinVO newDiskOfferingView(DiskOffering offering) { + SearchCriteria sc = dofIdSearch.create(); + sc.setParameters("id", offering.getId()); + List offerings = searchIncludingRemoved(sc, null, null, false); + assert offerings != null && offerings.size() == 1 : "No disk offering found for offering id " + offering.getId(); + return offerings.get(0); + } + + @Override + public List searchIncludingRemoved(SearchCriteria sc, final Filter filter, final Boolean lock, final boolean cache) { + sc.addAnd(_typeAttr, Op.EQ, Type.Disk); + return super.searchIncludingRemoved(sc, filter, lock, cache); + } + + @Override + public List customSearchIncludingRemoved(SearchCriteria sc, final Filter filter) { + sc.addAnd(_typeAttr, Op.EQ, Type.Disk); + return super.customSearchIncludingRemoved(sc, filter); + } +} diff --git a/server/src/com/cloud/api/query/vo/DiskOfferingJoinVO.java b/server/src/com/cloud/api/query/vo/DiskOfferingJoinVO.java new file mode 100644 index 00000000000..7785beeece3 --- /dev/null +++ b/server/src/com/cloud/api/query/vo/DiskOfferingJoinVO.java @@ -0,0 +1,233 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api.query.vo; + +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +import com.cloud.storage.DiskOfferingVO.Type; +import com.cloud.utils.db.GenericDao; + +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + +@Entity +@Table(name="disk_offering_view") +public class DiskOfferingJoinVO extends BaseViewVO implements InternalIdentity, Identity { + + @Id + @Column(name="id", updatable=false, nullable = false) + private long id; + + @Column(name="uuid") + private String uuid; + + @Column(name="name") + private String name; + + @Column(name="display_text") + private String displayText; + + @Column(name="disk_size") + long diskSize; + + @Column(name="tags", length=4096) + String tags; + + @Column(name="use_local_storage") + private boolean useLocalStorage; + + @Column(name="system_use") + private boolean systemUse; + + @Column(name="customized") + private boolean customized; + + @Column(name="sort_key") + int sortKey; + + @Column(name="type") + Type type; + + @Column(name=GenericDao.CREATED_COLUMN) + private Date created; + + @Column(name=GenericDao.REMOVED_COLUMN) + private Date removed; + + @Column(name="domain_id") + private long domainId; + + @Column(name="domain_uuid") + private String domainUuid; + + @Column(name="domain_name") + private String domainName = null; + + @Column(name="domain_path") + private String domainPath = null; + + + public DiskOfferingJoinVO() { + } + + @Override + public long getId() { + return id; + } + + @Override + public void setId(long id) { + this.id = id; + } + + @Override + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDisplayText() { + return displayText; + } + + public void setDisplayText(String displayText) { + this.displayText = displayText; + } + + public long getDiskSize() { + return diskSize; + } + + public void setDiskSize(long diskSize) { + this.diskSize = diskSize; + } + + public String getTags() { + return tags; + } + + public void setTags(String tags) { + this.tags = tags; + } + + public boolean isUseLocalStorage() { + return useLocalStorage; + } + + public void setUseLocalStorage(boolean useLocalStorage) { + this.useLocalStorage = useLocalStorage; + } + + public boolean isSystemUse() { + return systemUse; + } + + public void setSystemUse(boolean systemUse) { + this.systemUse = systemUse; + } + + public boolean isCustomized() { + return customized; + } + + public void setCustomized(boolean customized) { + this.customized = customized; + } + + public Date getCreated() { + return created; + } + + public void setCreated(Date created) { + this.created = created; + } + + public Date getRemoved() { + return removed; + } + + public void setRemoved(Date removed) { + this.removed = removed; + } + + public long getDomainId() { + return domainId; + } + + public void setDomainId(long domainId) { + this.domainId = domainId; + } + + public String getDomainUuid() { + return domainUuid; + } + + public void setDomainUuid(String domainUuid) { + this.domainUuid = domainUuid; + } + + public String getDomainName() { + return domainName; + } + + public void setDomainName(String domainName) { + this.domainName = domainName; + } + + public String getDomainPath() { + return domainPath; + } + + public void setDomainPath(String domainPath) { + this.domainPath = domainPath; + } + + public int getSortKey() { + return sortKey; + } + + public void setSortKey(int sortKey) { + this.sortKey = sortKey; + } + + public Type getType() { + return type; + } + + public void setType(Type type) { + this.type = type; + } + + + +} diff --git a/server/src/com/cloud/configuration/DefaultComponentLibrary.java b/server/src/com/cloud/configuration/DefaultComponentLibrary.java index e98946b9aa7..5a1b0026282 100755 --- a/server/src/com/cloud/configuration/DefaultComponentLibrary.java +++ b/server/src/com/cloud/configuration/DefaultComponentLibrary.java @@ -27,6 +27,7 @@ import com.cloud.alert.dao.AlertDaoImpl; import com.cloud.api.query.QueryManagerImpl; import com.cloud.api.query.dao.AccountJoinDaoImpl; import com.cloud.api.query.dao.AsyncJobJoinDaoImpl; +import com.cloud.api.query.dao.DiskOfferingJoinDaoImpl; import com.cloud.api.query.dao.DomainRouterJoinDaoImpl; import com.cloud.api.query.dao.InstanceGroupJoinDaoImpl; import com.cloud.api.query.dao.ProjectAccountJoinDaoImpl; @@ -392,6 +393,7 @@ public class DefaultComponentLibrary extends ComponentLibraryBase implements Com addDao("AccountJoinDao", AccountJoinDaoImpl.class); addDao("AsyncJobJoinDao", AsyncJobJoinDaoImpl.class); addDao("StoragePoolJoinDao", StoragePoolJoinDaoImpl.class); + addDao("DiskOfferingJoinDao", DiskOfferingJoinDaoImpl.class); } @Override diff --git a/server/src/com/cloud/server/ManagementServerImpl.java b/server/src/com/cloud/server/ManagementServerImpl.java index bad834dde5a..0684440b026 100755 --- a/server/src/com/cloud/server/ManagementServerImpl.java +++ b/server/src/com/cloud/server/ManagementServerImpl.java @@ -46,7 +46,6 @@ import org.apache.cloudstack.api.BaseUpdateTemplateOrIsoCmd; import org.apache.cloudstack.api.command.admin.cluster.ListClustersCmd; import org.apache.cloudstack.api.command.admin.config.ListCfgsByCmd; import org.apache.cloudstack.api.command.admin.resource.ListAlertsCmd; -import org.apache.cloudstack.api.command.admin.storage.ListStoragePoolsCmd; import org.apache.cloudstack.api.command.admin.systemvm.DestroySystemVmCmd; import org.apache.cloudstack.api.command.admin.systemvm.UpgradeSystemVMCmd; import org.apache.cloudstack.api.command.user.address.ListPublicIpAddressesCmd; @@ -55,7 +54,6 @@ import org.apache.cloudstack.api.command.user.guest.ListGuestOsCategoriesCmd; import org.apache.cloudstack.api.command.user.guest.ListGuestOsCmd; import org.apache.cloudstack.api.command.user.iso.ListIsosCmd; import org.apache.cloudstack.api.command.user.iso.UpdateIsoCmd; -import org.apache.cloudstack.api.command.user.offering.ListDiskOfferingsCmd; import org.apache.cloudstack.api.command.user.offering.ListServiceOfferingsCmd; import org.apache.cloudstack.api.command.user.ssh.ListSSHKeyPairsCmd; import org.apache.cloudstack.api.command.user.ssh.DeleteSSHKeyPairCmd; @@ -91,9 +89,6 @@ import org.apache.cloudstack.api.command.admin.systemvm.StopSystemVmCmd; import org.apache.cloudstack.api.command.admin.domain.UpdateDomainCmd; import org.apache.cloudstack.api.command.admin.host.ListHostsCmd; import org.apache.cloudstack.api.command.admin.host.UpdateHostPasswordCmd; -import com.cloud.api.query.dao.DomainRouterJoinDao; -import com.cloud.api.query.dao.InstanceGroupJoinDao; - import org.apache.cloudstack.api.command.user.vmgroup.UpdateVMGroupCmd; import org.apache.cloudstack.api.command.admin.resource.UploadCustomCertificateCmd; import org.apache.cloudstack.api.response.ExtractResponse; @@ -103,13 +98,11 @@ import com.cloud.async.AsyncJobManager; import com.cloud.async.AsyncJobResult; import com.cloud.async.AsyncJobVO; import com.cloud.async.BaseAsyncJobExecutor; -import com.cloud.async.dao.AsyncJobDao; import com.cloud.capacity.Capacity; import com.cloud.capacity.CapacityVO; import com.cloud.capacity.dao.CapacityDao; import com.cloud.capacity.dao.CapacityDaoImpl.SummedCapacity; import com.cloud.configuration.Config; -import com.cloud.configuration.ConfigurationManager; import com.cloud.configuration.Configuration; import com.cloud.configuration.ConfigurationVO; import com.cloud.configuration.dao.ConfigurationDao; @@ -139,7 +132,6 @@ import com.cloud.event.EventTypes; import com.cloud.event.EventUtils; import com.cloud.event.EventVO; import com.cloud.event.dao.EventDao; -import com.cloud.event.dao.EventJoinDao; import com.cloud.exception.CloudAuthenticationException; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InvalidParameterValueException; @@ -179,7 +171,6 @@ import com.cloud.server.ResourceTag.TaggedResourceType; import com.cloud.server.auth.UserAuthenticator; import com.cloud.service.ServiceOfferingVO; import com.cloud.service.dao.ServiceOfferingDao; -import com.cloud.storage.DiskOfferingVO; import com.cloud.storage.GuestOS; import com.cloud.storage.GuestOSCategoryVO; import com.cloud.storage.GuestOSVO; @@ -187,7 +178,6 @@ import com.cloud.storage.GuestOsCategory; import com.cloud.storage.Storage; import com.cloud.storage.Storage.ImageFormat; import com.cloud.storage.StorageManager; -import com.cloud.storage.StoragePool; import com.cloud.storage.StoragePoolVO; import com.cloud.storage.Upload; import com.cloud.storage.Upload.Mode; @@ -195,7 +185,6 @@ import com.cloud.storage.UploadVO; import com.cloud.storage.VMTemplateVO; import com.cloud.storage.Volume; import com.cloud.storage.VolumeVO; -import com.cloud.storage.dao.DiskOfferingDao; import com.cloud.storage.dao.GuestOSCategoryDao; import com.cloud.storage.dao.GuestOSDao; import com.cloud.storage.dao.StoragePoolDao; @@ -220,12 +209,10 @@ import com.cloud.user.UserVO; import com.cloud.user.dao.AccountDao; import com.cloud.user.dao.SSHKeyPairDao; import com.cloud.user.dao.UserDao; -import com.cloud.uservm.UserVm; import com.cloud.utils.EnumUtils; import com.cloud.utils.NumbersUtil; import com.cloud.utils.Pair; import com.cloud.utils.PasswordGenerator; -import com.cloud.utils.PropertiesUtil; import com.cloud.utils.Ternary; import com.cloud.utils.component.Adapters; import com.cloud.utils.component.ComponentLocator; @@ -258,7 +245,6 @@ import com.cloud.vm.VirtualMachineProfileImpl; import com.cloud.vm.dao.ConsoleProxyDao; import com.cloud.vm.dao.DomainRouterDao; import com.cloud.vm.dao.InstanceGroupDao; -import com.cloud.vm.dao.NicDao; import com.cloud.vm.dao.SecondaryStorageVmDao; import com.cloud.vm.dao.UserVmDao; import com.cloud.vm.dao.VMInstanceDao; @@ -274,12 +260,10 @@ public class ManagementServerImpl implements ManagementServer { private final AlertManager _alertMgr; private final IPAddressDao _publicIpAddressDao; private final DomainRouterDao _routerDao; - private final DomainRouterJoinDao _routerJoinDao; private final ConsoleProxyDao _consoleProxyDao; private final ClusterDao _clusterDao; private final SecondaryStorageVmDao _secStorageVmDao; private final EventDao _eventDao; - private final EventJoinDao _eventJoinDao; private final DataCenterDao _dcDao; private final VlanDao _vlanDao; private final AccountVlanMapDao _accountVlanMapDao; @@ -294,7 +278,6 @@ public class ManagementServerImpl implements ManagementServer { private final SwiftManager _swiftMgr; private final S3Manager _s3Mgr; private final ServiceOfferingDao _offeringsDao; - private final DiskOfferingDao _diskOfferingDao; private final VMTemplateDao _templateDao; private final DomainDao _domainDao; private final AccountDao _accountDao; @@ -303,25 +286,21 @@ public class ManagementServerImpl implements ManagementServer { private final GuestOSDao _guestOSDao; private final GuestOSCategoryDao _guestOSCategoryDao; private final StoragePoolDao _poolDao; - private final NicDao _nicDao; private final NetworkDao _networkDao; private final StorageManager _storageMgr; private final VirtualMachineManager _itMgr; private final HostPodDao _hostPodDao; private final VMInstanceDao _vmInstanceDao; private final VolumeDao _volumeDao; - private final AsyncJobDao _jobDao; private final AsyncJobManager _asyncMgr; private final int _purgeDelay; private final InstanceGroupDao _vmGroupDao; - private final InstanceGroupJoinDao _vmGroupJoinDao; private final UploadMonitor _uploadMonitor; private final UploadDao _uploadDao; private final SSHKeyPairDao _sshKeyPairDao; private final LoadBalancerDao _loadbalancerDao; private final HypervisorCapabilitiesDao _hypervisorCapabilitiesDao; private final Adapters _hostAllocators; - private final ConfigurationManager _configMgr; private final ResourceTagDao _resourceTagDao; @Inject @@ -340,6 +319,8 @@ public class ManagementServerImpl implements ManagementServer { private final Map _configs; + // even though this _statsCollector is never used here, but we create the singleton here to avoid null pointer exception in other places + // like ApiDbUtils to reference StatsCollector instance. private final StatsCollector _statsCollector; private final Map _availableIdsMap; @@ -352,9 +333,7 @@ public class ManagementServerImpl implements ManagementServer { ComponentLocator locator = ComponentLocator.getLocator(Name); _configDao = locator.getDao(ConfigurationDao.class); _routerDao = locator.getDao(DomainRouterDao.class); - _routerJoinDao = locator.getDao(DomainRouterJoinDao.class); _eventDao = locator.getDao(EventDao.class); - _eventJoinDao = locator.getDao(EventJoinDao.class); _dcDao = locator.getDao(DataCenterDao.class); _vlanDao = locator.getDao(VlanDao.class); _accountVlanMapDao = locator.getDao(AccountVlanMapDao.class); @@ -362,9 +341,7 @@ public class ManagementServerImpl implements ManagementServer { _hostDao = locator.getDao(HostDao.class); _detailsDao = locator.getDao(HostDetailsDao.class); _hostPodDao = locator.getDao(HostPodDao.class); - _jobDao = locator.getDao(AsyncJobDao.class); _clusterDao = locator.getDao(ClusterDao.class); - _nicDao = locator.getDao(NicDao.class); _networkDao = locator.getDao(NetworkDao.class); _loadbalancerDao = locator.getDao(LoadBalancerDao.class); @@ -382,7 +359,6 @@ public class ManagementServerImpl implements ManagementServer { _userDao = locator.getDao(UserDao.class); _userVmDao = locator.getDao(UserVmDao.class); _offeringsDao = locator.getDao(ServiceOfferingDao.class); - _diskOfferingDao = locator.getDao(DiskOfferingDao.class); _templateDao = locator.getDao(VMTemplateDao.class); _domainDao = locator.getDao(DomainDao.class); _accountDao = locator.getDao(AccountDao.class); @@ -392,7 +368,6 @@ public class ManagementServerImpl implements ManagementServer { _guestOSCategoryDao = locator.getDao(GuestOSCategoryDao.class); _poolDao = locator.getDao(StoragePoolDao.class); _vmGroupDao = locator.getDao(InstanceGroupDao.class); - _vmGroupJoinDao = locator.getDao(InstanceGroupJoinDao.class); _uploadDao = locator.getDao(UploadDao.class); _configs = _configDao.getConfiguration(); _vmInstanceDao = locator.getDao(VMInstanceDao.class); @@ -403,7 +378,6 @@ public class ManagementServerImpl implements ManagementServer { _itMgr = locator.getManager(VirtualMachineManager.class); _ksMgr = locator.getManager(KeystoreManager.class); _resourceMgr = locator.getManager(ResourceManager.class); - _configMgr = locator.getManager(ConfigurationManager.class); _resourceTagDao = locator.getDao(ResourceTagDao.class); _hypervisorCapabilitiesDao = locator.getDao(HypervisorCapabilitiesDao.class); @@ -997,7 +971,7 @@ public class ManagementServerImpl implements ManagementServer { Pair, Integer> allHostsInClusterPair = searchForServers(startIndex, pageSize, null, hostType, null, null, null, cluster, null, null, null, null); - // filter out the current host + // filter out the current host List allHostsInCluster = allHostsInClusterPair.first(); allHostsInCluster.remove(srcHost); Pair, Integer> otherHostsInCluster = new Pair, Integer>(allHostsInCluster, new Integer(allHostsInClusterPair.second().intValue()-1)); @@ -2153,169 +2127,7 @@ public class ManagementServerImpl implements ManagementServer { || (accountType == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) || (accountType == Account.ACCOUNT_TYPE_READ_ONLY_ADMIN)); } - private List searchDiskOfferingsInternal(Account account, Object name, Object id, Object keyword, Filter searchFilter) { - // it was decided to return all offerings for the user's domain, and - // everything above till root (for normal user - // or - // domain admin) - // list all offerings belonging to this domain, and all of its parents - // check the parent, if not null, add offerings for that parent to list - List dol = new ArrayList(); - DomainVO domainRecord = _domainDao.findById(account.getDomainId()); - boolean includePublicOfferings = true; - if (domainRecord != null) { - while (true) { - SearchBuilder sb = _diskOfferingDao.createSearchBuilder(); - sb.and("name", sb.entity().getName(), SearchCriteria.Op.LIKE); - sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); - sb.and("removed", sb.entity().getRemoved(), SearchCriteria.Op.NULL); - - SearchCriteria sc = sb.create(); - if (keyword != null) { - includePublicOfferings = false; - SearchCriteria ssc = _diskOfferingDao.createSearchCriteria(); - ssc.addOr("displayText", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - - sc.addAnd("name", SearchCriteria.Op.SC, ssc); - } - - if (name != null) { - includePublicOfferings = false; - sc.setParameters("name", "%" + name + "%"); - } - - if (id != null) { - includePublicOfferings = false; - sc.setParameters("id", id); - } - - // for this domain - sc.addAnd("domainId", SearchCriteria.Op.EQ, domainRecord.getId()); - - // search and add for this domain - dol.addAll(_diskOfferingDao.search(sc, searchFilter)); - - // try and move on to the next domain - if (domainRecord.getParent() != null) { - domainRecord = _domainDao.findById(domainRecord.getParent()); - } else { - break;// now we got all the offerings for this user/dom adm - } - } - } else { - s_logger.error("Could not find the domainId for account:" + account.getAccountName()); - throw new CloudAuthenticationException("Could not find the domainId for account:" + account.getAccountName()); - } - - // add all the public offerings to the sol list before returning - if (includePublicOfferings) { - dol.addAll(_diskOfferingDao.findPublicDiskOfferings()); - } - - return dol; - - } - - @Override - public List searchForDiskOfferings(ListDiskOfferingsCmd cmd) { - // Note - // The list method for offerings is being modified in accordance with - // discussion with Will/Kevin - // For now, we will be listing the following based on the usertype - // 1. For root, we will list all offerings - // 2. For domainAdmin and regular users, we will list everything in - // their domains+parent domains ... all the way - // till - // root - - Boolean isAscending = Boolean.parseBoolean(_configDao.getValue("sortkey.algorithm")); - isAscending = (isAscending == null ? true : isAscending); - Filter searchFilter = new Filter(DiskOfferingVO.class, "sortKey", isAscending, cmd.getStartIndex(), cmd.getPageSizeVal()); - SearchBuilder sb = _diskOfferingDao.createSearchBuilder(); - - // SearchBuilder and SearchCriteria are now flexible so that the search - // builder can be built with all possible - // search terms and only those with criteria can be set. The proper SQL - // should be generated as a result. - Account account = UserContext.current().getCaller(); - Object name = cmd.getDiskOfferingName(); - Object id = cmd.getId(); - Object keyword = cmd.getKeyword(); - Long domainId = cmd.getDomainId(); - // Keeping this logic consistent with domain specific zones - // if a domainId is provided, we just return the disk offering - // associated with this domain - if (domainId != null) { - if (account.getType() == Account.ACCOUNT_TYPE_ADMIN) { - return _diskOfferingDao.listByDomainId(domainId);// no perm - // check - } else { - // check if the user's domain == do's domain || user's domain is - // a child of so's domain - if (isPermissible(account.getDomainId(), domainId)) { - // perm check succeeded - return _diskOfferingDao.listByDomainId(domainId); - } else { - throw new PermissionDeniedException("The account:" + account.getAccountName() - + " does not fall in the same domain hierarchy as the disk offering"); - } - } - } - - // For non-root users - if ((account.getType() == Account.ACCOUNT_TYPE_NORMAL || account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) - || account.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) { - return searchDiskOfferingsInternal(account, name, id, keyword, searchFilter); - } - - // For root users, preserving existing flow - sb.and("name", sb.entity().getName(), SearchCriteria.Op.LIKE); - sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); - sb.and("removed", sb.entity().getRemoved(), SearchCriteria.Op.NULL); - - // FIXME: disk offerings should search back up the hierarchy for - // available disk offerings... - /* - * sb.addAnd("domainId", sb.entity().getDomainId(), - * SearchCriteria.Op.EQ); if (domainId != null) { - * SearchBuilder domainSearch = - * _domainDao.createSearchBuilder(); domainSearch.addAnd("path", - * domainSearch.entity().getPath(), SearchCriteria.Op.LIKE); - * sb.join("domainSearch", domainSearch, sb.entity().getDomainId(), - * domainSearch.entity().getId()); } - */ - - SearchCriteria sc = sb.create(); - if (keyword != null) { - SearchCriteria ssc = _diskOfferingDao.createSearchCriteria(); - ssc.addOr("displayText", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - - sc.addAnd("name", SearchCriteria.Op.SC, ssc); - } - - if (name != null) { - sc.setParameters("name", "%" + name + "%"); - } - - if (id != null) { - sc.setParameters("id", id); - } - - // FIXME: disk offerings should search back up the hierarchy for - // available disk offerings... - /* - * if (domainId != null) { sc.setParameters("domainId", domainId); // - * //DomainVO domain = _domainDao.findById((Long)domainId); // // I want - * to join on user_vm.domain_id = domain.id where domain.path like - * 'foo%' //sc.setJoinParameters("domainSearch", "path", - * domain.getPath() + "%"); // } - */ - - return _diskOfferingDao.search(sc, searchFilter); - } @Override public List> getCommands() { @@ -3321,6 +3133,7 @@ public class ManagementServerImpl implements ManagementServer { } + @Override public void enableAdminUser(String password) { String encodedPassword = null; diff --git a/setup/db/create-schema-view.sql b/setup/db/create-schema-view.sql index bf04c1caa57..63f59983249 100644 --- a/setup/db/create-schema-view.sql +++ b/setup/db/create-schema-view.sql @@ -818,4 +818,27 @@ left join data_center on storage_pool.data_center_id = data_center.id left join host_pod_ref on storage_pool.pod_id = host_pod_ref.id left join storage_pool_details on storage_pool_details.pool_id = storage_pool.id and storage_pool_details.value = 'true' left join op_host_capacity on storage_pool.id = op_host_capacity.host_id and op_host_capacity.capacity_type = 3 -left join async_job on async_job.instance_id = storage_pool.id and async_job.instance_type = "StoragePool" and async_job.job_status = 0; \ No newline at end of file +left join async_job on async_job.instance_id = storage_pool.id and async_job.instance_type = "StoragePool" and async_job.job_status = 0; + +DROP VIEW IF EXISTS `cloud`.`disk_offering_view`; +CREATE VIEW disk_offering_view AS +select +disk_offering.id, +disk_offering.uuid, +disk_offering.name, +disk_offering.display_text, +disk_offering.disk_size, +disk_offering.created, +disk_offering.tags, +disk_offering.customized, +disk_offering.removed, +disk_offering.use_local_storage, +disk_offering.system_use, +disk_offering.sort_key, +disk_offering.type, +domain.id domain_id, +domain.uuid domain_uuid, +domain.name domain_name, +domain.path domain_path +from disk_offering +left join domain on disk_offering.domain_id=domain.id; \ No newline at end of file diff --git a/setup/db/db/schema-40to410.sql b/setup/db/db/schema-40to410.sql index a9d168d6eed..9513b20aeda 100644 --- a/setup/db/db/schema-40to410.sql +++ b/setup/db/db/schema-40to410.sql @@ -945,4 +945,28 @@ left join storage_pool_details on storage_pool_details.pool_id = storage_pool.id left join op_host_capacity on storage_pool.id = op_host_capacity.host_id and op_host_capacity.capacity_type = 3 left join async_job on async_job.instance_id = storage_pool.id and async_job.instance_type = "StoragePool" and async_job.job_status = 0; +DROP VIEW IF EXISTS `cloud`.`disk_offering_view`; +CREATE VIEW disk_offering_view AS +select +disk_offering.id, +disk_offering.uuid, +disk_offering.name, +disk_offering.display_text, +disk_offering.disk_size, +disk_offering.created, +disk_offering.tags, +disk_offering.customized, +disk_offering.removed, +disk_offering.use_local_storage, +disk_offering.system_use, +disk_offering.sort_key, +disk_offering.type, +domain.id domain_id, +domain.uuid domain_uuid, +domain.name domain_name, +domain.path domain_path +from disk_offering +left join domain on disk_offering.domain_id=domain.id; + + INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Advanced', 'DEFAULT', 'management-server', 'direct.agent.pool.size', '500', 'Default size for DirectAgentPool'); From a4c413bc13cae8d6060a4bfd58fb2d6a18bebbc7 Mon Sep 17 00:00:00 2001 From: Brian Federle Date: Mon, 21 Jan 2013 14:30:56 -0800 Subject: [PATCH 40/80] CLOUDSTACK-537: Fix for instance wizard When using SG-enabled advanced zone, fix case where 'add guest network' form shows up in select network step -- adding a guest network via the wizard is not supported in this type of setup. --- ui/css/cloudstack3.css | 8 ++++++++ ui/scripts/instanceWizard.js | 8 ++++++++ 2 files changed, 16 insertions(+) diff --git a/ui/css/cloudstack3.css b/ui/css/cloudstack3.css index 58563a6711a..db101d21ec4 100644 --- a/ui/css/cloudstack3.css +++ b/ui/css/cloudstack3.css @@ -5778,6 +5778,10 @@ label.error { height: 223px; } +.multi-wizard.instance-wizard .select-network.no-add-network .select table .select-container { + height: 282px; +} + .multi-wizard.instance-wizard .select-network .select.new-network table .select-container { height: 29px; overflow: visible; @@ -5802,6 +5806,10 @@ label.error { margin: -17px 0 0; } +.multi-wizard.instance-wizard .select-network.no-add-network .select.new-network { + display: none !important; +} + .multi-wizard.instance-wizard .select-network .main-desc { width: 252px; top: 12px; diff --git a/ui/scripts/instanceWizard.js b/ui/scripts/instanceWizard.js index b98147b2056..f3fe6a53991 100644 --- a/ui/scripts/instanceWizard.js +++ b/ui/scripts/instanceWizard.js @@ -284,6 +284,7 @@ $networkStep.find("#from_instance_page_2").show(); $networkStep.find("#from_vpc_tier").text(""); $networkStep.find("#from_vpc_tier").hide(); + $networkStepContainer.removeClass('next-use-security-groups'); } else { // Advanced SG-enabled zone step5ContainerType = 'select-advanced-sg'; } @@ -384,8 +385,15 @@ }); //get network offerings (end) *** + $networkStepContainer.removeClass('repeat next-use-security-groups'); + if (step5ContainerType == 'select-advanced-sg') { $networkStepContainer.addClass('repeat next-use-security-groups'); + + // Add guest network is disabled + $networkStepContainer.find('.select-network').addClass('no-add-network'); + } else { + $networkStepContainer.find('.select-network').removeClass('no-add-network'); } args.response.success({ From 6e40c336287e2c68f763d10e80654d9151ac56b7 Mon Sep 17 00:00:00 2001 From: Min Chen Date: Mon, 21 Jan 2013 15:07:35 -0800 Subject: [PATCH 41/80] CLOUDSTACK-355: create DB view for ServiceOfferingResponse to fix count for ListServiceOfferingsCmd. --- .../com/cloud/server/ManagementService.java | 7 - .../offering/ListServiceOfferingsCmd.java | 15 +- .../apache/cloudstack/query/QueryService.java | 4 + server/src/com/cloud/api/ApiDBUtils.java | 13 + .../src/com/cloud/api/ApiResponseHelper.java | 30 +- server/src/com/cloud/api/ApiServer.java | 2 + .../com/cloud/api/query/QueryManagerImpl.java | 154 +++++++++ .../cloud/api/query/ViewResponseHelper.java | 10 + .../api/query/dao/ServiceOfferingJoinDao.java | 30 ++ .../query/dao/ServiceOfferingJoinDaoImpl.java | 91 +++++ .../api/query/vo/ServiceOfferingJoinVO.java | 311 ++++++++++++++++++ .../DefaultComponentLibrary.java | 2 + .../cloud/server/ManagementServerImpl.java | 217 ------------ setup/db/create-schema-view.sql | 33 +- setup/db/db/schema-40to410.sql | 31 ++ 15 files changed, 685 insertions(+), 265 deletions(-) create mode 100644 server/src/com/cloud/api/query/dao/ServiceOfferingJoinDao.java create mode 100644 server/src/com/cloud/api/query/dao/ServiceOfferingJoinDaoImpl.java create mode 100644 server/src/com/cloud/api/query/vo/ServiceOfferingJoinVO.java diff --git a/api/src/com/cloud/server/ManagementService.java b/api/src/com/cloud/server/ManagementService.java index 99355652a2d..3bc7f934c04 100755 --- a/api/src/com/cloud/server/ManagementService.java +++ b/api/src/com/cloud/server/ManagementService.java @@ -110,13 +110,6 @@ public interface ManagementService { */ Pair, Integer> searchForConfigurations(ListCfgsByCmd c); - /** - * Searches for Service Offerings by the specified search criteria Can search by: "name" - * - * @param cmd - * @return List of ServiceOfferings - */ - List searchForServiceOfferings(ListServiceOfferingsCmd cmd); /** * Searches for Clusters by the specified search criteria diff --git a/api/src/org/apache/cloudstack/api/command/user/offering/ListServiceOfferingsCmd.java b/api/src/org/apache/cloudstack/api/command/user/offering/ListServiceOfferingsCmd.java index 9fad577d8ad..5f773d028f3 100644 --- a/api/src/org/apache/cloudstack/api/command/user/offering/ListServiceOfferingsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/offering/ListServiceOfferingsCmd.java @@ -16,9 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.offering; -import java.util.ArrayList; -import java.util.List; - import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; @@ -29,7 +26,6 @@ import org.apache.cloudstack.api.response.DomainResponse; import org.apache.cloudstack.api.response.ListResponse; import org.apache.cloudstack.api.response.ServiceOfferingResponse; import org.apache.cloudstack.api.response.UserVmResponse; -import com.cloud.offering.ServiceOffering; @APICommand(name = "listServiceOfferings", description="Lists all available service offerings.", responseObject=ServiceOfferingResponse.class) public class ListServiceOfferingsCmd extends BaseListCmd { @@ -102,17 +98,10 @@ public class ListServiceOfferingsCmd extends BaseListCmd { @Override public void execute(){ - List offerings = _mgr.searchForServiceOfferings(this); - ListResponse response = new ListResponse(); - List offeringResponses = new ArrayList(); - for (ServiceOffering offering : offerings) { - ServiceOfferingResponse offeringResponse = _responseGenerator.createServiceOfferingResponse(offering); - offeringResponse.setObjectName("serviceoffering"); - offeringResponses.add(offeringResponse); - } - response.setResponses(offeringResponses); + ListResponse response = _queryService.searchForServiceOfferings(this); response.setResponseName(getCommandName()); this.setResponseObject(response); + } } diff --git a/api/src/org/apache/cloudstack/query/QueryService.java b/api/src/org/apache/cloudstack/query/QueryService.java index f2b0d3232a2..add9d23943c 100644 --- a/api/src/org/apache/cloudstack/query/QueryService.java +++ b/api/src/org/apache/cloudstack/query/QueryService.java @@ -27,6 +27,7 @@ import org.apache.cloudstack.api.command.user.account.ListProjectAccountsCmd; import org.apache.cloudstack.api.command.user.event.ListEventsCmd; import org.apache.cloudstack.api.command.user.job.ListAsyncJobsCmd; import org.apache.cloudstack.api.command.user.offering.ListDiskOfferingsCmd; +import org.apache.cloudstack.api.command.user.offering.ListServiceOfferingsCmd; import org.apache.cloudstack.api.command.user.project.ListProjectInvitationsCmd; import org.apache.cloudstack.api.command.user.project.ListProjectsCmd; import org.apache.cloudstack.api.command.user.securitygroup.ListSecurityGroupsCmd; @@ -47,6 +48,7 @@ import org.apache.cloudstack.api.response.ProjectInvitationResponse; import org.apache.cloudstack.api.response.ProjectResponse; import org.apache.cloudstack.api.response.ResourceTagResponse; import org.apache.cloudstack.api.response.SecurityGroupResponse; +import org.apache.cloudstack.api.response.ServiceOfferingResponse; import org.apache.cloudstack.api.response.StoragePoolResponse; import org.apache.cloudstack.api.response.UserResponse; import org.apache.cloudstack.api.response.UserVmResponse; @@ -96,4 +98,6 @@ public interface QueryService { public ListResponse searchForAsyncJobs(ListAsyncJobsCmd cmd); public ListResponse searchForDiskOfferings(ListDiskOfferingsCmd cmd); + + public ListResponse searchForServiceOfferings(ListServiceOfferingsCmd cmd); } diff --git a/server/src/com/cloud/api/ApiDBUtils.java b/server/src/com/cloud/api/ApiDBUtils.java index 3f2f0bb3a63..9b88664fe2b 100755 --- a/server/src/com/cloud/api/ApiDBUtils.java +++ b/server/src/com/cloud/api/ApiDBUtils.java @@ -36,6 +36,7 @@ import org.apache.cloudstack.api.response.ProjectInvitationResponse; import org.apache.cloudstack.api.response.ProjectResponse; import org.apache.cloudstack.api.response.ResourceTagResponse; import org.apache.cloudstack.api.response.SecurityGroupResponse; +import org.apache.cloudstack.api.response.ServiceOfferingResponse; import org.apache.cloudstack.api.response.StoragePoolResponse; import org.apache.cloudstack.api.response.UserResponse; import org.apache.cloudstack.api.response.UserVmResponse; @@ -52,6 +53,7 @@ import com.cloud.api.query.dao.ProjectInvitationJoinDao; import com.cloud.api.query.dao.ProjectJoinDao; import com.cloud.api.query.dao.ResourceTagJoinDao; import com.cloud.api.query.dao.SecurityGroupJoinDao; +import com.cloud.api.query.dao.ServiceOfferingJoinDao; import com.cloud.api.query.dao.StoragePoolJoinDao; import com.cloud.api.query.dao.UserAccountJoinDao; import com.cloud.api.query.dao.UserVmJoinDao; @@ -68,6 +70,7 @@ import com.cloud.api.query.vo.ProjectInvitationJoinVO; import com.cloud.api.query.vo.ProjectJoinVO; import com.cloud.api.query.vo.ResourceTagJoinVO; import com.cloud.api.query.vo.SecurityGroupJoinVO; +import com.cloud.api.query.vo.ServiceOfferingJoinVO; import com.cloud.api.query.vo.StoragePoolJoinVO; import com.cloud.api.query.vo.UserAccountJoinVO; import com.cloud.api.query.vo.UserVmJoinVO; @@ -338,6 +341,7 @@ public class ApiDBUtils { private static AccountJoinDao _accountJoinDao; private static AsyncJobJoinDao _jobJoinDao; private static DiskOfferingJoinDao _diskOfferingJoinDao; + private static ServiceOfferingJoinDao _srvOfferingJoinDao; private static PhysicalNetworkTrafficTypeDao _physicalNetworkTrafficTypeDao; private static PhysicalNetworkServiceProviderDao _physicalNetworkServiceProviderDao; @@ -443,6 +447,7 @@ public class ApiDBUtils { _snapshotPolicyDao = locator.getDao(SnapshotPolicyDao.class); _asyncJobDao = locator.getDao(AsyncJobDao.class); _diskOfferingJoinDao = locator.getDao(DiskOfferingJoinDao.class); + _srvOfferingJoinDao = locator.getDao(ServiceOfferingJoinDao.class); // Note: stats collector should already have been initialized by this time, otherwise a null instance is returned _statsCollector = StatsCollector.getInstance(); @@ -1413,4 +1418,12 @@ public class ApiDBUtils { public static DiskOfferingJoinVO newDiskOfferingView(DiskOffering offering){ return _diskOfferingJoinDao.newDiskOfferingView(offering); } + + public static ServiceOfferingResponse newServiceOfferingResponse(ServiceOfferingJoinVO offering) { + return _srvOfferingJoinDao.newServiceOfferingResponse(offering); + } + + public static ServiceOfferingJoinVO newServiceOfferingView(ServiceOffering offering){ + return _srvOfferingJoinDao.newServiceOfferingView(offering); + } } diff --git a/server/src/com/cloud/api/ApiResponseHelper.java b/server/src/com/cloud/api/ApiResponseHelper.java index 07646d89497..1965f333f35 100755 --- a/server/src/com/cloud/api/ApiResponseHelper.java +++ b/server/src/com/cloud/api/ApiResponseHelper.java @@ -54,6 +54,7 @@ import com.cloud.api.query.vo.ProjectInvitationJoinVO; import com.cloud.api.query.vo.ProjectJoinVO; import com.cloud.api.query.vo.ResourceTagJoinVO; import com.cloud.api.query.vo.SecurityGroupJoinVO; +import com.cloud.api.query.vo.ServiceOfferingJoinVO; import com.cloud.api.query.vo.StoragePoolJoinVO; import com.cloud.api.query.vo.UserAccountJoinVO; import com.cloud.api.query.vo.UserVmJoinVO; @@ -342,33 +343,8 @@ public class ApiResponseHelper implements ResponseGenerator { @Override public ServiceOfferingResponse createServiceOfferingResponse(ServiceOffering offering) { - ServiceOfferingResponse offeringResponse = new ServiceOfferingResponse(); - offeringResponse.setId(offering.getUuid()); - offeringResponse.setName(offering.getName()); - offeringResponse.setIsSystemOffering(offering.getSystemUse()); - offeringResponse.setDefaultUse(offering.getDefaultUse()); - offeringResponse.setSystemVmType(offering.getSystemVmType()); - offeringResponse.setDisplayText(offering.getDisplayText()); - offeringResponse.setCpuNumber(offering.getCpu()); - offeringResponse.setCpuSpeed(offering.getSpeed()); - offeringResponse.setMemory(offering.getRamSize()); - offeringResponse.setCreated(offering.getCreated()); - offeringResponse.setStorageType(offering.getUseLocalStorage() ? ServiceOffering.StorageType.local.toString() : ServiceOffering.StorageType.shared.toString()); - offeringResponse.setOfferHa(offering.getOfferHA()); - offeringResponse.setLimitCpuUse(offering.getLimitCpuUse()); - offeringResponse.setTags(offering.getTags()); - if (offering.getDomainId() != null) { - Domain domain = ApiDBUtils.findDomainById(offering.getDomainId()); - if (domain != null) { - offeringResponse.setDomain(domain.getName()); - offeringResponse.setDomainId(domain.getUuid()); - } - } - offeringResponse.setNetworkRate(offering.getRateMbps()); - offeringResponse.setHostTag(offering.getHostTag()); - offeringResponse.setObjectName("serviceoffering"); - - return offeringResponse; + ServiceOfferingJoinVO vOffering = ApiDBUtils.newServiceOfferingView(offering); + return ApiDBUtils.newServiceOfferingResponse(vOffering); } @Override diff --git a/server/src/com/cloud/api/ApiServer.java b/server/src/com/cloud/api/ApiServer.java index 19c88514b04..ad2a12f0068 100755 --- a/server/src/com/cloud/api/ApiServer.java +++ b/server/src/com/cloud/api/ApiServer.java @@ -96,6 +96,7 @@ import org.apache.cloudstack.api.command.admin.router.ListRoutersCmd; import org.apache.cloudstack.api.command.admin.storage.ListStoragePoolsCmd; import org.apache.cloudstack.api.command.admin.user.ListUsersCmd; import org.apache.cloudstack.api.command.user.offering.ListDiskOfferingsCmd; +import org.apache.cloudstack.api.command.user.offering.ListServiceOfferingsCmd; import org.apache.cloudstack.api.command.user.project.ListProjectInvitationsCmd; import org.apache.cloudstack.api.command.user.project.ListProjectsCmd; import org.apache.cloudstack.api.command.user.securitygroup.ListSecurityGroupsCmd; @@ -516,6 +517,7 @@ public class ApiServer implements HttpRequestHandler { && !(cmdObj instanceof ListAccountsCmd) && !(cmdObj instanceof ListStoragePoolsCmd) && !(cmdObj instanceof ListDiskOfferingsCmd) + && !(cmdObj instanceof ListServiceOfferingsCmd) ) { buildAsyncListResponse((BaseListCmd) cmdObj, caller); } diff --git a/server/src/com/cloud/api/query/QueryManagerImpl.java b/server/src/com/cloud/api/query/QueryManagerImpl.java index c38603ff3ca..ee472961871 100644 --- a/server/src/com/cloud/api/query/QueryManagerImpl.java +++ b/server/src/com/cloud/api/query/QueryManagerImpl.java @@ -33,6 +33,7 @@ import org.apache.cloudstack.api.command.user.account.ListProjectAccountsCmd; import org.apache.cloudstack.api.command.user.event.ListEventsCmd; import org.apache.cloudstack.api.command.user.job.ListAsyncJobsCmd; import org.apache.cloudstack.api.command.user.offering.ListDiskOfferingsCmd; +import org.apache.cloudstack.api.command.user.offering.ListServiceOfferingsCmd; import org.apache.cloudstack.api.command.user.project.ListProjectInvitationsCmd; import org.apache.cloudstack.api.command.user.project.ListProjectsCmd; import org.apache.cloudstack.api.command.user.securitygroup.ListSecurityGroupsCmd; @@ -53,6 +54,7 @@ import org.apache.cloudstack.api.response.ProjectInvitationResponse; import org.apache.cloudstack.api.response.ProjectResponse; import org.apache.cloudstack.api.response.ResourceTagResponse; import org.apache.cloudstack.api.response.SecurityGroupResponse; +import org.apache.cloudstack.api.response.ServiceOfferingResponse; import org.apache.cloudstack.api.response.StoragePoolResponse; import org.apache.cloudstack.api.response.UserResponse; import org.apache.cloudstack.api.response.UserVmResponse; @@ -71,6 +73,7 @@ import com.cloud.api.query.dao.ProjectInvitationJoinDao; import com.cloud.api.query.dao.ProjectJoinDao; import com.cloud.api.query.dao.ResourceTagJoinDao; import com.cloud.api.query.dao.SecurityGroupJoinDao; +import com.cloud.api.query.dao.ServiceOfferingJoinDao; import com.cloud.api.query.dao.StoragePoolJoinDao; import com.cloud.api.query.dao.UserAccountJoinDao; import com.cloud.api.query.dao.UserVmJoinDao; @@ -87,6 +90,7 @@ import com.cloud.api.query.vo.ProjectInvitationJoinVO; import com.cloud.api.query.vo.ProjectJoinVO; import com.cloud.api.query.vo.ResourceTagJoinVO; import com.cloud.api.query.vo.SecurityGroupJoinVO; +import com.cloud.api.query.vo.ServiceOfferingJoinVO; import com.cloud.api.query.vo.StoragePoolJoinVO; import com.cloud.api.query.vo.UserAccountJoinVO; import com.cloud.api.query.vo.UserVmJoinVO; @@ -110,6 +114,8 @@ import com.cloud.projects.ProjectManager; import com.cloud.projects.dao.ProjectAccountDao; import com.cloud.projects.dao.ProjectDao; import com.cloud.server.Criteria; +import com.cloud.service.ServiceOfferingVO; +import com.cloud.service.dao.ServiceOfferingDao; import com.cloud.storage.DiskOfferingVO; import com.cloud.storage.StoragePool; import com.cloud.storage.StoragePoolVO; @@ -221,6 +227,12 @@ public class QueryManagerImpl implements QueryService, Manager { @Inject private DiskOfferingJoinDao _diskOfferingJoinDao; + @Inject + private ServiceOfferingJoinDao _srvOfferingJoinDao; + + @Inject + private ServiceOfferingDao _srvOfferingDao; + @Inject private HighAvailabilityManager _haMgr; @@ -2033,6 +2045,148 @@ public class QueryManagerImpl implements QueryService, Manager { } + + @Override + public ListResponse searchForServiceOfferings(ListServiceOfferingsCmd cmd) { + Pair, Integer> result = searchForServiceOfferingsInternal(cmd); + ListResponse response = new ListResponse(); + List offeringResponses = ViewResponseHelper.createServiceOfferingResponse(result.first().toArray(new ServiceOfferingJoinVO[result.first().size()])); + response.setResponses(offeringResponses, result.second()); + return response; + } + + private Pair, Integer> searchForServiceOfferingsInternal(ListServiceOfferingsCmd cmd) { + // Note + // The list method for offerings is being modified in accordance with + // discussion with Will/Kevin + // For now, we will be listing the following based on the usertype + // 1. For root, we will list all offerings + // 2. For domainAdmin and regular users, we will list everything in + // their domains+parent domains ... all the way + // till + // root + Boolean isAscending = Boolean.parseBoolean(_configDao.getValue("sortkey.algorithm")); + isAscending = (isAscending == null ? true : isAscending); + Filter searchFilter = new Filter(ServiceOfferingJoinVO.class, "sortKey", isAscending, cmd.getStartIndex(), cmd.getPageSizeVal()); + SearchCriteria sc = _srvOfferingJoinDao.createSearchCriteria(); + + Account caller = UserContext.current().getCaller(); + Object name = cmd.getServiceOfferingName(); + Object id = cmd.getId(); + Object keyword = cmd.getKeyword(); + Long vmId = cmd.getVirtualMachineId(); + Long domainId = cmd.getDomainId(); + Boolean isSystem = cmd.getIsSystem(); + String vmTypeStr = cmd.getSystemVmType(); + + if (caller.getType() != Account.ACCOUNT_TYPE_ADMIN && isSystem) { + throw new InvalidParameterValueException("Only ROOT admins can access system's offering"); + } + + // Keeping this logic consistent with domain specific zones + // if a domainId is provided, we just return the so associated with this + // domain + if (domainId != null && caller.getType() != Account.ACCOUNT_TYPE_ADMIN) { + // check if the user's domain == so's domain || user's domain is a + // child of so's domain + if (!isPermissible(caller.getDomainId(), domainId)) { + throw new PermissionDeniedException("The account:" + caller.getAccountName() + + " does not fall in the same domain hierarchy as the service offering"); + } + } + + boolean includePublicOfferings = false; + if ((caller.getType() == Account.ACCOUNT_TYPE_NORMAL || caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) + || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) { + // For non-root users + if (isSystem) { + throw new InvalidParameterValueException("Only root admins can access system's offering"); + } + // find all domain Id up to root domain for this account + List domainIds = new ArrayList(); + DomainVO domainRecord = _domainDao.findById(caller.getDomainId()); + if ( domainRecord == null ){ + s_logger.error("Could not find the domainId for account:" + caller.getAccountName()); + throw new CloudAuthenticationException("Could not find the domainId for account:" + caller.getAccountName()); + } + domainIds.add(domainRecord.getId()); + while (domainRecord.getParent() != null ){ + domainRecord = _domainDao.findById(domainRecord.getParent()); + domainIds.add(domainRecord.getId()); + } + sc.addAnd("domainIdIn", SearchCriteria.Op.IN, domainIds); + + // include also public offering if no keyword, name and id specified + if ( keyword == null && name == null && id == null ){ + includePublicOfferings = true; + } + } + else { + // for root users + if (caller.getDomainId() != 1 && isSystem) { // NON ROOT admin + throw new InvalidParameterValueException("Non ROOT admins cannot access system's offering"); + } + if (domainId != null) { + sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId); + } + } + + if (keyword != null) { + SearchCriteria ssc = _srvOfferingJoinDao.createSearchCriteria(); + ssc.addOr("displayText", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + + sc.addAnd("name", SearchCriteria.Op.SC, ssc); + } else if (vmId != null) { + UserVmVO vmInstance = _userVmDao.findById(vmId); + if ((vmInstance == null) || (vmInstance.getRemoved() != null)) { + InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a virtual machine with specified id"); + ex.addProxyObject(vmInstance, vmId, "vmId"); + throw ex; + } + + _accountMgr.checkAccess(caller, null, true, vmInstance); + + ServiceOfferingVO offering = _srvOfferingDao.findByIdIncludingRemoved(vmInstance.getServiceOfferingId()); + sc.addAnd("id", SearchCriteria.Op.NEQ, offering.getId()); + + // Only return offerings with the same Guest IP type and storage + // pool preference + // sc.addAnd("guestIpType", SearchCriteria.Op.EQ, + // offering.getGuestIpType()); + sc.addAnd("useLocalStorage", SearchCriteria.Op.EQ, offering.getUseLocalStorage()); + } + + if (id != null) { + sc.addAnd("id", SearchCriteria.Op.EQ, id); + } + + if (isSystem != null) { + sc.addAnd("systemUse", SearchCriteria.Op.EQ, isSystem); + } + + if (name != null) { + sc.addAnd("name", SearchCriteria.Op.LIKE, "%" + name + "%"); + } + + if (vmTypeStr != null) { + sc.addAnd("vm_type", SearchCriteria.Op.EQ, vmTypeStr); + } + + if (includePublicOfferings){ + SearchCriteria spc = _srvOfferingJoinDao.createSearchCriteria(); + spc.addAnd("domainId", SearchCriteria.Op.NULL); + spc.addAnd("systemUse", SearchCriteria.Op.EQ, false); + sc.addOr("systemUse", SearchCriteria.Op.SC, spc); + } + + return _srvOfferingJoinDao.searchAndCount(sc, searchFilter); + + } + + + + // This method is used for permissions check for both disk and service // offerings private boolean isPermissible(Long accountDomainId, Long offeringDomainId) { diff --git a/server/src/com/cloud/api/query/ViewResponseHelper.java b/server/src/com/cloud/api/query/ViewResponseHelper.java index 9c761d4f91c..dfccdceb8d4 100644 --- a/server/src/com/cloud/api/query/ViewResponseHelper.java +++ b/server/src/com/cloud/api/query/ViewResponseHelper.java @@ -35,6 +35,7 @@ import org.apache.cloudstack.api.response.ProjectInvitationResponse; import org.apache.cloudstack.api.response.ProjectResponse; import org.apache.cloudstack.api.response.ResourceTagResponse; import org.apache.cloudstack.api.response.SecurityGroupResponse; +import org.apache.cloudstack.api.response.ServiceOfferingResponse; import org.apache.cloudstack.api.response.StoragePoolResponse; import org.apache.cloudstack.api.response.UserResponse; import org.apache.cloudstack.api.response.UserVmResponse; @@ -54,6 +55,7 @@ import com.cloud.api.query.vo.ProjectInvitationJoinVO; import com.cloud.api.query.vo.ProjectJoinVO; import com.cloud.api.query.vo.ResourceTagJoinVO; import com.cloud.api.query.vo.SecurityGroupJoinVO; +import com.cloud.api.query.vo.ServiceOfferingJoinVO; import com.cloud.api.query.vo.StoragePoolJoinVO; import com.cloud.api.query.vo.UserAccountJoinVO; import com.cloud.api.query.vo.UserVmJoinVO; @@ -284,4 +286,12 @@ public class ViewResponseHelper { } return respList; } + + public static List createServiceOfferingResponse(ServiceOfferingJoinVO... offerings) { + List respList = new ArrayList(); + for (ServiceOfferingJoinVO vt : offerings){ + respList.add(ApiDBUtils.newServiceOfferingResponse(vt)); + } + return respList; + } } diff --git a/server/src/com/cloud/api/query/dao/ServiceOfferingJoinDao.java b/server/src/com/cloud/api/query/dao/ServiceOfferingJoinDao.java new file mode 100644 index 00000000000..a797125a18d --- /dev/null +++ b/server/src/com/cloud/api/query/dao/ServiceOfferingJoinDao.java @@ -0,0 +1,30 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api.query.dao; + +import org.apache.cloudstack.api.response.ServiceOfferingResponse; + +import com.cloud.api.query.vo.ServiceOfferingJoinVO; +import com.cloud.offering.ServiceOffering; +import com.cloud.utils.db.GenericDao; + +public interface ServiceOfferingJoinDao extends GenericDao { + + ServiceOfferingResponse newServiceOfferingResponse(ServiceOfferingJoinVO offering); + + ServiceOfferingJoinVO newServiceOfferingView(ServiceOffering offering); +} diff --git a/server/src/com/cloud/api/query/dao/ServiceOfferingJoinDaoImpl.java b/server/src/com/cloud/api/query/dao/ServiceOfferingJoinDaoImpl.java new file mode 100644 index 00000000000..8827c48bf68 --- /dev/null +++ b/server/src/com/cloud/api/query/dao/ServiceOfferingJoinDaoImpl.java @@ -0,0 +1,91 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api.query.dao; + +import java.util.List; + +import javax.ejb.Local; + +import org.apache.log4j.Logger; + +import com.cloud.api.query.vo.ServiceOfferingJoinVO; +import org.apache.cloudstack.api.response.ServiceOfferingResponse; + +import com.cloud.offering.ServiceOffering; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; + + +@Local(value={ServiceOfferingJoinDao.class}) +public class ServiceOfferingJoinDaoImpl extends GenericDaoBase implements ServiceOfferingJoinDao { + public static final Logger s_logger = Logger.getLogger(ServiceOfferingJoinDaoImpl.class); + + + private SearchBuilder sofIdSearch; + + protected ServiceOfferingJoinDaoImpl() { + + sofIdSearch = createSearchBuilder(); + sofIdSearch.and("id", sofIdSearch.entity().getId(), SearchCriteria.Op.EQ); + sofIdSearch.done(); + + this._count = "select count(distinct id) from service_offering_view WHERE "; + } + + + + @Override + public ServiceOfferingResponse newServiceOfferingResponse(ServiceOfferingJoinVO offering) { + + ServiceOfferingResponse offeringResponse = new ServiceOfferingResponse(); + offeringResponse.setId(offering.getUuid()); + offeringResponse.setName(offering.getName()); + offeringResponse.setIsSystemOffering(offering.isSystemUse()); + offeringResponse.setDefaultUse(offering.isDefaultUse()); + offeringResponse.setSystemVmType(offering.getSystemVmType()); + offeringResponse.setDisplayText(offering.getDisplayText()); + offeringResponse.setCpuNumber(offering.getCpu()); + offeringResponse.setCpuSpeed(offering.getSpeed()); + offeringResponse.setMemory(offering.getRamSize()); + offeringResponse.setCreated(offering.getCreated()); + offeringResponse.setStorageType(offering.isUseLocalStorage() ? ServiceOffering.StorageType.local.toString() + : ServiceOffering.StorageType.shared.toString()); + offeringResponse.setOfferHa(offering.isOfferHA()); + offeringResponse.setLimitCpuUse(offering.isLimitCpuUse()); + offeringResponse.setTags(offering.getTags()); + offeringResponse.setDomain(offering.getDomainName()); + offeringResponse.setDomainId(offering.getDomainUuid()); + offeringResponse.setNetworkRate(offering.getRateMbps()); + offeringResponse.setHostTag(offering.getHostTag()); + offeringResponse.setObjectName("serviceoffering"); + + return offeringResponse; + } + + + @Override + public ServiceOfferingJoinVO newServiceOfferingView(ServiceOffering offering) { + SearchCriteria sc = sofIdSearch.create(); + sc.setParameters("id", offering.getId()); + List offerings = searchIncludingRemoved(sc, null, null, false); + assert offerings != null && offerings.size() == 1 : "No service offering found for offering id " + offering.getId(); + return offerings.get(0); + } + + +} diff --git a/server/src/com/cloud/api/query/vo/ServiceOfferingJoinVO.java b/server/src/com/cloud/api/query/vo/ServiceOfferingJoinVO.java new file mode 100644 index 00000000000..fe4a1658ec8 --- /dev/null +++ b/server/src/com/cloud/api/query/vo/ServiceOfferingJoinVO.java @@ -0,0 +1,311 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api.query.vo; + +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +import com.cloud.utils.db.GenericDao; + +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + +@Entity +@Table(name="service_offering_view") +public class ServiceOfferingJoinVO extends BaseViewVO implements InternalIdentity, Identity { + + @Id + @Column(name="id", updatable=false, nullable = false) + private long id; + + @Column(name="uuid") + private String uuid; + + @Column(name="name") + private String name; + + @Column(name="display_text") + private String displayText; + + @Column(name="tags", length=4096) + String tags; + + @Column(name="use_local_storage") + private boolean useLocalStorage; + + @Column(name="system_use") + private boolean systemUse; + + @Column(name="cpu") + private int cpu; + + @Column(name="speed") + private int speed; + + @Column(name="ram_size") + private int ramSize; + + @Column(name="nw_rate") + private Integer rateMbps; + + @Column(name="mc_rate") + private Integer multicastRateMbps; + + @Column(name="ha_enabled") + private boolean offerHA; + + @Column(name="limit_cpu_use") + private boolean limitCpuUse; + + @Column(name="host_tag") + private String hostTag; + + @Column(name="default_use") + private boolean default_use; + + @Column(name="vm_type") + private String vm_type; + + @Column(name="sort_key") + int sortKey; + + + @Column(name=GenericDao.CREATED_COLUMN) + private Date created; + + @Column(name=GenericDao.REMOVED_COLUMN) + private Date removed; + + @Column(name="domain_id") + private long domainId; + + @Column(name="domain_uuid") + private String domainUuid; + + @Column(name="domain_name") + private String domainName = null; + + @Column(name="domain_path") + private String domainPath = null; + + + public ServiceOfferingJoinVO() { + } + + @Override + public long getId() { + return id; + } + + @Override + public void setId(long id) { + this.id = id; + } + + @Override + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDisplayText() { + return displayText; + } + + public void setDisplayText(String displayText) { + this.displayText = displayText; + } + + + public String getTags() { + return tags; + } + + public void setTags(String tags) { + this.tags = tags; + } + + public boolean isUseLocalStorage() { + return useLocalStorage; + } + + public void setUseLocalStorage(boolean useLocalStorage) { + this.useLocalStorage = useLocalStorage; + } + + public boolean isSystemUse() { + return systemUse; + } + + public void setSystemUse(boolean systemUse) { + this.systemUse = systemUse; + } + + + public Date getCreated() { + return created; + } + + public void setCreated(Date created) { + this.created = created; + } + + public Date getRemoved() { + return removed; + } + + public void setRemoved(Date removed) { + this.removed = removed; + } + + public long getDomainId() { + return domainId; + } + + public void setDomainId(long domainId) { + this.domainId = domainId; + } + + public String getDomainUuid() { + return domainUuid; + } + + public void setDomainUuid(String domainUuid) { + this.domainUuid = domainUuid; + } + + public String getDomainName() { + return domainName; + } + + public void setDomainName(String domainName) { + this.domainName = domainName; + } + + public String getDomainPath() { + return domainPath; + } + + public void setDomainPath(String domainPath) { + this.domainPath = domainPath; + } + + public int getSortKey() { + return sortKey; + } + + public void setSortKey(int sortKey) { + this.sortKey = sortKey; + } + + public int getCpu() { + return cpu; + } + + public void setCpu(int cpu) { + this.cpu = cpu; + } + + public int getSpeed() { + return speed; + } + + public void setSpeed(int speed) { + this.speed = speed; + } + + public int getRamSize() { + return ramSize; + } + + public void setRamSize(int ramSize) { + this.ramSize = ramSize; + } + + public Integer getRateMbps() { + return rateMbps; + } + + public void setRateMbps(Integer rateMbps) { + this.rateMbps = rateMbps; + } + + public Integer getMulticastRateMbps() { + return multicastRateMbps; + } + + public void setMulticastRateMbps(Integer multicastRateMbps) { + this.multicastRateMbps = multicastRateMbps; + } + + public boolean isOfferHA() { + return offerHA; + } + + public void setOfferHA(boolean offerHA) { + this.offerHA = offerHA; + } + + public boolean isLimitCpuUse() { + return limitCpuUse; + } + + public void setLimitCpuUse(boolean limitCpuUse) { + this.limitCpuUse = limitCpuUse; + } + + public String getHostTag() { + return hostTag; + } + + public void setHostTag(String hostTag) { + this.hostTag = hostTag; + } + + public boolean isDefaultUse() { + return default_use; + } + + public void setDefaultUse(boolean default_use) { + this.default_use = default_use; + } + + public String getSystemVmType() { + return vm_type; + } + + public void setSystemVmType(String vm_type) { + this.vm_type = vm_type; + } + + +} diff --git a/server/src/com/cloud/configuration/DefaultComponentLibrary.java b/server/src/com/cloud/configuration/DefaultComponentLibrary.java index 5a1b0026282..9652586124a 100755 --- a/server/src/com/cloud/configuration/DefaultComponentLibrary.java +++ b/server/src/com/cloud/configuration/DefaultComponentLibrary.java @@ -28,6 +28,7 @@ import com.cloud.api.query.QueryManagerImpl; import com.cloud.api.query.dao.AccountJoinDaoImpl; import com.cloud.api.query.dao.AsyncJobJoinDaoImpl; import com.cloud.api.query.dao.DiskOfferingJoinDaoImpl; +import com.cloud.api.query.dao.ServiceOfferingJoinDaoImpl; import com.cloud.api.query.dao.DomainRouterJoinDaoImpl; import com.cloud.api.query.dao.InstanceGroupJoinDaoImpl; import com.cloud.api.query.dao.ProjectAccountJoinDaoImpl; @@ -394,6 +395,7 @@ public class DefaultComponentLibrary extends ComponentLibraryBase implements Com addDao("AsyncJobJoinDao", AsyncJobJoinDaoImpl.class); addDao("StoragePoolJoinDao", StoragePoolJoinDaoImpl.class); addDao("DiskOfferingJoinDao", DiskOfferingJoinDaoImpl.class); + addDao("ServiceOfferingJoinDao", ServiceOfferingJoinDaoImpl.class); } @Override diff --git a/server/src/com/cloud/server/ManagementServerImpl.java b/server/src/com/cloud/server/ManagementServerImpl.java index 0684440b026..8182421bf02 100755 --- a/server/src/com/cloud/server/ManagementServerImpl.java +++ b/server/src/com/cloud/server/ManagementServerImpl.java @@ -54,7 +54,6 @@ import org.apache.cloudstack.api.command.user.guest.ListGuestOsCategoriesCmd; import org.apache.cloudstack.api.command.user.guest.ListGuestOsCmd; import org.apache.cloudstack.api.command.user.iso.ListIsosCmd; import org.apache.cloudstack.api.command.user.iso.UpdateIsoCmd; -import org.apache.cloudstack.api.command.user.offering.ListServiceOfferingsCmd; import org.apache.cloudstack.api.command.user.ssh.ListSSHKeyPairsCmd; import org.apache.cloudstack.api.command.user.ssh.DeleteSSHKeyPairCmd; import org.apache.cloudstack.api.command.user.ssh.RegisterSSHKeyPairCmd; @@ -132,7 +131,6 @@ import com.cloud.event.EventTypes; import com.cloud.event.EventUtils; import com.cloud.event.EventVO; import com.cloud.event.dao.EventDao; -import com.cloud.exception.CloudAuthenticationException; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.OperationTimedoutException; @@ -607,221 +605,6 @@ public class ManagementServerImpl implements ManagementServer { return cal.getTime(); } - // This method is used for permissions check for both disk and service - // offerings - private boolean isPermissible(Long accountDomainId, Long offeringDomainId) { - - if (accountDomainId == offeringDomainId) { - return true; // account and service offering in same domain - } - - DomainVO domainRecord = _domainDao.findById(accountDomainId); - - if (domainRecord != null) { - while (true) { - if (domainRecord.getId() == offeringDomainId) { - return true; - } - - // try and move on to the next domain - if (domainRecord.getParent() != null) { - domainRecord = _domainDao.findById(domainRecord.getParent()); - } else { - break; - } - } - } - - return false; - } - - @Override - public List searchForServiceOfferings(ListServiceOfferingsCmd cmd) { - - // Note - // The list method for offerings is being modified in accordance with - // discussion with Will/Kevin - // For now, we will be listing the following based on the usertype - // 1. For root, we will list all offerings - // 2. For domainAdmin and regular users, we will list everything in - // their domains+parent domains ... all the way - // till - // root - Boolean isAscending = Boolean.parseBoolean(_configDao.getValue("sortkey.algorithm")); - isAscending = (isAscending == null ? true : isAscending); - Filter searchFilter = new Filter(ServiceOfferingVO.class, "sortKey", isAscending, cmd.getStartIndex(), cmd.getPageSizeVal()); - SearchCriteria sc = _offeringsDao.createSearchCriteria(); - - Account caller = UserContext.current().getCaller(); - Object name = cmd.getServiceOfferingName(); - Object id = cmd.getId(); - Object keyword = cmd.getKeyword(); - Long vmId = cmd.getVirtualMachineId(); - Long domainId = cmd.getDomainId(); - Boolean isSystem = cmd.getIsSystem(); - String vmTypeStr = cmd.getSystemVmType(); - - if (caller.getType() != Account.ACCOUNT_TYPE_ADMIN && isSystem) { - throw new InvalidParameterValueException("Only ROOT admins can access system's offering"); - } - - // Keeping this logic consistent with domain specific zones - // if a domainId is provided, we just return the so associated with this - // domain - if (domainId != null && caller.getType() != Account.ACCOUNT_TYPE_ADMIN) { - // check if the user's domain == so's domain || user's domain is a - // child of so's domain - if (!isPermissible(caller.getDomainId(), domainId)) { - throw new PermissionDeniedException("The account:" + caller.getAccountName() - + " does not fall in the same domain hierarchy as the service offering"); - } - } - - // For non-root users - if ((caller.getType() == Account.ACCOUNT_TYPE_NORMAL || caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) - || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) { - if (isSystem) { - throw new InvalidParameterValueException("Only root admins can access system's offering"); - } - return searchServiceOfferingsInternal(caller, name, id, vmId, keyword, searchFilter); - } - - // for root users, the existing flow - if (caller.getDomainId() != 1 && isSystem) { // NON ROOT admin - throw new InvalidParameterValueException("Non ROOT admins cannot access system's offering"); - } - - if (keyword != null) { - SearchCriteria ssc = _offeringsDao.createSearchCriteria(); - ssc.addOr("displayText", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - - sc.addAnd("name", SearchCriteria.Op.SC, ssc); - } else if (vmId != null) { - UserVmVO vmInstance = _userVmDao.findById(vmId); - if ((vmInstance == null) || (vmInstance.getRemoved() != null)) { - InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a virtual machine with specified id"); - ex.addProxyObject(vmInstance, vmId, "vmId"); - throw ex; - } - - _accountMgr.checkAccess(caller, null, true, vmInstance); - - ServiceOfferingVO offering = _offeringsDao.findByIdIncludingRemoved(vmInstance.getServiceOfferingId()); - sc.addAnd("id", SearchCriteria.Op.NEQ, offering.getId()); - - // Only return offerings with the same Guest IP type and storage - // pool preference - // sc.addAnd("guestIpType", SearchCriteria.Op.EQ, - // offering.getGuestIpType()); - sc.addAnd("useLocalStorage", SearchCriteria.Op.EQ, offering.getUseLocalStorage()); - } - if (id != null) { - sc.addAnd("id", SearchCriteria.Op.EQ, id); - } - - if (isSystem != null) { - sc.addAnd("systemUse", SearchCriteria.Op.EQ, isSystem); - } - - if (name != null) { - sc.addAnd("name", SearchCriteria.Op.LIKE, "%" + name + "%"); - } - - if (domainId != null) { - sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId); - } - - if (vmTypeStr != null) { - sc.addAnd("vm_type", SearchCriteria.Op.EQ, vmTypeStr); - } - - sc.addAnd("removed", SearchCriteria.Op.NULL); - return _offeringsDao.search(sc, searchFilter); - - } - - private List searchServiceOfferingsInternal(Account caller, Object name, Object id, Long vmId, Object keyword, - Filter searchFilter) { - - // it was decided to return all offerings for the user's domain, and - // everything above till root (for normal user - // or - // domain admin) - // list all offerings belonging to this domain, and all of its parents - // check the parent, if not null, add offerings for that parent to list - List sol = new ArrayList(); - DomainVO domainRecord = _domainDao.findById(caller.getDomainId()); - boolean includePublicOfferings = true; - if (domainRecord != null) { - while (true) { - if (id != null) { - ServiceOfferingVO so = _offeringsDao.findById((Long) id); - if (so != null) { - sol.add(so); - } - return sol; - } - - SearchCriteria sc = _offeringsDao.createSearchCriteria(); - - if (keyword != null) { - includePublicOfferings = false; - SearchCriteria ssc = _offeringsDao.createSearchCriteria(); - ssc.addOr("displayText", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - - sc.addAnd("name", SearchCriteria.Op.SC, ssc); - } else if (vmId != null) { - UserVmVO vmInstance = _userVmDao.findById(vmId); - if ((vmInstance == null) || (vmInstance.getRemoved() != null)) { - InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a virtual machine with id " + vmId); - ex.addProxyObject(vmInstance, vmId, "vmId"); - throw ex; - } - - _accountMgr.checkAccess(caller, null, false, vmInstance); - - ServiceOfferingVO offering = _offeringsDao.findById(vmInstance.getServiceOfferingId()); - sc.addAnd("id", SearchCriteria.Op.NEQ, offering.getId()); - - sc.addAnd("useLocalStorage", SearchCriteria.Op.EQ, offering.getUseLocalStorage()); - } - - if (name != null) { - includePublicOfferings = false; - sc.addAnd("name", SearchCriteria.Op.LIKE, "%" + name + "%"); - } - sc.addAnd("systemUse", SearchCriteria.Op.EQ, false); - - // for this domain - sc.addAnd("domainId", SearchCriteria.Op.EQ, domainRecord.getId()); - - // don't return removed service offerings - sc.addAnd("removed", SearchCriteria.Op.NULL); - - // search and add for this domain - sol.addAll(_offeringsDao.search(sc, searchFilter)); - - // try and move on to the next domain - if (domainRecord.getParent() != null) { - domainRecord = _domainDao.findById(domainRecord.getParent()); - } else { - break;// now we got all the offerings for this user/dom adm - } - } - } else { - s_logger.error("Could not find the domainId for account:" + caller.getAccountName()); - throw new CloudAuthenticationException("Could not find the domainId for account:" + caller.getAccountName()); - } - - // add all the public offerings to the sol list before returning - if (includePublicOfferings) { - sol.addAll(_offeringsDao.findPublicServiceOfferings()); - } - - return sol; - } @Override public List searchForClusters(long zoneId, Long startIndex, Long pageSizeVal, String hypervisorType) { diff --git a/setup/db/create-schema-view.sql b/setup/db/create-schema-view.sql index 63f59983249..495b6c5cd20 100644 --- a/setup/db/create-schema-view.sql +++ b/setup/db/create-schema-view.sql @@ -841,4 +841,35 @@ domain.uuid domain_uuid, domain.name domain_name, domain.path domain_path from disk_offering -left join domain on disk_offering.domain_id=domain.id; \ No newline at end of file +left join domain on disk_offering.domain_id=domain.id; + +DROP VIEW IF EXISTS `cloud`.`service_offering_view`; +CREATE VIEW service_offering_view AS +select +service_offering.id, +disk_offering.uuid, +disk_offering.name, +disk_offering.display_text, +disk_offering.created, +disk_offering.tags, +disk_offering.removed, +disk_offering.use_local_storage, +disk_offering.system_use, +service_offering.cpu, +service_offering.speed, +service_offering.ram_size, +service_offering.nw_rate, +service_offering.mc_rate, +service_offering.ha_enabled, +service_offering.limit_cpu_use, +service_offering.host_tag, +service_offering.default_use, +service_offering.vm_type, +service_offering.sort_key, +domain.id domain_id, +domain.uuid domain_uuid, +domain.name domain_name, +domain.path domain_path +from service_offering +inner join disk_offering on service_offering.id = disk_offering.id +left join domain on disk_offering.domain_id=domain.id; diff --git a/setup/db/db/schema-40to410.sql b/setup/db/db/schema-40to410.sql index 9513b20aeda..79b7f8fb889 100644 --- a/setup/db/db/schema-40to410.sql +++ b/setup/db/db/schema-40to410.sql @@ -968,5 +968,36 @@ domain.path domain_path from disk_offering left join domain on disk_offering.domain_id=domain.id; +DROP VIEW IF EXISTS `cloud`.`service_offering_view`; +CREATE VIEW service_offering_view AS +select +service_offering.id, +disk_offering.uuid, +disk_offering.name, +disk_offering.display_text, +disk_offering.created, +disk_offering.tags, +disk_offering.removed, +disk_offering.use_local_storage, +disk_offering.system_use, +service_offering.cpu, +service_offering.speed, +service_offering.ram_size, +service_offering.nw_rate, +service_offering.mc_rate, +service_offering.ha_enabled, +service_offering.limit_cpu_use, +service_offering.host_tag, +service_offering.default_use, +service_offering.vm_type, +service_offering.sort_key, +domain.id domain_id, +domain.uuid domain_uuid, +domain.name domain_name, +domain.path domain_path +from service_offering +inner join disk_offering on service_offering.id = disk_offering.id +left join domain on disk_offering.domain_id=domain.id; + INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Advanced', 'DEFAULT', 'management-server', 'direct.agent.pool.size', '500', 'Default size for DirectAgentPool'); From bfdec24de44b4aca47fdf78a22f710157a775701 Mon Sep 17 00:00:00 2001 From: Jessica Wang Date: Mon, 21 Jan 2013 15:52:10 -0800 Subject: [PATCH 42/80] CLOUDSTACK-537: cloudstack UI - Advanced SG-enabled zone - VM Wizard - step 5 - specify canusefordeploy parameter in listNetworks API when populating network list. --- ui/scripts/instanceWizard.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ui/scripts/instanceWizard.js b/ui/scripts/instanceWizard.js index f3fe6a53991..8d064d838a7 100644 --- a/ui/scripts/instanceWizard.js +++ b/ui/scripts/instanceWizard.js @@ -329,7 +329,8 @@ if(step5ContainerType == 'select-network' || step5ContainerType == 'select-advanced-sg') { var defaultNetworkArray = [], optionalNetworkArray = []; var networkData = { - zoneId: args.currentData.zoneid + zoneId: args.currentData.zoneid, + canusefordeploy: true }; // step5ContainerType of Advanced SG-enabled zone is 'select-security-group', so won't come into this block From ff5477d1f13c22c8ab2c1a80a8b87f474274cc01 Mon Sep 17 00:00:00 2001 From: Jessica Wang Date: Mon, 21 Jan 2013 15:53:29 -0800 Subject: [PATCH 43/80] CLOUDSTACK-537: cloudstack UI - Advanced SG-enabled zone - VM Wizard - remove obsolete variable(myNetworks), rename variable sharedNetworks to networkObjs. --- ui/scripts/instanceWizard.js | 15 ++++++--------- ui/scripts/ui-custom/instanceWizard.js | 2 +- 2 files changed, 7 insertions(+), 10 deletions(-) diff --git a/ui/scripts/instanceWizard.js b/ui/scripts/instanceWizard.js index 8d064d838a7..47908c26b80 100644 --- a/ui/scripts/instanceWizard.js +++ b/ui/scripts/instanceWizard.js @@ -399,9 +399,8 @@ args.response.success({ type: 'select-network', - data: { - myNetworks: [], //not used any more - sharedNetworks: networkObjs, + data: { + networkObjs: networkObjs, securityGroups: [], networkOfferings: networkOfferingObjs, vpcs: vpcObjs @@ -432,9 +431,8 @@ }); args.response.success({ type: 'select-security-group', - data: { - myNetworks: [], //not used any more - sharedNetworks: [], + data: { + networkObjs: [], securityGroups: securityGroupArray, networkOfferings: [], vpcs: [] @@ -445,9 +443,8 @@ else if(step5ContainerType == 'nothing-to-select') { args.response.success({ type: 'nothing-to-select', - data: { - myNetworks: [], //not used any more - sharedNetworks: [], + data: { + networkObjs: [], securityGroups: [], networkOfferings: [], vpcs: [] diff --git a/ui/scripts/ui-custom/instanceWizard.js b/ui/scripts/ui-custom/instanceWizard.js index f2cfd9ced53..d1f2507e120 100644 --- a/ui/scripts/ui-custom/instanceWizard.js +++ b/ui/scripts/ui-custom/instanceWizard.js @@ -636,7 +636,7 @@ // My networks $step.find('.my-networks .select-container').append( - makeSelects('my-networks', $.merge(args.data.myNetworks, args.data.sharedNetworks), { + makeSelects('my-networks', args.data.networkObjs, { name: 'name', desc: 'type', id: 'id' From 635ac34d0665a614c67d35dbd2b51b43e9da075d Mon Sep 17 00:00:00 2001 From: Jessica Wang Date: Mon, 21 Jan 2013 16:02:39 -0800 Subject: [PATCH 44/80] CLOUDSTACK-537: cloudstack UI - Advanced SG-enabled zone - VM Wizard - step5 - select network step - desc field - append '(sg)' if a network includes security group service. --- ui/scripts/instanceWizard.js | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/ui/scripts/instanceWizard.js b/ui/scripts/instanceWizard.js index 47908c26b80..8ebee623bf5 100644 --- a/ui/scripts/instanceWizard.js +++ b/ui/scripts/instanceWizard.js @@ -365,6 +365,18 @@ async: false, success: function(json) { networkObjs = json.listnetworksresponse.network ? json.listnetworksresponse.network : []; + + if(networkObjs.length > 0) { + for(var i = 0; i < networkObjs.length; i++) { + var networkObj = networkObjs[i]; + var serviceObjArray = networkObj.service; + for(var k = 0; k < serviceObjArray.length; k++) { + if(serviceObjArray[k].name == "SecurityGroup") { + networkObjs[i].type = networkObjs[i].type + ' (sg)'; + } + } + } + } } }); From b867609df8353994920e9051bc96677f55eccfe3 Mon Sep 17 00:00:00 2001 From: Pranav Saxena Date: Tue, 22 Jan 2013 15:05:32 +0530 Subject: [PATCH 45/80] CLOUDSTACK-1027: Update SSL certificate button should properly reflect it's functionality:Changing the label and adding the title tag --- ui/index.jsp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ui/index.jsp b/ui/index.jsp index 3fe6bad5f4a..5481da80130 100644 --- a/ui/index.jsp +++ b/ui/index.jsp @@ -959,7 +959,7 @@ under the License.
-
+
 
From fe994a6e63d79b9bce9b334ef8dfd2ca8d4cb5d8 Mon Sep 17 00:00:00 2001 From: Pranav Saxena Date: Tue, 22 Jan 2013 15:09:28 +0530 Subject: [PATCH 46/80] CLOUDSTACK-1027: Update SSL certificate button should properly reflect it's functionality:Changing the label and adding the title tag --- client/WEB-INF/classes/resources/messages.properties | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/client/WEB-INF/classes/resources/messages.properties b/client/WEB-INF/classes/resources/messages.properties index 3dc01aa2008..390738fd4cf 100644 --- a/client/WEB-INF/classes/resources/messages.properties +++ b/client/WEB-INF/classes/resources/messages.properties @@ -1359,8 +1359,8 @@ label.type=Type label.unavailable=Unavailable label.unlimited=Unlimited label.untagged=Untagged -label.update.ssl.cert=Update SSL Certificate -label.update.ssl=Update SSL Certificate +label.update.ssl.cert= SSL Certificate +label.update.ssl= SSL Certificate label.updating=Updating label.url=URL label.usage.interface=Usage Interface From 3bac7b8c07b21eaa3a7b244f4d74efa7b4b5b41f Mon Sep 17 00:00:00 2001 From: Hugo Trippaers Date: Tue, 22 Jan 2013 11:00:50 +0100 Subject: [PATCH 47/80] Summary: Fix schema-40to410.sql Applied some formatting Changed invalid comment Added workaround for non existing table vm_template_iso Fix non prefixed table names in views Removed 'use cloud' statement --- setup/db/db/schema-40to410.sql | 1867 ++++++++++++++++++-------------- 1 file changed, 1052 insertions(+), 815 deletions(-) diff --git a/setup/db/db/schema-40to410.sql b/setup/db/db/schema-40to410.sql index 79b7f8fb889..947059e7f94 100644 --- a/setup/db/db/schema-40to410.sql +++ b/setup/db/db/schema-40to410.sql @@ -141,863 +141,1100 @@ UPDATE `cloud`.`conditions` set uuid=id WHERE uuid is NULL; INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Advanced', 'DEFAULT', 'management-server', '"detail.batch.query.size"', '2000', 'Default entity detail batch query size for listing'); ---- DB views for list api --- -use cloud; +-- DB views for list api DROP VIEW IF EXISTS `cloud`.`user_vm_view`; CREATE VIEW `cloud`.`user_vm_view` AS -select -vm_instance.id id, -vm_instance.name name, -user_vm.display_name display_name, -user_vm.user_data user_data, -account.id account_id, -account.uuid account_uuid, -account.account_name account_name, -account.type account_type, -domain.id domain_id, -domain.uuid domain_uuid, -domain.name domain_name, -domain.path domain_path, -projects.id project_id, -projects.uuid project_uuid, -projects.name project_name, -instance_group.id instance_group_id, -instance_group.uuid instance_group_uuid, -instance_group.name instance_group_name, -vm_instance.uuid uuid, -vm_instance.last_host_id last_host_id, -vm_instance.vm_type type, -vm_instance.vnc_password vnc_password, -vm_instance.limit_cpu_use limit_cpu_use, -vm_instance.created created, -vm_instance.state state, -vm_instance.removed removed, -vm_instance.ha_enabled ha_enabled, -vm_instance.hypervisor_type hypervisor_type, -vm_instance.instance_name instance_name, -vm_instance.guest_os_id guest_os_id, -guest_os.uuid guest_os_uuid, -vm_instance.pod_id pod_id, -host_pod_ref.uuid pod_uuid, -vm_instance.private_ip_address private_ip_address, -vm_instance.private_mac_address private_mac_address, -vm_instance.vm_type vm_type, -data_center.id data_center_id, -data_center.uuid data_center_uuid, -data_center.name data_center_name, -data_center.is_security_group_enabled security_group_enabled, -host.id host_id, -host.uuid host_uuid, -host.name host_name, -vm_template.id template_id, -vm_template.uuid template_uuid, -vm_template.name template_name, -vm_template.display_text template_display_text, -vm_template.enable_password password_enabled, -iso.id iso_id, -iso.uuid iso_uuid, -iso.name iso_name, -iso.display_text iso_display_text, -service_offering.id service_offering_id, -disk_offering.uuid service_offering_uuid, -service_offering.cpu cpu, -service_offering.speed speed, -service_offering.ram_size ram_size, -disk_offering.name service_offering_name, -storage_pool.id pool_id, -storage_pool.uuid pool_uuid, -storage_pool.pool_type pool_type, -volumes.id volume_id, -volumes.uuid volume_uuid, -volumes.device_id volume_device_id, -volumes.volume_type volume_type, -security_group.id security_group_id, -security_group.uuid security_group_uuid, -security_group.name security_group_name, -security_group.description security_group_description, -nics.id nic_id, -nics.uuid nic_uuid, -nics.network_id network_id, -nics.ip4_address ip_address, -nics.default_nic is_default_nic, -nics.gateway gateway, -nics.netmask netmask, -nics.mac_address mac_address, -nics.broadcast_uri broadcast_uri, -nics.isolation_uri isolation_uri, -vpc.id vpc_id, -vpc.uuid vpc_uuid, -networks.uuid network_uuid, -networks.traffic_type traffic_type, -networks.guest_type guest_type, -user_ip_address.id public_ip_id, -user_ip_address.uuid public_ip_uuid, -user_ip_address.public_ip_address public_ip_address, -ssh_keypairs.keypair_name keypair_name, -resource_tags.id tag_id, -resource_tags.uuid tag_uuid, -resource_tags.key tag_key, -resource_tags.value tag_value, -resource_tags.domain_id tag_domain_id, -resource_tags.account_id tag_account_id, -resource_tags.resource_id tag_resource_id, -resource_tags.resource_uuid tag_resource_uuid, -resource_tags.resource_type tag_resource_type, -resource_tags.customer tag_customer, -async_job.id job_id, -async_job.uuid job_uuid, -async_job.job_status job_status, -async_job.account_id job_account_id -from user_vm -inner join vm_instance on vm_instance.id = user_vm.id and vm_instance.removed is NULL -inner join account on vm_instance.account_id=account.id -inner join domain on vm_instance.domain_id=domain.id -left join guest_os on vm_instance.guest_os_id = guest_os.id -left join host_pod_ref on vm_instance.pod_id = host_pod_ref.id -left join projects on projects.project_account_id = account.id -left join instance_group_vm_map on vm_instance.id=instance_group_vm_map.instance_id -left join instance_group on instance_group_vm_map.group_id=instance_group.id -left join data_center on vm_instance.data_center_id=data_center.id -left join host on vm_instance.host_id=host.id -left join vm_template on vm_instance.vm_template_id=vm_template.id -left join vm_template iso on iso.id=user_vm.iso_id -left join service_offering on vm_instance.service_offering_id=service_offering.id -left join disk_offering on vm_instance.service_offering_id=disk_offering.id -left join volumes on vm_instance.id=volumes.instance_id -left join storage_pool on volumes.pool_id=storage_pool.id -left join security_group_vm_map on vm_instance.id=security_group_vm_map.instance_id -left join security_group on security_group_vm_map.security_group_id=security_group.id -left join nics on vm_instance.id=nics.instance_id -left join networks on nics.network_id=networks.id -left join vpc on networks.vpc_id = vpc.id -left join user_ip_address on user_ip_address.vm_id=vm_instance.id -left join user_vm_details on user_vm_details.vm_id=vm_instance.id and user_vm_details.name = "SSH.PublicKey" -left join ssh_keypairs on ssh_keypairs.public_key = user_vm_details.value -left join resource_tags on resource_tags.resource_id = vm_instance.id and resource_tags.resource_type = "UserVm" -left join async_job on async_job.instance_id = vm_instance.id and async_job.instance_type = "VirtualMachine" and async_job.job_status = 0; + select + vm_instance.id id, + vm_instance.name name, + user_vm.display_name display_name, + user_vm.user_data user_data, + account.id account_id, + account.uuid account_uuid, + account.account_name account_name, + account.type account_type, + domain.id domain_id, + domain.uuid domain_uuid, + domain.name domain_name, + domain.path domain_path, + projects.id project_id, + projects.uuid project_uuid, + projects.name project_name, + instance_group.id instance_group_id, + instance_group.uuid instance_group_uuid, + instance_group.name instance_group_name, + vm_instance.uuid uuid, + vm_instance.last_host_id last_host_id, + vm_instance.vm_type type, + vm_instance.vnc_password vnc_password, + vm_instance.limit_cpu_use limit_cpu_use, + vm_instance.created created, + vm_instance.state state, + vm_instance.removed removed, + vm_instance.ha_enabled ha_enabled, + vm_instance.hypervisor_type hypervisor_type, + vm_instance.instance_name instance_name, + vm_instance.guest_os_id guest_os_id, + guest_os.uuid guest_os_uuid, + vm_instance.pod_id pod_id, + host_pod_ref.uuid pod_uuid, + vm_instance.private_ip_address private_ip_address, + vm_instance.private_mac_address private_mac_address, + vm_instance.vm_type vm_type, + data_center.id data_center_id, + data_center.uuid data_center_uuid, + data_center.name data_center_name, + data_center.is_security_group_enabled security_group_enabled, + host.id host_id, + host.uuid host_uuid, + host.name host_name, + vm_template.id template_id, + vm_template.uuid template_uuid, + vm_template.name template_name, + vm_template.display_text template_display_text, + vm_template.enable_password password_enabled, +-- iso.id iso_id, +-- iso.uuid iso_uuid, +-- iso.name iso_name, +-- iso.display_text iso_display_text, +-- FIXME workaround + NULL iso_id, + NULL iso_uuid, + NULL iso_name, + NULL iso_display_text, service_offering.id service_offering_id, +-- end of workaround + disk_offering.uuid service_offering_uuid, + service_offering.cpu cpu, + service_offering.speed speed, + service_offering.ram_size ram_size, + disk_offering.name service_offering_name, + storage_pool.id pool_id, + storage_pool.uuid pool_uuid, + storage_pool.pool_type pool_type, + volumes.id volume_id, + volumes.uuid volume_uuid, + volumes.device_id volume_device_id, + volumes.volume_type volume_type, + security_group.id security_group_id, + security_group.uuid security_group_uuid, + security_group.name security_group_name, + security_group.description security_group_description, + nics.id nic_id, + nics.uuid nic_uuid, + nics.network_id network_id, + nics.ip4_address ip_address, + nics.default_nic is_default_nic, + nics.gateway gateway, + nics.netmask netmask, + nics.mac_address mac_address, + nics.broadcast_uri broadcast_uri, + nics.isolation_uri isolation_uri, + vpc.id vpc_id, + vpc.uuid vpc_uuid, + networks.uuid network_uuid, + networks.traffic_type traffic_type, + networks.guest_type guest_type, + user_ip_address.id public_ip_id, + user_ip_address.uuid public_ip_uuid, + user_ip_address.public_ip_address public_ip_address, + ssh_keypairs.keypair_name keypair_name, + resource_tags.id tag_id, + resource_tags.uuid tag_uuid, + resource_tags.key tag_key, + resource_tags.value tag_value, + resource_tags.domain_id tag_domain_id, + resource_tags.account_id tag_account_id, + resource_tags.resource_id tag_resource_id, + resource_tags.resource_uuid tag_resource_uuid, + resource_tags.resource_type tag_resource_type, + resource_tags.customer tag_customer, + async_job.id job_id, + async_job.uuid job_uuid, + async_job.job_status job_status, + async_job.account_id job_account_id + from + `cloud`.`user_vm` + inner join + `cloud`.`vm_instance` ON vm_instance.id = user_vm.id + and vm_instance.removed is NULL + inner join + `cloud`.`account` ON vm_instance.account_id = account.id + inner join + `cloud`.`domain` ON vm_instance.domain_id = domain.id + left join + `cloud`.`guest_os` ON vm_instance.guest_os_id = guest_os.id + left join + `cloud`.`host_pod_ref` ON vm_instance.pod_id = host_pod_ref.id + left join + `cloud`.`projects` ON projects.project_account_id = account.id + left join + `cloud`.`instance_group_vm_map` ON vm_instance.id = instance_group_vm_map.instance_id + left join + `cloud`.`instance_group` ON instance_group_vm_map.group_id = instance_group.id + left join + `cloud`.`data_center` ON vm_instance.data_center_id = data_center.id + left join + `cloud`.`host` ON vm_instance.host_id = host.id + left join + `cloud`.`vm_template` ON vm_instance.vm_template_id = vm_template.id +-- left join +-- `cloud`.`vm_template iso` ON iso.id = user_vm.iso_id + left join + `cloud`.`service_offering` ON vm_instance.service_offering_id = service_offering.id + left join + `cloud`.`disk_offering` ON vm_instance.service_offering_id = disk_offering.id + left join + `cloud`.`volumes` ON vm_instance.id = volumes.instance_id + left join + `cloud`.`storage_pool` ON volumes.pool_id = storage_pool.id + left join + `cloud`.`security_group_vm_map` ON vm_instance.id = security_group_vm_map.instance_id + left join + `cloud`.`security_group` ON security_group_vm_map.security_group_id = security_group.id + left join + `cloud`.`nics` ON vm_instance.id = nics.instance_id + left join + `cloud`.`networks` ON nics.network_id = networks.id + left join + `cloud`.`vpc` ON networks.vpc_id = vpc.id + left join + `cloud`.`user_ip_address` ON user_ip_address.vm_id = vm_instance.id + left join + `cloud`.`user_vm_details` ON user_vm_details.vm_id = vm_instance.id + and user_vm_details.name = 'SSH.PublicKey' + left join + `cloud`.`ssh_keypairs` ON ssh_keypairs.public_key = user_vm_details.value + left join + `cloud`.`resource_tags` ON resource_tags.resource_id = vm_instance.id + and resource_tags.resource_type = 'UserVm' + left join + `cloud`.`async_job` ON async_job.instance_id = vm_instance.id + and async_job.instance_type = 'VirtualMachine' + and async_job.job_status = 0; DROP VIEW IF EXISTS `cloud`.`domain_router_view`; -CREATE VIEW domain_router_view AS -select -vm_instance.id id, -vm_instance.name name, -account.id account_id, -account.uuid account_uuid, -account.account_name account_name, -account.type account_type, -domain.id domain_id, -domain.uuid domain_uuid, -domain.name domain_name, -domain.path domain_path, -projects.id project_id, -projects.uuid project_uuid, -projects.name project_name, -vm_instance.uuid uuid, -vm_instance.created created, -vm_instance.state state, -vm_instance.removed removed, -vm_instance.pod_id pod_id, -vm_instance.instance_name instance_name, -host_pod_ref.uuid pod_uuid, -data_center.id data_center_id, -data_center.uuid data_center_uuid, -data_center.name data_center_name, -data_center.dns1 dns1, -data_center.dns2 dns2, -host.id host_id, -host.uuid host_uuid, -host.name host_name, -vm_template.id template_id, -vm_template.uuid template_uuid, -service_offering.id service_offering_id, -disk_offering.uuid service_offering_uuid, -disk_offering.name service_offering_name, -nics.id nic_id, -nics.uuid nic_uuid, -nics.network_id network_id, -nics.ip4_address ip_address, -nics.default_nic is_default_nic, -nics.gateway gateway, -nics.netmask netmask, -nics.mac_address mac_address, -nics.broadcast_uri broadcast_uri, -nics.isolation_uri isolation_uri, -vpc.id vpc_id, -vpc.uuid vpc_uuid, -networks.uuid network_uuid, -networks.name network_name, -networks.network_domain network_domain, -networks.traffic_type traffic_type, -networks.guest_type guest_type, -async_job.id job_id, -async_job.uuid job_uuid, -async_job.job_status job_status, -async_job.account_id job_account_id, -domain_router.template_version template_version, -domain_router.scripts_version scripts_version, -domain_router.is_redundant_router is_redundant_router, -domain_router.redundant_state redundant_state, -domain_router.stop_pending stop_pending -from domain_router -inner join vm_instance on vm_instance.id = domain_router.id -inner join account on vm_instance.account_id=account.id -inner join domain on vm_instance.domain_id=domain.id -left join host_pod_ref on vm_instance.pod_id = host_pod_ref.id -left join projects on projects.project_account_id = account.id -left join data_center on vm_instance.data_center_id=data_center.id -left join host on vm_instance.host_id=host.id -left join vm_template on vm_instance.vm_template_id=vm_template.id -left join service_offering on vm_instance.service_offering_id=service_offering.id -left join disk_offering on vm_instance.service_offering_id=disk_offering.id -left join volumes on vm_instance.id=volumes.instance_id -left join storage_pool on volumes.pool_id=storage_pool.id -left join nics on vm_instance.id=nics.instance_id -left join networks on nics.network_id=networks.id -left join vpc on networks.vpc_id = vpc.id -left join async_job on async_job.instance_id = vm_instance.id and async_job.instance_type = "DomainRouter" and async_job.job_status = 0; +CREATE VIEW `cloud`.`domain_router_view` AS + select + vm_instance.id id, + vm_instance.name name, + account.id account_id, + account.uuid account_uuid, + account.account_name account_name, + account.type account_type, + domain.id domain_id, + domain.uuid domain_uuid, + domain.name domain_name, + domain.path domain_path, + projects.id project_id, + projects.uuid project_uuid, + projects.name project_name, + vm_instance.uuid uuid, + vm_instance.created created, + vm_instance.state state, + vm_instance.removed removed, + vm_instance.pod_id pod_id, + vm_instance.instance_name instance_name, + host_pod_ref.uuid pod_uuid, + data_center.id data_center_id, + data_center.uuid data_center_uuid, + data_center.name data_center_name, + data_center.dns1 dns1, + data_center.dns2 dns2, + host.id host_id, + host.uuid host_uuid, + host.name host_name, + vm_template.id template_id, + vm_template.uuid template_uuid, + service_offering.id service_offering_id, + disk_offering.uuid service_offering_uuid, + disk_offering.name service_offering_name, + nics.id nic_id, + nics.uuid nic_uuid, + nics.network_id network_id, + nics.ip4_address ip_address, + nics.default_nic is_default_nic, + nics.gateway gateway, + nics.netmask netmask, + nics.mac_address mac_address, + nics.broadcast_uri broadcast_uri, + nics.isolation_uri isolation_uri, + vpc.id vpc_id, + vpc.uuid vpc_uuid, + networks.uuid network_uuid, + networks.name network_name, + networks.network_domain network_domain, + networks.traffic_type traffic_type, + networks.guest_type guest_type, + async_job.id job_id, + async_job.uuid job_uuid, + async_job.job_status job_status, + async_job.account_id job_account_id, + domain_router.template_version template_version, + domain_router.scripts_version scripts_version, + domain_router.is_redundant_router is_redundant_router, + domain_router.redundant_state redundant_state, + domain_router.stop_pending stop_pending + from + `cloud`.`domain_router` + inner join + `cloud`.`vm_instance` ON vm_instance.id = domain_router.id + inner join + `cloud`.`account` ON vm_instance.account_id = account.id + inner join + `cloud`.`domain` ON vm_instance.domain_id = domain.id + left join + `cloud`.`host_pod_ref` ON vm_instance.pod_id = host_pod_ref.id + left join + `cloud`.`projects` ON projects.project_account_id = account.id + left join + `cloud`.`data_center` ON vm_instance.data_center_id = data_center.id + left join + `cloud`.`host` ON vm_instance.host_id = host.id + left join + `cloud`.`vm_template` ON vm_instance.vm_template_id = vm_template.id + left join + `cloud`.`service_offering` ON vm_instance.service_offering_id = service_offering.id + left join + `cloud`.`disk_offering` ON vm_instance.service_offering_id = disk_offering.id + left join + `cloud`.`volumes` ON vm_instance.id = volumes.instance_id + left join + `cloud`.`storage_pool` ON volumes.pool_id = storage_pool.id + left join + `cloud`.`nics` ON vm_instance.id = nics.instance_id + left join + `cloud`.`networks` ON nics.network_id = networks.id + left join + `cloud`.`vpc` ON networks.vpc_id = vpc.id + left join + `cloud`.`async_job` ON async_job.instance_id = vm_instance.id + and async_job.instance_type = 'DomainRouter' + and async_job.job_status = 0; DROP VIEW IF EXISTS `cloud`.`security_group_view`; -CREATE VIEW security_group_view AS -select -security_group.id id, -security_group.name name, -security_group.description description, -security_group.uuid uuid, -account.id account_id, -account.uuid account_uuid, -account.account_name account_name, -account.type account_type, -domain.id domain_id, -domain.uuid domain_uuid, -domain.name domain_name, -domain.path domain_path, -projects.id project_id, -projects.uuid project_uuid, -projects.name project_name, -security_group_rule.id rule_id, -security_group_rule.uuid rule_uuid, -security_group_rule.type rule_type, -security_group_rule.start_port rule_start_port, -security_group_rule.end_port rule_end_port, -security_group_rule.protocol rule_protocol, -security_group_rule.allowed_network_id rule_allowed_network_id, -security_group_rule.allowed_ip_cidr rule_allowed_ip_cidr, -security_group_rule.create_status rule_create_status, -resource_tags.id tag_id, -resource_tags.uuid tag_uuid, -resource_tags.key tag_key, -resource_tags.value tag_value, -resource_tags.domain_id tag_domain_id, -resource_tags.account_id tag_account_id, -resource_tags.resource_id tag_resource_id, -resource_tags.resource_uuid tag_resource_uuid, -resource_tags.resource_type tag_resource_type, -resource_tags.customer tag_customer, -async_job.id job_id, -async_job.uuid job_uuid, -async_job.job_status job_status, -async_job.account_id job_account_id -from security_group -left join security_group_rule on security_group.id = security_group_rule.security_group_id -inner join account on security_group.account_id=account.id -inner join domain on security_group.domain_id=domain.id -left join projects on projects.project_account_id = security_group.account_id -left join resource_tags on resource_tags.resource_id = security_group.id and resource_tags.resource_type = "SecurityGroup" -left join async_job on async_job.instance_id = security_group.id and async_job.instance_type = "SecurityGroup" and async_job.job_status = 0; +CREATE VIEW `cloud`.`security_group_view` AS + select + security_group.id id, + security_group.name name, + security_group.description description, + security_group.uuid uuid, + account.id account_id, + account.uuid account_uuid, + account.account_name account_name, + account.type account_type, + domain.id domain_id, + domain.uuid domain_uuid, + domain.name domain_name, + domain.path domain_path, + projects.id project_id, + projects.uuid project_uuid, + projects.name project_name, + security_group_rule.id rule_id, + security_group_rule.uuid rule_uuid, + security_group_rule.type rule_type, + security_group_rule.start_port rule_start_port, + security_group_rule.end_port rule_end_port, + security_group_rule.protocol rule_protocol, + security_group_rule.allowed_network_id rule_allowed_network_id, + security_group_rule.allowed_ip_cidr rule_allowed_ip_cidr, + security_group_rule.create_status rule_create_status, + resource_tags.id tag_id, + resource_tags.uuid tag_uuid, + resource_tags.key tag_key, + resource_tags.value tag_value, + resource_tags.domain_id tag_domain_id, + resource_tags.account_id tag_account_id, + resource_tags.resource_id tag_resource_id, + resource_tags.resource_uuid tag_resource_uuid, + resource_tags.resource_type tag_resource_type, + resource_tags.customer tag_customer, + async_job.id job_id, + async_job.uuid job_uuid, + async_job.job_status job_status, + async_job.account_id job_account_id + from + `cloud`.`security_group` + left join + `cloud`.`security_group_rule` ON security_group.id = security_group_rule.security_group_id + inner join + `cloud`.`account` ON security_group.account_id = account.id + inner join + `cloud`.`domain` ON security_group.domain_id = domain.id + left join + `cloud`.`projects` ON projects.project_account_id = security_group.account_id + left join + `cloud`.`resource_tags` ON resource_tags.resource_id = security_group.id + and resource_tags.resource_type = 'SecurityGroup' + left join + `cloud`.`async_job` ON async_job.instance_id = security_group.id + and async_job.instance_type = 'SecurityGroup' + and async_job.job_status = 0; DROP VIEW IF EXISTS `cloud`.`resource_tag_view`; -CREATE VIEW resource_tag_view AS -select -resource_tags.id, -resource_tags.uuid, -resource_tags.key, -resource_tags.value, -resource_tags.resource_id, -resource_tags.resource_uuid, -resource_tags.resource_type, -resource_tags.customer, -account.id account_id, -account.uuid account_uuid, -account.account_name account_name, -account.type account_type, -domain.id domain_id, -domain.uuid domain_uuid, -domain.name domain_name, -domain.path domain_path, -projects.id project_id, -projects.uuid project_uuid, -projects.name project_name -from resource_tags -inner join account on resource_tags.account_id=account.id -inner join domain on resource_tags.domain_id=domain.id -left join projects on projects.project_account_id = resource_tags.account_id; +CREATE VIEW `cloud`.`resource_tag_view` AS + select + resource_tags.id, + resource_tags.uuid, + resource_tags.key, + resource_tags.value, + resource_tags.resource_id, + resource_tags.resource_uuid, + resource_tags.resource_type, + resource_tags.customer, + account.id account_id, + account.uuid account_uuid, + account.account_name account_name, + account.type account_type, + domain.id domain_id, + domain.uuid domain_uuid, + domain.name domain_name, + domain.path domain_path, + projects.id project_id, + projects.uuid project_uuid, + projects.name project_name + from + `cloud`.`resource_tags` + inner join + `cloud`.`account` ON resource_tags.account_id = account.id + inner join + `cloud`.`domain` ON resource_tags.domain_id = domain.id + left join + `cloud`.`projects` ON projects.project_account_id = resource_tags.account_id; DROP VIEW IF EXISTS `cloud`.`event_view`; -CREATE VIEW event_view AS -select -event.id, -event.uuid, -event.type, -event.state, -event.description, -event.created, -event.level, -event.parameters, -event.start_id, -eve.uuid start_uuid, -event.user_id, -user.username user_name, -account.id account_id, -account.uuid account_uuid, -account.account_name account_name, -account.type account_type, -domain.id domain_id, -domain.uuid domain_uuid, -domain.name domain_name, -domain.path domain_path, -projects.id project_id, -projects.uuid project_uuid, -projects.name project_name -from event -inner join account on event.account_id=account.id -inner join domain on event.domain_id=domain.id -inner join user on event.user_id = user.id -left join projects on projects.project_account_id = event.account_id -left join event eve on event.start_id = eve.id; +CREATE VIEW `cloud`.`event_view` AS + select + event.id, + event.uuid, + event.type, + event.state, + event.description, + event.created, + event.level, + event.parameters, + event.start_id, + eve.uuid start_uuid, + event.user_id, + user.username user_name, + account.id account_id, + account.uuid account_uuid, + account.account_name account_name, + account.type account_type, + domain.id domain_id, + domain.uuid domain_uuid, + domain.name domain_name, + domain.path domain_path, + projects.id project_id, + projects.uuid project_uuid, + projects.name project_name + from + `cloud`.`event` + inner join + `cloud`.`account` ON event.account_id = account.id + inner join + `cloud`.`domain` ON event.domain_id = domain.id + inner join + `cloud`.`user` ON event.user_id = user.id + left join + `cloud`.`projects` ON projects.project_account_id = event.account_id + left join + `cloud`.`event` eve ON event.start_id = eve.id; DROP VIEW IF EXISTS `cloud`.`instance_group_view`; -CREATE VIEW instance_group_view AS -select -instance_group.id, -instance_group.uuid, -instance_group.name, -instance_group.removed, -instance_group.created, -account.id account_id, -account.uuid account_uuid, -account.account_name account_name, -account.type account_type, -domain.id domain_id, -domain.uuid domain_uuid, -domain.name domain_name, -domain.path domain_path, -projects.id project_id, -projects.uuid project_uuid, -projects.name project_name -from instance_group -inner join account on instance_group.account_id=account.id -inner join domain on account.domain_id=domain.id -left join projects on projects.project_account_id = instance_group.account_id; +CREATE VIEW `cloud`.`instance_group_view` AS + select + instance_group.id, + instance_group.uuid, + instance_group.name, + instance_group.removed, + instance_group.created, + account.id account_id, + account.uuid account_uuid, + account.account_name account_name, + account.type account_type, + domain.id domain_id, + domain.uuid domain_uuid, + domain.name domain_name, + domain.path domain_path, + projects.id project_id, + projects.uuid project_uuid, + projects.name project_name + from + `cloud`.`instance_group` + inner join + `cloud`.`account` ON instance_group.account_id = account.id + inner join + `cloud`.`domain` ON account.domain_id = domain.id + left join + `cloud`.`projects` ON projects.project_account_id = instance_group.account_id; DROP VIEW IF EXISTS `cloud`.`user_view`; -CREATE VIEW user_view AS -select -user.id, -user.uuid, -user.username, -user.password, -user.firstname, -user.lastname, -user.email, -user.state, -user.api_key, -user.secret_key, -user.created, -user.removed, -user.timezone, -user.registration_token, -user.is_registered, -user.incorrect_login_attempts, -account.id account_id, -account.uuid account_uuid, -account.account_name account_name, -account.type account_type, -domain.id domain_id, -domain.uuid domain_uuid, -domain.name domain_name, -domain.path domain_path, -async_job.id job_id, -async_job.uuid job_uuid, -async_job.job_status job_status, -async_job.account_id job_account_id -from user -inner join account on user.account_id = account.id -inner join domain on account.domain_id=domain.id -left join async_job on async_job.instance_id = user.id and async_job.instance_type = "User" and async_job.job_status = 0; +CREATE VIEW `cloud`.`user_view` AS + select + user.id, + user.uuid, + user.username, + user.password, + user.firstname, + user.lastname, + user.email, + user.state, + user.api_key, + user.secret_key, + user.created, + user.removed, + user.timezone, + user.registration_token, + user.is_registered, + user.incorrect_login_attempts, + account.id account_id, + account.uuid account_uuid, + account.account_name account_name, + account.type account_type, + domain.id domain_id, + domain.uuid domain_uuid, + domain.name domain_name, + domain.path domain_path, + async_job.id job_id, + async_job.uuid job_uuid, + async_job.job_status job_status, + async_job.account_id job_account_id + from + `cloud`.`user` + inner join + `cloud`.`account` ON user.account_id = account.id + inner join + `cloud`.`domain` ON account.domain_id = domain.id + left join + `cloud`.`async_job` ON async_job.instance_id = user.id + and async_job.instance_type = 'User' + and async_job.job_status = 0; DROP VIEW IF EXISTS `cloud`.`project_view`; -CREATE VIEW project_view AS -select -projects.id, -projects.uuid, -projects.name, -projects.display_text, -projects.state, -projects.removed, -projects.created, -account.account_name owner, -pacct.account_id, -domain.id domain_id, -domain.uuid domain_uuid, -domain.name domain_name, -domain.path domain_path, -resource_tags.id tag_id, -resource_tags.uuid tag_uuid, -resource_tags.key tag_key, -resource_tags.value tag_value, -resource_tags.domain_id tag_domain_id, -resource_tags.account_id tag_account_id, -resource_tags.resource_id tag_resource_id, -resource_tags.resource_uuid tag_resource_uuid, -resource_tags.resource_type tag_resource_type, -resource_tags.customer tag_customer -from projects -inner join domain on projects.domain_id=domain.id -inner join project_account on projects.id = project_account.project_id and project_account.account_role = "Admin" -inner join account on account.id = project_account.account_id -left join resource_tags on resource_tags.resource_id = projects.id and resource_tags.resource_type = "Project" -left join project_account pacct on projects.id = pacct.project_id; +CREATE VIEW `cloud`.`project_view` AS + select + projects.id, + projects.uuid, + projects.name, + projects.display_text, + projects.state, + projects.removed, + projects.created, + account.account_name owner, + pacct.account_id, + domain.id domain_id, + domain.uuid domain_uuid, + domain.name domain_name, + domain.path domain_path, + resource_tags.id tag_id, + resource_tags.uuid tag_uuid, + resource_tags.key tag_key, + resource_tags.value tag_value, + resource_tags.domain_id tag_domain_id, + resource_tags.account_id tag_account_id, + resource_tags.resource_id tag_resource_id, + resource_tags.resource_uuid tag_resource_uuid, + resource_tags.resource_type tag_resource_type, + resource_tags.customer tag_customer + from + `cloud`.`projects` + inner join + `cloud`.`domain` ON projects.domain_id = domain.id + inner join + `cloud`.`project_account` ON projects.id = project_account.project_id + and project_account.account_role = 'Admin' + inner join + `cloud`.`account` ON account.id = project_account.account_id + left join + `cloud`.`resource_tags` ON resource_tags.resource_id = projects.id + and resource_tags.resource_type = 'Project' + left join + `cloud`.`project_account` pacct ON projects.id = pacct.project_id; DROP VIEW IF EXISTS `cloud`.`project_account_view`; -CREATE VIEW project_account_view AS -select -project_account.id, -account.id account_id, -account.uuid account_uuid, -account.account_name, -account.type account_type, -project_account.account_role, -projects.id project_id, -projects.uuid project_uuid, -projects.name project_name, -domain.id domain_id, -domain.uuid domain_uuid, -domain.name domain_name, -domain.path domain_path -from project_account -inner join account on project_account.account_id = account.id -inner join domain on account.domain_id=domain.id -inner join projects on projects.id = project_account.project_id; +CREATE VIEW `cloud`.`project_account_view` AS + select + project_account.id, + account.id account_id, + account.uuid account_uuid, + account.account_name, + account.type account_type, + project_account.account_role, + projects.id project_id, + projects.uuid project_uuid, + projects.name project_name, + domain.id domain_id, + domain.uuid domain_uuid, + domain.name domain_name, + domain.path domain_path + from + `cloud`.`project_account` + inner join + `cloud`.`account` ON project_account.account_id = account.id + inner join + `cloud`.`domain` ON account.domain_id = domain.id + inner join + `cloud`.`projects` ON projects.id = project_account.project_id; DROP VIEW IF EXISTS `cloud`.`project_invitation_view`; -CREATE VIEW project_invitation_view AS -select -project_invitations.id, -project_invitations.uuid, -project_invitations.email, -project_invitations.created, -project_invitations.state, -projects.id project_id, -projects.uuid project_uuid, -projects.name project_name, -account.id account_id, -account.uuid account_uuid, -account.account_name, -account.type account_type, -domain.id domain_id, -domain.uuid domain_uuid, -domain.name domain_name, -domain.path domain_path -from project_invitations -left join account on project_invitations.account_id = account.id -left join domain on project_invitations.domain_id=domain.id -left join projects on projects.id = project_invitations.project_id; +CREATE VIEW `cloud`.`project_invitation_view` AS + select + project_invitations.id, + project_invitations.uuid, + project_invitations.email, + project_invitations.created, + project_invitations.state, + projects.id project_id, + projects.uuid project_uuid, + projects.name project_name, + account.id account_id, + account.uuid account_uuid, + account.account_name, + account.type account_type, + domain.id domain_id, + domain.uuid domain_uuid, + domain.name domain_name, + domain.path domain_path + from + `cloud`.`project_invitations` + left join + `cloud`.`account` ON project_invitations.account_id = account.id + left join + `cloud`.`domain` ON project_invitations.domain_id = domain.id + left join + `cloud`.`projects` ON projects.id = project_invitations.project_id; DROP VIEW IF EXISTS `cloud`.`host_view`; -CREATE VIEW host_view AS -select -host.id, -host.uuid, -host.name, -host.status, -host.disconnected, -host.type, -host.private_ip_address, -host.version, -host.hypervisor_type, -host.hypervisor_version, -host.capabilities, -host.last_ping, -host.created, -host.removed, -host.resource_state, -host.mgmt_server_id, -host.cpus, -host.speed, -host.ram, -cluster.id cluster_id, -cluster.uuid cluster_uuid, -cluster.name cluster_name, -cluster.cluster_type, -data_center.id data_center_id, -data_center.uuid data_center_uuid, -data_center.name data_center_name, -host_pod_ref.id pod_id, -host_pod_ref.uuid pod_uuid, -host_pod_ref.name pod_name, -host_tags.tag, -guest_os_category.id guest_os_category_id, -guest_os_category.uuid guest_os_category_uuid, -guest_os_category.name guest_os_category_name, -mem_caps.used_capacity memory_used_capacity, -mem_caps.reserved_capacity memory_reserved_capacity, -cpu_caps.used_capacity cpu_used_capacity, -cpu_caps.reserved_capacity cpu_reserved_capacity, -async_job.id job_id, -async_job.uuid job_uuid, -async_job.job_status job_status, -async_job.account_id job_account_id -from host -left join cluster on host.cluster_id = cluster.id -left join data_center on host.data_center_id = data_center.id -left join host_pod_ref on host.pod_id = host_pod_ref.id -left join host_details on host.id = host_details.id and host_details.name = "guest.os.category.id" -left join guest_os_category on guest_os_category.id = CONVERT( host_details.value, UNSIGNED ) -left join host_tags on host_tags.host_id = host.id -left join op_host_capacity mem_caps on host.id = mem_caps.host_id and mem_caps.capacity_type = 0 -left join op_host_capacity cpu_caps on host.id = cpu_caps.host_id and cpu_caps.capacity_type = 1 -left join async_job on async_job.instance_id = host.id and async_job.instance_type = "Host" and async_job.job_status = 0; +CREATE VIEW `cloud`.`host_view` AS + select + host.id, + host.uuid, + host.name, + host.status, + host.disconnected, + host.type, + host.private_ip_address, + host.version, + host.hypervisor_type, + host.hypervisor_version, + host.capabilities, + host.last_ping, + host.created, + host.removed, + host.resource_state, + host.mgmt_server_id, + host.cpus, + host.speed, + host.ram, + cluster.id cluster_id, + cluster.uuid cluster_uuid, + cluster.name cluster_name, + cluster.cluster_type, + data_center.id data_center_id, + data_center.uuid data_center_uuid, + data_center.name data_center_name, + host_pod_ref.id pod_id, + host_pod_ref.uuid pod_uuid, + host_pod_ref.name pod_name, + host_tags.tag, + guest_os_category.id guest_os_category_id, + guest_os_category.uuid guest_os_category_uuid, + guest_os_category.name guest_os_category_name, + mem_caps.used_capacity memory_used_capacity, + mem_caps.reserved_capacity memory_reserved_capacity, + cpu_caps.used_capacity cpu_used_capacity, + cpu_caps.reserved_capacity cpu_reserved_capacity, + async_job.id job_id, + async_job.uuid job_uuid, + async_job.job_status job_status, + async_job.account_id job_account_id + from + `cloud`.`host` + left join + `cloud`.`cluster` ON host.cluster_id = cluster.id + left join + `cloud`.`data_center` ON host.data_center_id = data_center.id + left join + `cloud`.`host_pod_ref` ON host.pod_id = host_pod_ref.id + left join + `cloud`.`host_details` ON host.id = host_details.id + and host_details.name = 'guest.os.category.id' + left join + `cloud`.`guest_os_category` ON guest_os_category.id = CONVERT( host_details.value , UNSIGNED) + left join + `cloud`.`host_tags` ON host_tags.host_id = host.id + left join + `cloud`.`op_host_capacity` mem_caps ON host.id = mem_caps.host_id + and mem_caps.capacity_type = 0 + left join + `cloud`.`op_host_capacity` cpu_caps ON host.id = cpu_caps.host_id + and cpu_caps.capacity_type = 1 + left join + `cloud`.`async_job` ON async_job.instance_id = host.id + and async_job.instance_type = 'Host' + and async_job.job_status = 0; DROP VIEW IF EXISTS `cloud`.`volume_view`; -CREATE VIEW volume_view AS -select -volumes.id, -volumes.uuid, -volumes.name, -volumes.device_id, -volumes.volume_type, -volumes.size, -volumes.created, -volumes.state, -volumes.attached, -volumes.removed, -volumes.pod_id, -account.id account_id, -account.uuid account_uuid, -account.account_name account_name, -account.type account_type, -domain.id domain_id, -domain.uuid domain_uuid, -domain.name domain_name, -domain.path domain_path, -projects.id project_id, -projects.uuid project_uuid, -projects.name project_name, -data_center.id data_center_id, -data_center.uuid data_center_uuid, -data_center.name data_center_name, -vm_instance.id vm_id, -vm_instance.uuid vm_uuid, -vm_instance.name vm_name, -vm_instance.state vm_state, -vm_instance.vm_type, -user_vm.display_name vm_display_name, -volume_host_ref.size volume_host_size, -volume_host_ref.created volume_host_created, -volume_host_ref.format, -volume_host_ref.download_pct, -volume_host_ref.download_state, -volume_host_ref.error_str, -disk_offering.id disk_offering_id, -disk_offering.uuid disk_offering_uuid, -disk_offering.name disk_offering_name, -disk_offering.display_text disk_offering_display_text, -disk_offering.use_local_storage, -disk_offering.system_use, -storage_pool.id pool_id, -storage_pool.uuid pool_uuid, -storage_pool.name pool_name, -cluster.hypervisor_type, -vm_template.id template_id, -vm_template.uuid template_uuid, -vm_template.extractable, -vm_template.type template_type, -resource_tags.id tag_id, -resource_tags.uuid tag_uuid, -resource_tags.key tag_key, -resource_tags.value tag_value, -resource_tags.domain_id tag_domain_id, -resource_tags.account_id tag_account_id, -resource_tags.resource_id tag_resource_id, -resource_tags.resource_uuid tag_resource_uuid, -resource_tags.resource_type tag_resource_type, -resource_tags.customer tag_customer, -async_job.id job_id, -async_job.uuid job_uuid, -async_job.job_status job_status, -async_job.account_id job_account_id -from volumes -inner join account on volumes.account_id=account.id -inner join domain on volumes.domain_id=domain.id -left join projects on projects.project_account_id = account.id -left join data_center on volumes.data_center_id = data_center.id -left join vm_instance on volumes.instance_id = vm_instance.id -left join user_vm on user_vm.id = vm_instance.id -left join volume_host_ref on volumes.id = volume_host_ref.volume_id and volumes.data_center_id = volume_host_ref.zone_id -left join disk_offering on volumes.disk_offering_id = disk_offering.id -left join storage_pool on volumes.pool_id = storage_pool.id -left join cluster on storage_pool.cluster_id = cluster.id -left join vm_template on volumes.template_id = vm_template.id -left join resource_tags on resource_tags.resource_id = volumes.id and resource_tags.resource_type = "Volume" -left join async_job on async_job.instance_id = volumes.id and async_job.instance_type = "Volume" and async_job.job_status = 0; +CREATE VIEW `cloud`.`volume_view` AS + select + volumes.id, + volumes.uuid, + volumes.name, + volumes.device_id, + volumes.volume_type, + volumes.size, + volumes.created, + volumes.state, + volumes.attached, + volumes.removed, + volumes.pod_id, + account.id account_id, + account.uuid account_uuid, + account.account_name account_name, + account.type account_type, + domain.id domain_id, + domain.uuid domain_uuid, + domain.name domain_name, + domain.path domain_path, + projects.id project_id, + projects.uuid project_uuid, + projects.name project_name, + data_center.id data_center_id, + data_center.uuid data_center_uuid, + data_center.name data_center_name, + vm_instance.id vm_id, + vm_instance.uuid vm_uuid, + vm_instance.name vm_name, + vm_instance.state vm_state, + vm_instance.vm_type, + user_vm.display_name vm_display_name, + volume_host_ref.size volume_host_size, + volume_host_ref.created volume_host_created, + volume_host_ref.format, + volume_host_ref.download_pct, + volume_host_ref.download_state, + volume_host_ref.error_str, + disk_offering.id disk_offering_id, + disk_offering.uuid disk_offering_uuid, + disk_offering.name disk_offering_name, + disk_offering.display_text disk_offering_display_text, + disk_offering.use_local_storage, + disk_offering.system_use, + storage_pool.id pool_id, + storage_pool.uuid pool_uuid, + storage_pool.name pool_name, + cluster.hypervisor_type, + vm_template.id template_id, + vm_template.uuid template_uuid, + vm_template.extractable, + vm_template.type template_type, + resource_tags.id tag_id, + resource_tags.uuid tag_uuid, + resource_tags.key tag_key, + resource_tags.value tag_value, + resource_tags.domain_id tag_domain_id, + resource_tags.account_id tag_account_id, + resource_tags.resource_id tag_resource_id, + resource_tags.resource_uuid tag_resource_uuid, + resource_tags.resource_type tag_resource_type, + resource_tags.customer tag_customer, + async_job.id job_id, + async_job.uuid job_uuid, + async_job.job_status job_status, + async_job.account_id job_account_id + from + `cloud`.`volumes` + inner join + `cloud`.`account` ON volumes.account_id = account.id + inner join + `cloud`.`domain` ON volumes.domain_id = domain.id + left join + `cloud`.`projects` ON projects.project_account_id = account.id + left join + `cloud`.`data_center` ON volumes.data_center_id = data_center.id + left join + `cloud`.`vm_instance` ON volumes.instance_id = vm_instance.id + left join + `cloud`.`user_vm` ON user_vm.id = vm_instance.id + left join + `cloud`.`volume_host_ref` ON volumes.id = volume_host_ref.volume_id + and volumes.data_center_id = volume_host_ref.zone_id + left join + `cloud`.`disk_offering` ON volumes.disk_offering_id = disk_offering.id + left join + `cloud`.`storage_pool` ON volumes.pool_id = storage_pool.id + left join + `cloud`.`cluster` ON storage_pool.cluster_id = cluster.id + left join + `cloud`.`vm_template` ON volumes.template_id = vm_template.id + left join + `cloud`.`resource_tags` ON resource_tags.resource_id = volumes.id + and resource_tags.resource_type = 'Volume' + left join + `cloud`.`async_job` ON async_job.instance_id = volumes.id + and async_job.instance_type = 'Volume' + and async_job.job_status = 0; DROP VIEW IF EXISTS `cloud`.`account_netstats_view`; -CREATE VIEW account_netstats_view AS -SELECT account_id, -sum(net_bytes_received)+ sum(current_bytes_received) as bytesReceived, -sum(net_bytes_sent)+ sum(current_bytes_sent) as bytesSent -FROM user_statistics -group by account_id; +CREATE VIEW `cloud`.`account_netstats_view` AS + SELECT + account_id, + sum(net_bytes_received) + sum(current_bytes_received) as bytesReceived, + sum(net_bytes_sent) + sum(current_bytes_sent) as bytesSent + FROM + `cloud`.`user_statistics` + group by account_id; DROP VIEW IF EXISTS `cloud`.`account_vmstats_view`; -CREATE VIEW account_vmstats_view AS -SELECT account_id, state, count(*) as vmcount -from vm_instance -group by account_id, state; +CREATE VIEW `cloud`.`account_vmstats_view` AS + SELECT + account_id, state, count(*) as vmcount + from + `cloud`.`vm_instance` + group by account_id , state; DROP VIEW IF EXISTS `cloud`.`free_ip_view`; -CREATE VIEW free_ip_view AS -select count(user_ip_address.id) free_ip -from user_ip_address -inner join vlan on vlan.id = user_ip_address.vlan_db_id and vlan.vlan_type = "VirtualNetwork" -where state = "Free" +CREATE VIEW `cloud`.`free_ip_view` AS + select + count(user_ip_address.id) free_ip + from + `cloud`.`user_ip_address` + inner join + `cloud`.`vlan` ON vlan.id = user_ip_address.vlan_db_id + and vlan.vlan_type = 'VirtualNetwork' + where + state = 'Free'; DROP VIEW IF EXISTS `cloud`.`account_view`; -CREATE VIEW account_view AS -select -account.id, -account.uuid, -account.account_name, -account.type, -account.state, -account.removed, -account.cleanup_needed, -account.network_domain, -domain.id domain_id, -domain.uuid domain_uuid, -domain.name domain_name, -domain.path domain_path, -data_center.id data_center_id, -data_center.uuid data_center_uuid, -data_center.name data_center_name, -account_netstats_view.bytesReceived, -account_netstats_view.bytesSent, -vmlimit.max vmLimit, -vmcount.count vmTotal, -runningvm.vmcount runningVms, -stoppedvm.vmcount stoppedVms, -iplimit.max ipLimit, -ipcount.count ipTotal, -free_ip_view.free_ip ipFree, -volumelimit.max volumeLimit, -volumecount.count volumeTotal, -snapshotlimit.max snapshotLimit, -snapshotcount.count snapshotTotal, -templatelimit.max templateLimit, -templatecount.count templateTotal, -vpclimit.max vpcLimit, -vpccount.count vpcTotal, -projectlimit.max projectLimit, -projectcount.count projectTotal, -networklimit.max networkLimit, -networkcount.count networkTotal, -async_job.id job_id, -async_job.uuid job_uuid, -async_job.job_status job_status, -async_job.account_id job_account_id -from free_ip_view, account -inner join domain on account.domain_id=domain.id -left join data_center on account.default_zone_id = data_center.id -left join account_netstats_view on account.id = account_netstats_view.account_id -left join resource_limit vmlimit on account.id = vmlimit.account_id and vmlimit.type = "user_vm" -left join resource_count vmcount on account.id = vmcount.account_id and vmcount.type = "user_vm" -left join account_vmstats_view runningvm on account.id = runningvm.account_id and runningvm.state = "Running" -left join account_vmstats_view stoppedvm on account.id = stoppedvm.account_id and stoppedvm.state = "Stopped" -left join resource_limit iplimit on account.id = iplimit.account_id and iplimit.type = "public_ip" -left join resource_count ipcount on account.id = ipcount.account_id and ipcount.type = "public_ip" -left join resource_limit volumelimit on account.id = volumelimit.account_id and volumelimit.type = "volume" -left join resource_count volumecount on account.id = volumecount.account_id and volumecount.type = "volume" -left join resource_limit snapshotlimit on account.id = snapshotlimit.account_id and snapshotlimit.type = "snapshot" -left join resource_count snapshotcount on account.id = snapshotcount.account_id and snapshotcount.type = "snapshot" -left join resource_limit templatelimit on account.id = templatelimit.account_id and templatelimit.type = "template" -left join resource_count templatecount on account.id = templatecount.account_id and templatecount.type = "template" -left join resource_limit vpclimit on account.id = vpclimit.account_id and vpclimit.type = "vpc" -left join resource_count vpccount on account.id = vpccount.account_id and vpccount.type = "vpc" -left join resource_limit projectlimit on account.id = projectlimit.account_id and projectlimit.type = "project" -left join resource_count projectcount on account.id = projectcount.account_id and projectcount.type = "project" -left join resource_limit networklimit on account.id = networklimit.account_id and networklimit.type = "network" -left join resource_count networkcount on account.id = networkcount.account_id and networkcount.type = "network" -left join async_job on async_job.instance_id = account.id and async_job.instance_type = "Account" and async_job.job_status = 0; +CREATE VIEW `cloud`.`account_view` AS + select + account.id, + account.uuid, + account.account_name, + account.type, + account.state, + account.removed, + account.cleanup_needed, + account.network_domain, + domain.id domain_id, + domain.uuid domain_uuid, + domain.name domain_name, + domain.path domain_path, + data_center.id data_center_id, + data_center.uuid data_center_uuid, + data_center.name data_center_name, + account_netstats_view.bytesReceived, + account_netstats_view.bytesSent, + vmlimit.max vmLimit, + vmcount.count vmTotal, + runningvm.vmcount runningVms, + stoppedvm.vmcount stoppedVms, + iplimit.max ipLimit, + ipcount.count ipTotal, + free_ip_view.free_ip ipFree, + volumelimit.max volumeLimit, + volumecount.count volumeTotal, + snapshotlimit.max snapshotLimit, + snapshotcount.count snapshotTotal, + templatelimit.max templateLimit, + templatecount.count templateTotal, + vpclimit.max vpcLimit, + vpccount.count vpcTotal, + projectlimit.max projectLimit, + projectcount.count projectTotal, + networklimit.max networkLimit, + networkcount.count networkTotal, + async_job.id job_id, + async_job.uuid job_uuid, + async_job.job_status job_status, + async_job.account_id job_account_id + from + `cloud`.`free_ip_view`, + `cloud`.`account` + inner join + `cloud`.`domain` ON account.domain_id = domain.id + left join + `cloud`.`data_center` ON account.default_zone_id = data_center.id + left join + `cloud`.`account_netstats_view` ON account.id = account_netstats_view.account_id + left join + `cloud`.`resource_limit` vmlimit ON account.id = vmlimit.account_id + and vmlimit.type = 'user_vm' + left join + `cloud`.`resource_count` vmcount ON account.id = vmcount.account_id + and vmcount.type = 'user_vm' + left join + `cloud`.`account_vmstats_view` runningvm ON account.id = runningvm.account_id + and runningvm.state = 'Running' + left join + `cloud`.`account_vmstats_view` stoppedvm ON account.id = stoppedvm.account_id + and stoppedvm.state = 'Stopped' + left join + `cloud`.`resource_limit` iplimit ON account.id = iplimit.account_id + and iplimit.type = 'public_ip' + left join + `cloud`.`resource_count` ipcount ON account.id = ipcount.account_id + and ipcount.type = 'public_ip' + left join + `cloud`.`resource_limit` volumelimit ON account.id = volumelimit.account_id + and volumelimit.type = 'volume' + left join + `cloud`.`resource_count` volumecount ON account.id = volumecount.account_id + and volumecount.type = 'volume' + left join + `cloud`.`resource_limit` snapshotlimit ON account.id = snapshotlimit.account_id + and snapshotlimit.type = 'snapshot' + left join + `cloud`.`resource_count` snapshotcount ON account.id = snapshotcount.account_id + and snapshotcount.type = 'snapshot' + left join + `cloud`.`resource_limit` templatelimit ON account.id = templatelimit.account_id + and templatelimit.type = 'template' + left join + `cloud`.`resource_count` templatecount ON account.id = templatecount.account_id + and templatecount.type = 'template' + left join + `cloud`.`resource_limit` vpclimit ON account.id = vpclimit.account_id + and vpclimit.type = 'vpc' + left join + `cloud`.`resource_count` vpccount ON account.id = vpccount.account_id + and vpccount.type = 'vpc' + left join + `cloud`.`resource_limit` projectlimit ON account.id = projectlimit.account_id + and projectlimit.type = 'project' + left join + `cloud`.`resource_count` projectcount ON account.id = projectcount.account_id + and projectcount.type = 'project' + left join + `cloud`.`resource_limit` networklimit ON account.id = networklimit.account_id + and networklimit.type = 'network' + left join + `cloud`.`resource_count` networkcount ON account.id = networkcount.account_id + and networkcount.type = 'network' + left join + `cloud`.`async_job` ON async_job.instance_id = account.id + and async_job.instance_type = 'Account' + and async_job.job_status = 0; DROP VIEW IF EXISTS `cloud`.`async_job_view`; -CREATE VIEW async_job_view AS -select -account.id account_id, -account.uuid account_uuid, -account.account_name account_name, -account.type account_type, -domain.id domain_id, -domain.uuid domain_uuid, -domain.name domain_name, -domain.path domain_path, -user.id user_id, -user.uuid user_uuid, -async_job.id, -async_job.uuid, -async_job.job_cmd, -async_job.job_status, -async_job.job_process_status, -async_job.job_result_code, -async_job.job_result, -async_job.created, -async_job.removed, -async_job.instance_type, -async_job.instance_id, -CASE -WHEN async_job.instance_type = 'Volume' THEN volumes.uuid -WHEN async_job.instance_type = 'Template' or async_job.instance_type = 'Iso' THEN vm_template.uuid -WHEN async_job.instance_type = 'VirtualMachine' or async_job.instance_type = 'ConsoleProxy' or async_job.instance_type = 'SystemVm' or async_job.instance_type = 'DomainRouter' THEN vm_instance.uuid -WHEN async_job.instance_type = 'Snapshot' THEN snapshots.uuid -WHEN async_job.instance_type = 'Host' THEN host.uuid -WHEN async_job.instance_type = 'StoragePool' THEN storage_pool.uuid -WHEN async_job.instance_type = 'IpAddress' THEN user_ip_address.uuid -WHEN async_job.instance_type = 'SecurityGroup' THEN security_group.uuid -WHEN async_job.instance_type = 'PhysicalNetwork' THEN physical_network.uuid -WHEN async_job.instance_type = 'TrafficType' THEN physical_network_traffic_types.uuid -WHEN async_job.instance_type = 'PhysicalNetworkServiceProvider' THEN physical_network_service_providers.uuid -WHEN async_job.instance_type = 'FirewallRule' THEN firewall_rules.uuid -WHEN async_job.instance_type = 'Account' THEN acct.uuid -WHEN async_job.instance_type = 'User' THEN us.uuid -WHEN async_job.instance_type = 'StaticRoute' THEN static_routes.uuid -WHEN async_job.instance_type = 'PrivateGateway' THEN vpc_gateways.uuid -WHEN async_job.instance_type = 'Counter' THEN counter.uuid -WHEN async_job.instance_type = 'Condition' THEN conditions.uuid -WHEN async_job.instance_type = 'AutoScalePolicy' THEN autoscale_policies.uuid -WHEN async_job.instance_type = 'AutoScaleVmProfile' THEN autoscale_vmprofiles.uuid -WHEN async_job.instance_type = 'AutoScaleVmGroup' THEN autoscale_vmgroups.uuid -ELSE null -END instance_uuid -from async_job -left join account on async_job.account_id = account.id -left join domain on domain.id = account.domain_id -left join user on async_job.user_id = user.id -left join volumes on async_job.instance_id = volumes.id -left join vm_template on async_job.instance_id = vm_template.id -left join vm_instance on async_job.instance_id = vm_instance.id -left join snapshots on async_job.instance_id = snapshots.id -left join host on async_job.instance_id = host.id -left join storage_pool on async_job.instance_id = storage_pool.id -left join user_ip_address on async_job.instance_id = user_ip_address.id -left join security_group on async_job.instance_id = security_group.id -left join physical_network on async_job.instance_id = physical_network.id -left join physical_network_traffic_types on async_job.instance_id = physical_network_traffic_types.id -left join physical_network_service_providers on async_job.instance_id = physical_network_service_providers.id -left join firewall_rules on async_job.instance_id = firewall_rules.id -left join account acct on async_job.instance_id = acct.id -left join user us on async_job.instance_id = us.id -left join static_routes on async_job.instance_id = static_routes.id -left join vpc_gateways on async_job.instance_id = vpc_gateways.id -left join counter on async_job.instance_id = counter.id -left join conditions on async_job.instance_id = conditions.id -left join autoscale_policies on async_job.instance_id = autoscale_policies.id -left join autoscale_vmprofiles on async_job.instance_id = autoscale_vmprofiles.id -left join autoscale_vmgroups on async_job.instance_id = autoscale_vmgroups.id; +CREATE VIEW `cloud`.`async_job_view` AS + select + account.id account_id, + account.uuid account_uuid, + account.account_name account_name, + account.type account_type, + domain.id domain_id, + domain.uuid domain_uuid, + domain.name domain_name, + domain.path domain_path, + user.id user_id, + user.uuid user_uuid, + async_job.id, + async_job.uuid, + async_job.job_cmd, + async_job.job_status, + async_job.job_process_status, + async_job.job_result_code, + async_job.job_result, + async_job.created, + async_job.removed, + async_job.instance_type, + async_job.instance_id, + CASE + WHEN async_job.instance_type = 'Volume' THEN volumes.uuid + WHEN + async_job.instance_type = 'Template' + or async_job.instance_type = 'Iso' + THEN + vm_template.uuid + WHEN + async_job.instance_type = 'VirtualMachine' + or async_job.instance_type = 'ConsoleProxy' + or async_job.instance_type = 'SystemVm' + or async_job.instance_type = 'DomainRouter' + THEN + vm_instance.uuid + WHEN async_job.instance_type = 'Snapshot' THEN snapshots.uuid + WHEN async_job.instance_type = 'Host' THEN host.uuid + WHEN async_job.instance_type = 'StoragePool' THEN storage_pool.uuid + WHEN async_job.instance_type = 'IpAddress' THEN user_ip_address.uuid + WHEN async_job.instance_type = 'SecurityGroup' THEN security_group.uuid + WHEN async_job.instance_type = 'PhysicalNetwork' THEN physical_network.uuid + WHEN async_job.instance_type = 'TrafficType' THEN physical_network_traffic_types.uuid + WHEN async_job.instance_type = 'PhysicalNetworkServiceProvider' THEN physical_network_service_providers.uuid + WHEN async_job.instance_type = 'FirewallRule' THEN firewall_rules.uuid + WHEN async_job.instance_type = 'Account' THEN acct.uuid + WHEN async_job.instance_type = 'User' THEN us.uuid + WHEN async_job.instance_type = 'StaticRoute' THEN static_routes.uuid + WHEN async_job.instance_type = 'PrivateGateway' THEN vpc_gateways.uuid + WHEN async_job.instance_type = 'Counter' THEN counter.uuid + WHEN async_job.instance_type = 'Condition' THEN conditions.uuid + WHEN async_job.instance_type = 'AutoScalePolicy' THEN autoscale_policies.uuid + WHEN async_job.instance_type = 'AutoScaleVmProfile' THEN autoscale_vmprofiles.uuid + WHEN async_job.instance_type = 'AutoScaleVmGroup' THEN autoscale_vmgroups.uuid + ELSE null + END instance_uuid + from + `cloud`.`async_job` + left join + `cloud`.`account` ON async_job.account_id = account.id + left join + `cloud`.`domain` ON domain.id = account.domain_id + left join + `cloud`.`user` ON async_job.user_id = user.id + left join + `cloud`.`volumes` ON async_job.instance_id = volumes.id + left join + `cloud`.`vm_template` ON async_job.instance_id = vm_template.id + left join + `cloud`.`vm_instance` ON async_job.instance_id = vm_instance.id + left join + `cloud`.`snapshots` ON async_job.instance_id = snapshots.id + left join + `cloud`.`host` ON async_job.instance_id = host.id + left join + `cloud`.`storage_pool` ON async_job.instance_id = storage_pool.id + left join + `cloud`.`user_ip_address` ON async_job.instance_id = user_ip_address.id + left join + `cloud`.`security_group` ON async_job.instance_id = security_group.id + left join + `cloud`.`physical_network` ON async_job.instance_id = physical_network.id + left join + `cloud`.`physical_network_traffic_types` ON async_job.instance_id = physical_network_traffic_types.id + left join + `cloud`.`physical_network_service_providers` ON async_job.instance_id = physical_network_service_providers.id + left join + `cloud`.`firewall_rules` ON async_job.instance_id = firewall_rules.id + left join + `cloud`.`account` acct ON async_job.instance_id = acct.id + left join + `cloud`.`user` us ON async_job.instance_id = us.id + left join + `cloud`.`static_routes` ON async_job.instance_id = static_routes.id + left join + `cloud`.`vpc_gateways` ON async_job.instance_id = vpc_gateways.id + left join + `cloud`.`counter` ON async_job.instance_id = counter.id + left join + `cloud`.`conditions` ON async_job.instance_id = conditions.id + left join + `cloud`.`autoscale_policies` ON async_job.instance_id = autoscale_policies.id + left join + `cloud`.`autoscale_vmprofiles` ON async_job.instance_id = autoscale_vmprofiles.id + left join + `cloud`.`autoscale_vmgroups` ON async_job.instance_id = autoscale_vmgroups.id; DROP VIEW IF EXISTS `cloud`.`storage_pool_view`; -CREATE VIEW storage_pool_view AS -select -storage_pool.id, -storage_pool.uuid, -storage_pool.name, -storage_pool.status, -storage_pool.path, -storage_pool.pool_type, -storage_pool.host_address, -storage_pool.created, -storage_pool.removed, -storage_pool.capacity_bytes, -cluster.id cluster_id, -cluster.uuid cluster_uuid, -cluster.name cluster_name, -cluster.cluster_type, -data_center.id data_center_id, -data_center.uuid data_center_uuid, -data_center.name data_center_name, -host_pod_ref.id pod_id, -host_pod_ref.uuid pod_uuid, -host_pod_ref.name pod_name, -storage_pool_details.name tag, -op_host_capacity.used_capacity disk_used_capacity, -op_host_capacity.reserved_capacity disk_reserved_capacity, -async_job.id job_id, -async_job.uuid job_uuid, -async_job.job_status job_status, -async_job.account_id job_account_id -from storage_pool -left join cluster on storage_pool.cluster_id = cluster.id -left join data_center on storage_pool.data_center_id = data_center.id -left join host_pod_ref on storage_pool.pod_id = host_pod_ref.id -left join storage_pool_details on storage_pool_details.pool_id = storage_pool.id and storage_pool_details.value = 'true' -left join op_host_capacity on storage_pool.id = op_host_capacity.host_id and op_host_capacity.capacity_type = 3 -left join async_job on async_job.instance_id = storage_pool.id and async_job.instance_type = "StoragePool" and async_job.job_status = 0; +CREATE VIEW `cloud`.`storage_pool_view` AS + select + storage_pool.id, + storage_pool.uuid, + storage_pool.name, + storage_pool.status, + storage_pool.path, + storage_pool.pool_type, + storage_pool.host_address, + storage_pool.created, + storage_pool.removed, + storage_pool.capacity_bytes, + cluster.id cluster_id, + cluster.uuid cluster_uuid, + cluster.name cluster_name, + cluster.cluster_type, + data_center.id data_center_id, + data_center.uuid data_center_uuid, + data_center.name data_center_name, + host_pod_ref.id pod_id, + host_pod_ref.uuid pod_uuid, + host_pod_ref.name pod_name, + storage_pool_details.name tag, + op_host_capacity.used_capacity disk_used_capacity, + op_host_capacity.reserved_capacity disk_reserved_capacity, + async_job.id job_id, + async_job.uuid job_uuid, + async_job.job_status job_status, + async_job.account_id job_account_id + from + `cloud`.`storage_pool` + left join + `cloud`.`cluster` ON storage_pool.cluster_id = cluster.id + left join + `cloud`.`data_center` ON storage_pool.data_center_id = data_center.id + left join + `cloud`.`host_pod_ref` ON storage_pool.pod_id = host_pod_ref.id + left join + `cloud`.`storage_pool_details` ON storage_pool_details.pool_id = storage_pool.id + and storage_pool_details.value = 'true' + left join + `cloud`.`op_host_capacity` ON storage_pool.id = op_host_capacity.host_id + and op_host_capacity.capacity_type = 3 + left join + `cloud`.`async_job` ON async_job.instance_id = storage_pool.id + and async_job.instance_type = 'StoragePool' + and async_job.job_status = 0; DROP VIEW IF EXISTS `cloud`.`disk_offering_view`; -CREATE VIEW disk_offering_view AS -select -disk_offering.id, -disk_offering.uuid, -disk_offering.name, -disk_offering.display_text, -disk_offering.disk_size, -disk_offering.created, -disk_offering.tags, -disk_offering.customized, -disk_offering.removed, -disk_offering.use_local_storage, -disk_offering.system_use, -disk_offering.sort_key, -disk_offering.type, -domain.id domain_id, -domain.uuid domain_uuid, -domain.name domain_name, -domain.path domain_path -from disk_offering -left join domain on disk_offering.domain_id=domain.id; +CREATE VIEW `cloud`.`disk_offering_view` AS + select + disk_offering.id, + disk_offering.uuid, + disk_offering.name, + disk_offering.display_text, + disk_offering.disk_size, + disk_offering.created, + disk_offering.tags, + disk_offering.customized, + disk_offering.removed, + disk_offering.use_local_storage, + disk_offering.system_use, + disk_offering.sort_key, + disk_offering.type, + domain.id domain_id, + domain.uuid domain_uuid, + domain.name domain_name, + domain.path domain_path + from + `cloud`.`disk_offering` + left join + `cloud`.`domain` ON disk_offering.domain_id = domain.id; DROP VIEW IF EXISTS `cloud`.`service_offering_view`; -CREATE VIEW service_offering_view AS -select -service_offering.id, -disk_offering.uuid, -disk_offering.name, -disk_offering.display_text, -disk_offering.created, -disk_offering.tags, -disk_offering.removed, -disk_offering.use_local_storage, -disk_offering.system_use, -service_offering.cpu, -service_offering.speed, -service_offering.ram_size, -service_offering.nw_rate, -service_offering.mc_rate, -service_offering.ha_enabled, -service_offering.limit_cpu_use, -service_offering.host_tag, -service_offering.default_use, -service_offering.vm_type, -service_offering.sort_key, -domain.id domain_id, -domain.uuid domain_uuid, -domain.name domain_name, -domain.path domain_path -from service_offering -inner join disk_offering on service_offering.id = disk_offering.id -left join domain on disk_offering.domain_id=domain.id; - - +CREATE VIEW `cloud`.`service_offering_view` AS + select + service_offering.id, + disk_offering.uuid, + disk_offering.name, + disk_offering.display_text, + disk_offering.created, + disk_offering.tags, + disk_offering.removed, + disk_offering.use_local_storage, + disk_offering.system_use, + service_offering.cpu, + service_offering.speed, + service_offering.ram_size, + service_offering.nw_rate, + service_offering.mc_rate, + service_offering.ha_enabled, + service_offering.limit_cpu_use, + service_offering.host_tag, + service_offering.default_use, + service_offering.vm_type, + service_offering.sort_key, + domain.id domain_id, + domain.uuid domain_uuid, + domain.name domain_name, + domain.path domain_path + from + `cloud`.`service_offering` + inner join + `cloud`.`disk_offering` ON service_offering.id = disk_offering.id + left join + `cloud`.`domain` ON disk_offering.domain_id = domain.id; + INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Advanced', 'DEFAULT', 'management-server', 'direct.agent.pool.size', '500', 'Default size for DirectAgentPool'); From 2130a418e01058f67ceeaaa298119cf59f9e0835 Mon Sep 17 00:00:00 2001 From: Min Chen Date: Tue, 22 Jan 2013 10:08:57 -0800 Subject: [PATCH 48/80] Formatting db view sql creation, and also addressed FIXME in Hugo's change. --- setup/db/create-schema-view.sql | 1862 +++++++++++++++++-------------- setup/db/db/schema-40to410.sql | 19 +- 2 files changed, 1054 insertions(+), 827 deletions(-) diff --git a/setup/db/create-schema-view.sql b/setup/db/create-schema-view.sql index 495b6c5cd20..f5c0591c0aa 100644 --- a/setup/db/create-schema-view.sql +++ b/setup/db/create-schema-view.sql @@ -14,862 +14,1094 @@ -- KIND, either express or implied. See the License for the -- specific language governing permissions and limitations -- under the License. -use cloud; ---- DB views for list api --- +-- DB views for list api + DROP VIEW IF EXISTS `cloud`.`user_vm_view`; CREATE VIEW `cloud`.`user_vm_view` AS -select -vm_instance.id id, -vm_instance.name name, -user_vm.display_name display_name, -user_vm.user_data user_data, -account.id account_id, -account.uuid account_uuid, -account.account_name account_name, -account.type account_type, -domain.id domain_id, -domain.uuid domain_uuid, -domain.name domain_name, -domain.path domain_path, -projects.id project_id, -projects.uuid project_uuid, -projects.name project_name, -instance_group.id instance_group_id, -instance_group.uuid instance_group_uuid, -instance_group.name instance_group_name, -vm_instance.uuid uuid, -vm_instance.last_host_id last_host_id, -vm_instance.vm_type type, -vm_instance.vnc_password vnc_password, -vm_instance.limit_cpu_use limit_cpu_use, -vm_instance.created created, -vm_instance.state state, -vm_instance.removed removed, -vm_instance.ha_enabled ha_enabled, -vm_instance.hypervisor_type hypervisor_type, -vm_instance.instance_name instance_name, -vm_instance.guest_os_id guest_os_id, -guest_os.uuid guest_os_uuid, -vm_instance.pod_id pod_id, -host_pod_ref.uuid pod_uuid, -vm_instance.private_ip_address private_ip_address, -vm_instance.private_mac_address private_mac_address, -vm_instance.vm_type vm_type, -data_center.id data_center_id, -data_center.uuid data_center_uuid, -data_center.name data_center_name, -data_center.is_security_group_enabled security_group_enabled, -host.id host_id, -host.uuid host_uuid, -host.name host_name, -vm_template.id template_id, -vm_template.uuid template_uuid, -vm_template.name template_name, -vm_template.display_text template_display_text, -vm_template.enable_password password_enabled, -iso.id iso_id, -iso.uuid iso_uuid, -iso.name iso_name, -iso.display_text iso_display_text, -service_offering.id service_offering_id, -disk_offering.uuid service_offering_uuid, -service_offering.cpu cpu, -service_offering.speed speed, -service_offering.ram_size ram_size, -disk_offering.name service_offering_name, -storage_pool.id pool_id, -storage_pool.uuid pool_uuid, -storage_pool.pool_type pool_type, -volumes.id volume_id, -volumes.uuid volume_uuid, -volumes.device_id volume_device_id, -volumes.volume_type volume_type, -security_group.id security_group_id, -security_group.uuid security_group_uuid, -security_group.name security_group_name, -security_group.description security_group_description, -nics.id nic_id, -nics.uuid nic_uuid, -nics.network_id network_id, -nics.ip4_address ip_address, -nics.default_nic is_default_nic, -nics.gateway gateway, -nics.netmask netmask, -nics.mac_address mac_address, -nics.broadcast_uri broadcast_uri, -nics.isolation_uri isolation_uri, -vpc.id vpc_id, -vpc.uuid vpc_uuid, -networks.uuid network_uuid, -networks.traffic_type traffic_type, -networks.guest_type guest_type, -user_ip_address.id public_ip_id, -user_ip_address.uuid public_ip_uuid, -user_ip_address.public_ip_address public_ip_address, -ssh_keypairs.keypair_name keypair_name, -resource_tags.id tag_id, -resource_tags.uuid tag_uuid, -resource_tags.key tag_key, -resource_tags.value tag_value, -resource_tags.domain_id tag_domain_id, -resource_tags.account_id tag_account_id, -resource_tags.resource_id tag_resource_id, -resource_tags.resource_uuid tag_resource_uuid, -resource_tags.resource_type tag_resource_type, -resource_tags.customer tag_customer, -async_job.id job_id, -async_job.uuid job_uuid, -async_job.job_status job_status, -async_job.account_id job_account_id -from user_vm -inner join vm_instance on vm_instance.id = user_vm.id and vm_instance.removed is NULL -inner join account on vm_instance.account_id=account.id -inner join domain on vm_instance.domain_id=domain.id -left join guest_os on vm_instance.guest_os_id = guest_os.id -left join host_pod_ref on vm_instance.pod_id = host_pod_ref.id -left join projects on projects.project_account_id = account.id -left join instance_group_vm_map on vm_instance.id=instance_group_vm_map.instance_id -left join instance_group on instance_group_vm_map.group_id=instance_group.id -left join data_center on vm_instance.data_center_id=data_center.id -left join host on vm_instance.host_id=host.id -left join vm_template on vm_instance.vm_template_id=vm_template.id -left join vm_template iso on iso.id=user_vm.iso_id -left join service_offering on vm_instance.service_offering_id=service_offering.id -left join disk_offering on vm_instance.service_offering_id=disk_offering.id -left join volumes on vm_instance.id=volumes.instance_id -left join storage_pool on volumes.pool_id=storage_pool.id -left join security_group_vm_map on vm_instance.id=security_group_vm_map.instance_id -left join security_group on security_group_vm_map.security_group_id=security_group.id -left join nics on vm_instance.id=nics.instance_id -left join networks on nics.network_id=networks.id -left join vpc on networks.vpc_id = vpc.id -left join user_ip_address on user_ip_address.vm_id=vm_instance.id -left join user_vm_details on user_vm_details.vm_id=vm_instance.id and user_vm_details.name = "SSH.PublicKey" -left join ssh_keypairs on ssh_keypairs.public_key = user_vm_details.value -left join resource_tags on resource_tags.resource_id = vm_instance.id and resource_tags.resource_type = "UserVm" -left join async_job on async_job.instance_id = vm_instance.id and async_job.instance_type = "VirtualMachine" and async_job.job_status = 0; + select + vm_instance.id id, + vm_instance.name name, + user_vm.display_name display_name, + user_vm.user_data user_data, + account.id account_id, + account.uuid account_uuid, + account.account_name account_name, + account.type account_type, + domain.id domain_id, + domain.uuid domain_uuid, + domain.name domain_name, + domain.path domain_path, + projects.id project_id, + projects.uuid project_uuid, + projects.name project_name, + instance_group.id instance_group_id, + instance_group.uuid instance_group_uuid, + instance_group.name instance_group_name, + vm_instance.uuid uuid, + vm_instance.last_host_id last_host_id, + vm_instance.vm_type type, + vm_instance.vnc_password vnc_password, + vm_instance.limit_cpu_use limit_cpu_use, + vm_instance.created created, + vm_instance.state state, + vm_instance.removed removed, + vm_instance.ha_enabled ha_enabled, + vm_instance.hypervisor_type hypervisor_type, + vm_instance.instance_name instance_name, + vm_instance.guest_os_id guest_os_id, + guest_os.uuid guest_os_uuid, + vm_instance.pod_id pod_id, + host_pod_ref.uuid pod_uuid, + vm_instance.private_ip_address private_ip_address, + vm_instance.private_mac_address private_mac_address, + vm_instance.vm_type vm_type, + data_center.id data_center_id, + data_center.uuid data_center_uuid, + data_center.name data_center_name, + data_center.is_security_group_enabled security_group_enabled, + host.id host_id, + host.uuid host_uuid, + host.name host_name, + vm_template.id template_id, + vm_template.uuid template_uuid, + vm_template.name template_name, + vm_template.display_text template_display_text, + vm_template.enable_password password_enabled, + iso.id iso_id, + iso.uuid iso_uuid, + iso.name iso_name, + iso.display_text iso_display_text, + service_offering.id service_offering_id, + disk_offering.uuid service_offering_uuid, + service_offering.cpu cpu, + service_offering.speed speed, + service_offering.ram_size ram_size, + disk_offering.name service_offering_name, + storage_pool.id pool_id, + storage_pool.uuid pool_uuid, + storage_pool.pool_type pool_type, + volumes.id volume_id, + volumes.uuid volume_uuid, + volumes.device_id volume_device_id, + volumes.volume_type volume_type, + security_group.id security_group_id, + security_group.uuid security_group_uuid, + security_group.name security_group_name, + security_group.description security_group_description, + nics.id nic_id, + nics.uuid nic_uuid, + nics.network_id network_id, + nics.ip4_address ip_address, + nics.default_nic is_default_nic, + nics.gateway gateway, + nics.netmask netmask, + nics.mac_address mac_address, + nics.broadcast_uri broadcast_uri, + nics.isolation_uri isolation_uri, + vpc.id vpc_id, + vpc.uuid vpc_uuid, + networks.uuid network_uuid, + networks.traffic_type traffic_type, + networks.guest_type guest_type, + user_ip_address.id public_ip_id, + user_ip_address.uuid public_ip_uuid, + user_ip_address.public_ip_address public_ip_address, + ssh_keypairs.keypair_name keypair_name, + resource_tags.id tag_id, + resource_tags.uuid tag_uuid, + resource_tags.key tag_key, + resource_tags.value tag_value, + resource_tags.domain_id tag_domain_id, + resource_tags.account_id tag_account_id, + resource_tags.resource_id tag_resource_id, + resource_tags.resource_uuid tag_resource_uuid, + resource_tags.resource_type tag_resource_type, + resource_tags.customer tag_customer, + async_job.id job_id, + async_job.uuid job_uuid, + async_job.job_status job_status, + async_job.account_id job_account_id + from + `cloud`.`user_vm` + inner join + `cloud`.`vm_instance` ON vm_instance.id = user_vm.id + and vm_instance.removed is NULL + inner join + `cloud`.`account` ON vm_instance.account_id = account.id + inner join + `cloud`.`domain` ON vm_instance.domain_id = domain.id + left join + `cloud`.`guest_os` ON vm_instance.guest_os_id = guest_os.id + left join + `cloud`.`host_pod_ref` ON vm_instance.pod_id = host_pod_ref.id + left join + `cloud`.`projects` ON projects.project_account_id = account.id + left join + `cloud`.`instance_group_vm_map` ON vm_instance.id = instance_group_vm_map.instance_id + left join + `cloud`.`instance_group` ON instance_group_vm_map.group_id = instance_group.id + left join + `cloud`.`data_center` ON vm_instance.data_center_id = data_center.id + left join + `cloud`.`host` ON vm_instance.host_id = host.id + left join + `cloud`.`vm_template` ON vm_instance.vm_template_id = vm_template.id + left join + `cloud`.`vm_template` iso ON iso.id = user_vm.iso_id + left join + `cloud`.`service_offering` ON vm_instance.service_offering_id = service_offering.id + left join + `cloud`.`disk_offering` ON vm_instance.service_offering_id = disk_offering.id + left join + `cloud`.`volumes` ON vm_instance.id = volumes.instance_id + left join + `cloud`.`storage_pool` ON volumes.pool_id = storage_pool.id + left join + `cloud`.`security_group_vm_map` ON vm_instance.id = security_group_vm_map.instance_id + left join + `cloud`.`security_group` ON security_group_vm_map.security_group_id = security_group.id + left join + `cloud`.`nics` ON vm_instance.id = nics.instance_id + left join + `cloud`.`networks` ON nics.network_id = networks.id + left join + `cloud`.`vpc` ON networks.vpc_id = vpc.id + left join + `cloud`.`user_ip_address` ON user_ip_address.vm_id = vm_instance.id + left join + `cloud`.`user_vm_details` ON user_vm_details.vm_id = vm_instance.id + and user_vm_details.name = 'SSH.PublicKey' + left join + `cloud`.`ssh_keypairs` ON ssh_keypairs.public_key = user_vm_details.value + left join + `cloud`.`resource_tags` ON resource_tags.resource_id = vm_instance.id + and resource_tags.resource_type = 'UserVm' + left join + `cloud`.`async_job` ON async_job.instance_id = vm_instance.id + and async_job.instance_type = 'VirtualMachine' + and async_job.job_status = 0; DROP VIEW IF EXISTS `cloud`.`domain_router_view`; -CREATE VIEW domain_router_view AS -select -vm_instance.id id, -vm_instance.name name, -account.id account_id, -account.uuid account_uuid, -account.account_name account_name, -account.type account_type, -domain.id domain_id, -domain.uuid domain_uuid, -domain.name domain_name, -domain.path domain_path, -projects.id project_id, -projects.uuid project_uuid, -projects.name project_name, -vm_instance.uuid uuid, -vm_instance.created created, -vm_instance.state state, -vm_instance.removed removed, -vm_instance.pod_id pod_id, -vm_instance.instance_name instance_name, -host_pod_ref.uuid pod_uuid, -data_center.id data_center_id, -data_center.uuid data_center_uuid, -data_center.name data_center_name, -data_center.dns1 dns1, -data_center.dns2 dns2, -host.id host_id, -host.uuid host_uuid, -host.name host_name, -vm_template.id template_id, -vm_template.uuid template_uuid, -service_offering.id service_offering_id, -disk_offering.uuid service_offering_uuid, -disk_offering.name service_offering_name, -nics.id nic_id, -nics.uuid nic_uuid, -nics.network_id network_id, -nics.ip4_address ip_address, -nics.default_nic is_default_nic, -nics.gateway gateway, -nics.netmask netmask, -nics.mac_address mac_address, -nics.broadcast_uri broadcast_uri, -nics.isolation_uri isolation_uri, -vpc.id vpc_id, -vpc.uuid vpc_uuid, -networks.uuid network_uuid, -networks.name network_name, -networks.network_domain network_domain, -networks.traffic_type traffic_type, -networks.guest_type guest_type, -async_job.id job_id, -async_job.uuid job_uuid, -async_job.job_status job_status, -async_job.account_id job_account_id, -domain_router.template_version template_version, -domain_router.scripts_version scripts_version, -domain_router.is_redundant_router is_redundant_router, -domain_router.redundant_state redundant_state, -domain_router.stop_pending stop_pending -from domain_router -inner join vm_instance on vm_instance.id = domain_router.id -inner join account on vm_instance.account_id=account.id -inner join domain on vm_instance.domain_id=domain.id -left join host_pod_ref on vm_instance.pod_id = host_pod_ref.id -left join projects on projects.project_account_id = account.id -left join data_center on vm_instance.data_center_id=data_center.id -left join host on vm_instance.host_id=host.id -left join vm_template on vm_instance.vm_template_id=vm_template.id -left join service_offering on vm_instance.service_offering_id=service_offering.id -left join disk_offering on vm_instance.service_offering_id=disk_offering.id -left join volumes on vm_instance.id=volumes.instance_id -left join storage_pool on volumes.pool_id=storage_pool.id -left join nics on vm_instance.id=nics.instance_id -left join networks on nics.network_id=networks.id -left join vpc on networks.vpc_id = vpc.id -left join async_job on async_job.instance_id = vm_instance.id and async_job.instance_type = "DomainRouter" and async_job.job_status = 0; +CREATE VIEW `cloud`.`domain_router_view` AS + select + vm_instance.id id, + vm_instance.name name, + account.id account_id, + account.uuid account_uuid, + account.account_name account_name, + account.type account_type, + domain.id domain_id, + domain.uuid domain_uuid, + domain.name domain_name, + domain.path domain_path, + projects.id project_id, + projects.uuid project_uuid, + projects.name project_name, + vm_instance.uuid uuid, + vm_instance.created created, + vm_instance.state state, + vm_instance.removed removed, + vm_instance.pod_id pod_id, + vm_instance.instance_name instance_name, + host_pod_ref.uuid pod_uuid, + data_center.id data_center_id, + data_center.uuid data_center_uuid, + data_center.name data_center_name, + data_center.dns1 dns1, + data_center.dns2 dns2, + host.id host_id, + host.uuid host_uuid, + host.name host_name, + vm_template.id template_id, + vm_template.uuid template_uuid, + service_offering.id service_offering_id, + disk_offering.uuid service_offering_uuid, + disk_offering.name service_offering_name, + nics.id nic_id, + nics.uuid nic_uuid, + nics.network_id network_id, + nics.ip4_address ip_address, + nics.default_nic is_default_nic, + nics.gateway gateway, + nics.netmask netmask, + nics.mac_address mac_address, + nics.broadcast_uri broadcast_uri, + nics.isolation_uri isolation_uri, + vpc.id vpc_id, + vpc.uuid vpc_uuid, + networks.uuid network_uuid, + networks.name network_name, + networks.network_domain network_domain, + networks.traffic_type traffic_type, + networks.guest_type guest_type, + async_job.id job_id, + async_job.uuid job_uuid, + async_job.job_status job_status, + async_job.account_id job_account_id, + domain_router.template_version template_version, + domain_router.scripts_version scripts_version, + domain_router.is_redundant_router is_redundant_router, + domain_router.redundant_state redundant_state, + domain_router.stop_pending stop_pending + from + `cloud`.`domain_router` + inner join + `cloud`.`vm_instance` ON vm_instance.id = domain_router.id + inner join + `cloud`.`account` ON vm_instance.account_id = account.id + inner join + `cloud`.`domain` ON vm_instance.domain_id = domain.id + left join + `cloud`.`host_pod_ref` ON vm_instance.pod_id = host_pod_ref.id + left join + `cloud`.`projects` ON projects.project_account_id = account.id + left join + `cloud`.`data_center` ON vm_instance.data_center_id = data_center.id + left join + `cloud`.`host` ON vm_instance.host_id = host.id + left join + `cloud`.`vm_template` ON vm_instance.vm_template_id = vm_template.id + left join + `cloud`.`service_offering` ON vm_instance.service_offering_id = service_offering.id + left join + `cloud`.`disk_offering` ON vm_instance.service_offering_id = disk_offering.id + left join + `cloud`.`volumes` ON vm_instance.id = volumes.instance_id + left join + `cloud`.`storage_pool` ON volumes.pool_id = storage_pool.id + left join + `cloud`.`nics` ON vm_instance.id = nics.instance_id + left join + `cloud`.`networks` ON nics.network_id = networks.id + left join + `cloud`.`vpc` ON networks.vpc_id = vpc.id + left join + `cloud`.`async_job` ON async_job.instance_id = vm_instance.id + and async_job.instance_type = 'DomainRouter' + and async_job.job_status = 0; DROP VIEW IF EXISTS `cloud`.`security_group_view`; -CREATE VIEW security_group_view AS -select -security_group.id id, -security_group.name name, -security_group.description description, -security_group.uuid uuid, -account.id account_id, -account.uuid account_uuid, -account.account_name account_name, -account.type account_type, -domain.id domain_id, -domain.uuid domain_uuid, -domain.name domain_name, -domain.path domain_path, -projects.id project_id, -projects.uuid project_uuid, -projects.name project_name, -security_group_rule.id rule_id, -security_group_rule.uuid rule_uuid, -security_group_rule.type rule_type, -security_group_rule.start_port rule_start_port, -security_group_rule.end_port rule_end_port, -security_group_rule.protocol rule_protocol, -security_group_rule.allowed_network_id rule_allowed_network_id, -security_group_rule.allowed_ip_cidr rule_allowed_ip_cidr, -security_group_rule.create_status rule_create_status, -resource_tags.id tag_id, -resource_tags.uuid tag_uuid, -resource_tags.key tag_key, -resource_tags.value tag_value, -resource_tags.domain_id tag_domain_id, -resource_tags.account_id tag_account_id, -resource_tags.resource_id tag_resource_id, -resource_tags.resource_uuid tag_resource_uuid, -resource_tags.resource_type tag_resource_type, -resource_tags.customer tag_customer, -async_job.id job_id, -async_job.uuid job_uuid, -async_job.job_status job_status, -async_job.account_id job_account_id -from security_group -left join security_group_rule on security_group.id = security_group_rule.security_group_id -inner join account on security_group.account_id=account.id -inner join domain on security_group.domain_id=domain.id -left join projects on projects.project_account_id = security_group.account_id -left join resource_tags on resource_tags.resource_id = security_group.id and resource_tags.resource_type = "SecurityGroup" -left join async_job on async_job.instance_id = security_group.id and async_job.instance_type = "SecurityGroup" and async_job.job_status = 0; +CREATE VIEW `cloud`.`security_group_view` AS + select + security_group.id id, + security_group.name name, + security_group.description description, + security_group.uuid uuid, + account.id account_id, + account.uuid account_uuid, + account.account_name account_name, + account.type account_type, + domain.id domain_id, + domain.uuid domain_uuid, + domain.name domain_name, + domain.path domain_path, + projects.id project_id, + projects.uuid project_uuid, + projects.name project_name, + security_group_rule.id rule_id, + security_group_rule.uuid rule_uuid, + security_group_rule.type rule_type, + security_group_rule.start_port rule_start_port, + security_group_rule.end_port rule_end_port, + security_group_rule.protocol rule_protocol, + security_group_rule.allowed_network_id rule_allowed_network_id, + security_group_rule.allowed_ip_cidr rule_allowed_ip_cidr, + security_group_rule.create_status rule_create_status, + resource_tags.id tag_id, + resource_tags.uuid tag_uuid, + resource_tags.key tag_key, + resource_tags.value tag_value, + resource_tags.domain_id tag_domain_id, + resource_tags.account_id tag_account_id, + resource_tags.resource_id tag_resource_id, + resource_tags.resource_uuid tag_resource_uuid, + resource_tags.resource_type tag_resource_type, + resource_tags.customer tag_customer, + async_job.id job_id, + async_job.uuid job_uuid, + async_job.job_status job_status, + async_job.account_id job_account_id + from + `cloud`.`security_group` + left join + `cloud`.`security_group_rule` ON security_group.id = security_group_rule.security_group_id + inner join + `cloud`.`account` ON security_group.account_id = account.id + inner join + `cloud`.`domain` ON security_group.domain_id = domain.id + left join + `cloud`.`projects` ON projects.project_account_id = security_group.account_id + left join + `cloud`.`resource_tags` ON resource_tags.resource_id = security_group.id + and resource_tags.resource_type = 'SecurityGroup' + left join + `cloud`.`async_job` ON async_job.instance_id = security_group.id + and async_job.instance_type = 'SecurityGroup' + and async_job.job_status = 0; DROP VIEW IF EXISTS `cloud`.`resource_tag_view`; -CREATE VIEW resource_tag_view AS -select -resource_tags.id, -resource_tags.uuid, -resource_tags.key, -resource_tags.value, -resource_tags.resource_id, -resource_tags.resource_uuid, -resource_tags.resource_type, -resource_tags.customer, -account.id account_id, -account.uuid account_uuid, -account.account_name account_name, -account.type account_type, -domain.id domain_id, -domain.uuid domain_uuid, -domain.name domain_name, -domain.path domain_path, -projects.id project_id, -projects.uuid project_uuid, -projects.name project_name -from resource_tags -inner join account on resource_tags.account_id=account.id -inner join domain on resource_tags.domain_id=domain.id -left join projects on projects.project_account_id = resource_tags.account_id; +CREATE VIEW `cloud`.`resource_tag_view` AS + select + resource_tags.id, + resource_tags.uuid, + resource_tags.key, + resource_tags.value, + resource_tags.resource_id, + resource_tags.resource_uuid, + resource_tags.resource_type, + resource_tags.customer, + account.id account_id, + account.uuid account_uuid, + account.account_name account_name, + account.type account_type, + domain.id domain_id, + domain.uuid domain_uuid, + domain.name domain_name, + domain.path domain_path, + projects.id project_id, + projects.uuid project_uuid, + projects.name project_name + from + `cloud`.`resource_tags` + inner join + `cloud`.`account` ON resource_tags.account_id = account.id + inner join + `cloud`.`domain` ON resource_tags.domain_id = domain.id + left join + `cloud`.`projects` ON projects.project_account_id = resource_tags.account_id; DROP VIEW IF EXISTS `cloud`.`event_view`; -CREATE VIEW event_view AS -select -event.id, -event.uuid, -event.type, -event.state, -event.description, -event.created, -event.level, -event.parameters, -event.start_id, -eve.uuid start_uuid, -event.user_id, -user.username user_name, -account.id account_id, -account.uuid account_uuid, -account.account_name account_name, -account.type account_type, -domain.id domain_id, -domain.uuid domain_uuid, -domain.name domain_name, -domain.path domain_path, -projects.id project_id, -projects.uuid project_uuid, -projects.name project_name -from event -inner join account on event.account_id=account.id -inner join domain on event.domain_id=domain.id -inner join user on event.user_id = user.id -left join projects on projects.project_account_id = event.account_id -left join event eve on event.start_id = eve.id; +CREATE VIEW `cloud`.`event_view` AS + select + event.id, + event.uuid, + event.type, + event.state, + event.description, + event.created, + event.level, + event.parameters, + event.start_id, + eve.uuid start_uuid, + event.user_id, + user.username user_name, + account.id account_id, + account.uuid account_uuid, + account.account_name account_name, + account.type account_type, + domain.id domain_id, + domain.uuid domain_uuid, + domain.name domain_name, + domain.path domain_path, + projects.id project_id, + projects.uuid project_uuid, + projects.name project_name + from + `cloud`.`event` + inner join + `cloud`.`account` ON event.account_id = account.id + inner join + `cloud`.`domain` ON event.domain_id = domain.id + inner join + `cloud`.`user` ON event.user_id = user.id + left join + `cloud`.`projects` ON projects.project_account_id = event.account_id + left join + `cloud`.`event` eve ON event.start_id = eve.id; DROP VIEW IF EXISTS `cloud`.`instance_group_view`; -CREATE VIEW instance_group_view AS -select -instance_group.id, -instance_group.uuid, -instance_group.name, -instance_group.removed, -instance_group.created, -account.id account_id, -account.uuid account_uuid, -account.account_name account_name, -account.type account_type, -domain.id domain_id, -domain.uuid domain_uuid, -domain.name domain_name, -domain.path domain_path, -projects.id project_id, -projects.uuid project_uuid, -projects.name project_name -from instance_group -inner join account on instance_group.account_id=account.id -inner join domain on account.domain_id=domain.id -left join projects on projects.project_account_id = instance_group.account_id; +CREATE VIEW `cloud`.`instance_group_view` AS + select + instance_group.id, + instance_group.uuid, + instance_group.name, + instance_group.removed, + instance_group.created, + account.id account_id, + account.uuid account_uuid, + account.account_name account_name, + account.type account_type, + domain.id domain_id, + domain.uuid domain_uuid, + domain.name domain_name, + domain.path domain_path, + projects.id project_id, + projects.uuid project_uuid, + projects.name project_name + from + `cloud`.`instance_group` + inner join + `cloud`.`account` ON instance_group.account_id = account.id + inner join + `cloud`.`domain` ON account.domain_id = domain.id + left join + `cloud`.`projects` ON projects.project_account_id = instance_group.account_id; DROP VIEW IF EXISTS `cloud`.`user_view`; -CREATE VIEW user_view AS -select -user.id, -user.uuid, -user.username, -user.password, -user.firstname, -user.lastname, -user.email, -user.state, -user.api_key, -user.secret_key, -user.created, -user.removed, -user.timezone, -user.registration_token, -user.is_registered, -user.incorrect_login_attempts, -account.id account_id, -account.uuid account_uuid, -account.account_name account_name, -account.type account_type, -domain.id domain_id, -domain.uuid domain_uuid, -domain.name domain_name, -domain.path domain_path, -async_job.id job_id, -async_job.uuid job_uuid, -async_job.job_status job_status, -async_job.account_id job_account_id -from user -inner join account on user.account_id = account.id -inner join domain on account.domain_id=domain.id -left join async_job on async_job.instance_id = user.id and async_job.instance_type = "User" and async_job.job_status = 0; - - +CREATE VIEW `cloud`.`user_view` AS + select + user.id, + user.uuid, + user.username, + user.password, + user.firstname, + user.lastname, + user.email, + user.state, + user.api_key, + user.secret_key, + user.created, + user.removed, + user.timezone, + user.registration_token, + user.is_registered, + user.incorrect_login_attempts, + account.id account_id, + account.uuid account_uuid, + account.account_name account_name, + account.type account_type, + domain.id domain_id, + domain.uuid domain_uuid, + domain.name domain_name, + domain.path domain_path, + async_job.id job_id, + async_job.uuid job_uuid, + async_job.job_status job_status, + async_job.account_id job_account_id + from + `cloud`.`user` + inner join + `cloud`.`account` ON user.account_id = account.id + inner join + `cloud`.`domain` ON account.domain_id = domain.id + left join + `cloud`.`async_job` ON async_job.instance_id = user.id + and async_job.instance_type = 'User' + and async_job.job_status = 0; DROP VIEW IF EXISTS `cloud`.`project_view`; -CREATE VIEW project_view AS -select -projects.id, -projects.uuid, -projects.name, -projects.display_text, -projects.state, -projects.removed, -projects.created, -account.account_name owner, -pacct.account_id, -domain.id domain_id, -domain.uuid domain_uuid, -domain.name domain_name, -domain.path domain_path, -resource_tags.id tag_id, -resource_tags.uuid tag_uuid, -resource_tags.key tag_key, -resource_tags.value tag_value, -resource_tags.domain_id tag_domain_id, -resource_tags.account_id tag_account_id, -resource_tags.resource_id tag_resource_id, -resource_tags.resource_uuid tag_resource_uuid, -resource_tags.resource_type tag_resource_type, -resource_tags.customer tag_customer -from projects -inner join domain on projects.domain_id=domain.id -inner join project_account on projects.id = project_account.project_id and project_account.account_role = "Admin" -inner join account on account.id = project_account.account_id -left join resource_tags on resource_tags.resource_id = projects.id and resource_tags.resource_type = "Project" -left join project_account pacct on projects.id = pacct.project_id; +CREATE VIEW `cloud`.`project_view` AS + select + projects.id, + projects.uuid, + projects.name, + projects.display_text, + projects.state, + projects.removed, + projects.created, + account.account_name owner, + pacct.account_id, + domain.id domain_id, + domain.uuid domain_uuid, + domain.name domain_name, + domain.path domain_path, + resource_tags.id tag_id, + resource_tags.uuid tag_uuid, + resource_tags.key tag_key, + resource_tags.value tag_value, + resource_tags.domain_id tag_domain_id, + resource_tags.account_id tag_account_id, + resource_tags.resource_id tag_resource_id, + resource_tags.resource_uuid tag_resource_uuid, + resource_tags.resource_type tag_resource_type, + resource_tags.customer tag_customer + from + `cloud`.`projects` + inner join + `cloud`.`domain` ON projects.domain_id = domain.id + inner join + `cloud`.`project_account` ON projects.id = project_account.project_id + and project_account.account_role = 'Admin' + inner join + `cloud`.`account` ON account.id = project_account.account_id + left join + `cloud`.`resource_tags` ON resource_tags.resource_id = projects.id + and resource_tags.resource_type = 'Project' + left join + `cloud`.`project_account` pacct ON projects.id = pacct.project_id; DROP VIEW IF EXISTS `cloud`.`project_account_view`; -CREATE VIEW project_account_view AS -select -project_account.id, -account.id account_id, -account.uuid account_uuid, -account.account_name, -account.type account_type, -project_account.account_role, -projects.id project_id, -projects.uuid project_uuid, -projects.name project_name, -domain.id domain_id, -domain.uuid domain_uuid, -domain.name domain_name, -domain.path domain_path -from project_account -inner join account on project_account.account_id = account.id -inner join domain on account.domain_id=domain.id -inner join projects on projects.id = project_account.project_id; +CREATE VIEW `cloud`.`project_account_view` AS + select + project_account.id, + account.id account_id, + account.uuid account_uuid, + account.account_name, + account.type account_type, + project_account.account_role, + projects.id project_id, + projects.uuid project_uuid, + projects.name project_name, + domain.id domain_id, + domain.uuid domain_uuid, + domain.name domain_name, + domain.path domain_path + from + `cloud`.`project_account` + inner join + `cloud`.`account` ON project_account.account_id = account.id + inner join + `cloud`.`domain` ON account.domain_id = domain.id + inner join + `cloud`.`projects` ON projects.id = project_account.project_id; DROP VIEW IF EXISTS `cloud`.`project_invitation_view`; -CREATE VIEW project_invitation_view AS -select -project_invitations.id, -project_invitations.uuid, -project_invitations.email, -project_invitations.created, -project_invitations.state, -projects.id project_id, -projects.uuid project_uuid, -projects.name project_name, -account.id account_id, -account.uuid account_uuid, -account.account_name, -account.type account_type, -domain.id domain_id, -domain.uuid domain_uuid, -domain.name domain_name, -domain.path domain_path -from project_invitations -left join account on project_invitations.account_id = account.id -left join domain on project_invitations.domain_id=domain.id -left join projects on projects.id = project_invitations.project_id; +CREATE VIEW `cloud`.`project_invitation_view` AS + select + project_invitations.id, + project_invitations.uuid, + project_invitations.email, + project_invitations.created, + project_invitations.state, + projects.id project_id, + projects.uuid project_uuid, + projects.name project_name, + account.id account_id, + account.uuid account_uuid, + account.account_name, + account.type account_type, + domain.id domain_id, + domain.uuid domain_uuid, + domain.name domain_name, + domain.path domain_path + from + `cloud`.`project_invitations` + left join + `cloud`.`account` ON project_invitations.account_id = account.id + left join + `cloud`.`domain` ON project_invitations.domain_id = domain.id + left join + `cloud`.`projects` ON projects.id = project_invitations.project_id; DROP VIEW IF EXISTS `cloud`.`host_view`; -CREATE VIEW host_view AS -select -host.id, -host.uuid, -host.name, -host.status, -host.disconnected, -host.type, -host.private_ip_address, -host.version, -host.hypervisor_type, -host.hypervisor_version, -host.capabilities, -host.last_ping, -host.created, -host.removed, -host.resource_state, -host.mgmt_server_id, -host.cpus, -host.speed, -host.ram, -cluster.id cluster_id, -cluster.uuid cluster_uuid, -cluster.name cluster_name, -cluster.cluster_type, -data_center.id data_center_id, -data_center.uuid data_center_uuid, -data_center.name data_center_name, -host_pod_ref.id pod_id, -host_pod_ref.uuid pod_uuid, -host_pod_ref.name pod_name, -host_tags.tag, -guest_os_category.id guest_os_category_id, -guest_os_category.uuid guest_os_category_uuid, -guest_os_category.name guest_os_category_name, -mem_caps.used_capacity memory_used_capacity, -mem_caps.reserved_capacity memory_reserved_capacity, -cpu_caps.used_capacity cpu_used_capacity, -cpu_caps.reserved_capacity cpu_reserved_capacity, -async_job.id job_id, -async_job.uuid job_uuid, -async_job.job_status job_status, -async_job.account_id job_account_id -from host -left join cluster on host.cluster_id = cluster.id -left join data_center on host.data_center_id = data_center.id -left join host_pod_ref on host.pod_id = host_pod_ref.id -left join host_details on host.id = host_details.id and host_details.name = "guest.os.category.id" -left join guest_os_category on guest_os_category.id = CONVERT( host_details.value, UNSIGNED ) -left join host_tags on host_tags.host_id = host.id -left join op_host_capacity mem_caps on host.id = mem_caps.host_id and mem_caps.capacity_type = 0 -left join op_host_capacity cpu_caps on host.id = cpu_caps.host_id and cpu_caps.capacity_type = 1 -left join async_job on async_job.instance_id = host.id and async_job.instance_type = "Host" and async_job.job_status = 0; +CREATE VIEW `cloud`.`host_view` AS + select + host.id, + host.uuid, + host.name, + host.status, + host.disconnected, + host.type, + host.private_ip_address, + host.version, + host.hypervisor_type, + host.hypervisor_version, + host.capabilities, + host.last_ping, + host.created, + host.removed, + host.resource_state, + host.mgmt_server_id, + host.cpus, + host.speed, + host.ram, + cluster.id cluster_id, + cluster.uuid cluster_uuid, + cluster.name cluster_name, + cluster.cluster_type, + data_center.id data_center_id, + data_center.uuid data_center_uuid, + data_center.name data_center_name, + host_pod_ref.id pod_id, + host_pod_ref.uuid pod_uuid, + host_pod_ref.name pod_name, + host_tags.tag, + guest_os_category.id guest_os_category_id, + guest_os_category.uuid guest_os_category_uuid, + guest_os_category.name guest_os_category_name, + mem_caps.used_capacity memory_used_capacity, + mem_caps.reserved_capacity memory_reserved_capacity, + cpu_caps.used_capacity cpu_used_capacity, + cpu_caps.reserved_capacity cpu_reserved_capacity, + async_job.id job_id, + async_job.uuid job_uuid, + async_job.job_status job_status, + async_job.account_id job_account_id + from + `cloud`.`host` + left join + `cloud`.`cluster` ON host.cluster_id = cluster.id + left join + `cloud`.`data_center` ON host.data_center_id = data_center.id + left join + `cloud`.`host_pod_ref` ON host.pod_id = host_pod_ref.id + left join + `cloud`.`host_details` ON host.id = host_details.id + and host_details.name = 'guest.os.category.id' + left join + `cloud`.`guest_os_category` ON guest_os_category.id = CONVERT( host_details.value , UNSIGNED) + left join + `cloud`.`host_tags` ON host_tags.host_id = host.id + left join + `cloud`.`op_host_capacity` mem_caps ON host.id = mem_caps.host_id + and mem_caps.capacity_type = 0 + left join + `cloud`.`op_host_capacity` cpu_caps ON host.id = cpu_caps.host_id + and cpu_caps.capacity_type = 1 + left join + `cloud`.`async_job` ON async_job.instance_id = host.id + and async_job.instance_type = 'Host' + and async_job.job_status = 0; DROP VIEW IF EXISTS `cloud`.`volume_view`; -CREATE VIEW volume_view AS -select -volumes.id, -volumes.uuid, -volumes.name, -volumes.device_id, -volumes.volume_type, -volumes.size, -volumes.created, -volumes.state, -volumes.attached, -volumes.removed, -volumes.pod_id, -account.id account_id, -account.uuid account_uuid, -account.account_name account_name, -account.type account_type, -domain.id domain_id, -domain.uuid domain_uuid, -domain.name domain_name, -domain.path domain_path, -projects.id project_id, -projects.uuid project_uuid, -projects.name project_name, -data_center.id data_center_id, -data_center.uuid data_center_uuid, -data_center.name data_center_name, -vm_instance.id vm_id, -vm_instance.uuid vm_uuid, -vm_instance.name vm_name, -vm_instance.state vm_state, -vm_instance.vm_type, -user_vm.display_name vm_display_name, -volume_host_ref.size volume_host_size, -volume_host_ref.created volume_host_created, -volume_host_ref.format, -volume_host_ref.download_pct, -volume_host_ref.download_state, -volume_host_ref.error_str, -disk_offering.id disk_offering_id, -disk_offering.uuid disk_offering_uuid, -disk_offering.name disk_offering_name, -disk_offering.display_text disk_offering_display_text, -disk_offering.use_local_storage, -disk_offering.system_use, -storage_pool.id pool_id, -storage_pool.uuid pool_uuid, -storage_pool.name pool_name, -cluster.hypervisor_type, -vm_template.id template_id, -vm_template.uuid template_uuid, -vm_template.extractable, -vm_template.type template_type, -resource_tags.id tag_id, -resource_tags.uuid tag_uuid, -resource_tags.key tag_key, -resource_tags.value tag_value, -resource_tags.domain_id tag_domain_id, -resource_tags.account_id tag_account_id, -resource_tags.resource_id tag_resource_id, -resource_tags.resource_uuid tag_resource_uuid, -resource_tags.resource_type tag_resource_type, -resource_tags.customer tag_customer, -async_job.id job_id, -async_job.uuid job_uuid, -async_job.job_status job_status, -async_job.account_id job_account_id -from volumes -inner join account on volumes.account_id=account.id -inner join domain on volumes.domain_id=domain.id -left join projects on projects.project_account_id = account.id -left join data_center on volumes.data_center_id = data_center.id -left join vm_instance on volumes.instance_id = vm_instance.id -left join user_vm on user_vm.id = vm_instance.id -left join volume_host_ref on volumes.id = volume_host_ref.volume_id and volumes.data_center_id = volume_host_ref.zone_id -left join disk_offering on volumes.disk_offering_id = disk_offering.id -left join storage_pool on volumes.pool_id = storage_pool.id -left join cluster on storage_pool.cluster_id = cluster.id -left join vm_template on volumes.template_id = vm_template.id -left join resource_tags on resource_tags.resource_id = volumes.id and resource_tags.resource_type = "Volume" -left join async_job on async_job.instance_id = volumes.id and async_job.instance_type = "Volume" and async_job.job_status = 0; +CREATE VIEW `cloud`.`volume_view` AS + select + volumes.id, + volumes.uuid, + volumes.name, + volumes.device_id, + volumes.volume_type, + volumes.size, + volumes.created, + volumes.state, + volumes.attached, + volumes.removed, + volumes.pod_id, + account.id account_id, + account.uuid account_uuid, + account.account_name account_name, + account.type account_type, + domain.id domain_id, + domain.uuid domain_uuid, + domain.name domain_name, + domain.path domain_path, + projects.id project_id, + projects.uuid project_uuid, + projects.name project_name, + data_center.id data_center_id, + data_center.uuid data_center_uuid, + data_center.name data_center_name, + vm_instance.id vm_id, + vm_instance.uuid vm_uuid, + vm_instance.name vm_name, + vm_instance.state vm_state, + vm_instance.vm_type, + user_vm.display_name vm_display_name, + volume_host_ref.size volume_host_size, + volume_host_ref.created volume_host_created, + volume_host_ref.format, + volume_host_ref.download_pct, + volume_host_ref.download_state, + volume_host_ref.error_str, + disk_offering.id disk_offering_id, + disk_offering.uuid disk_offering_uuid, + disk_offering.name disk_offering_name, + disk_offering.display_text disk_offering_display_text, + disk_offering.use_local_storage, + disk_offering.system_use, + storage_pool.id pool_id, + storage_pool.uuid pool_uuid, + storage_pool.name pool_name, + cluster.hypervisor_type, + vm_template.id template_id, + vm_template.uuid template_uuid, + vm_template.extractable, + vm_template.type template_type, + resource_tags.id tag_id, + resource_tags.uuid tag_uuid, + resource_tags.key tag_key, + resource_tags.value tag_value, + resource_tags.domain_id tag_domain_id, + resource_tags.account_id tag_account_id, + resource_tags.resource_id tag_resource_id, + resource_tags.resource_uuid tag_resource_uuid, + resource_tags.resource_type tag_resource_type, + resource_tags.customer tag_customer, + async_job.id job_id, + async_job.uuid job_uuid, + async_job.job_status job_status, + async_job.account_id job_account_id + from + `cloud`.`volumes` + inner join + `cloud`.`account` ON volumes.account_id = account.id + inner join + `cloud`.`domain` ON volumes.domain_id = domain.id + left join + `cloud`.`projects` ON projects.project_account_id = account.id + left join + `cloud`.`data_center` ON volumes.data_center_id = data_center.id + left join + `cloud`.`vm_instance` ON volumes.instance_id = vm_instance.id + left join + `cloud`.`user_vm` ON user_vm.id = vm_instance.id + left join + `cloud`.`volume_host_ref` ON volumes.id = volume_host_ref.volume_id + and volumes.data_center_id = volume_host_ref.zone_id + left join + `cloud`.`disk_offering` ON volumes.disk_offering_id = disk_offering.id + left join + `cloud`.`storage_pool` ON volumes.pool_id = storage_pool.id + left join + `cloud`.`cluster` ON storage_pool.cluster_id = cluster.id + left join + `cloud`.`vm_template` ON volumes.template_id = vm_template.id + left join + `cloud`.`resource_tags` ON resource_tags.resource_id = volumes.id + and resource_tags.resource_type = 'Volume' + left join + `cloud`.`async_job` ON async_job.instance_id = volumes.id + and async_job.instance_type = 'Volume' + and async_job.job_status = 0; DROP VIEW IF EXISTS `cloud`.`account_netstats_view`; -CREATE VIEW account_netstats_view AS -SELECT account_id, -sum(net_bytes_received)+ sum(current_bytes_received) as bytesReceived, -sum(net_bytes_sent)+ sum(current_bytes_sent) as bytesSent -FROM user_statistics -group by account_id; +CREATE VIEW `cloud`.`account_netstats_view` AS + SELECT + account_id, + sum(net_bytes_received) + sum(current_bytes_received) as bytesReceived, + sum(net_bytes_sent) + sum(current_bytes_sent) as bytesSent + FROM + `cloud`.`user_statistics` + group by account_id; DROP VIEW IF EXISTS `cloud`.`account_vmstats_view`; -CREATE VIEW account_vmstats_view AS -SELECT account_id, state, count(*) as vmcount -from vm_instance -group by account_id, state; +CREATE VIEW `cloud`.`account_vmstats_view` AS + SELECT + account_id, state, count(*) as vmcount + from + `cloud`.`vm_instance` + group by account_id , state; DROP VIEW IF EXISTS `cloud`.`free_ip_view`; -CREATE VIEW free_ip_view AS -select count(user_ip_address.id) free_ip -from user_ip_address -inner join vlan on vlan.id = user_ip_address.vlan_db_id and vlan.vlan_type = "VirtualNetwork" -where state = "Free"; +CREATE VIEW `cloud`.`free_ip_view` AS + select + count(user_ip_address.id) free_ip + from + `cloud`.`user_ip_address` + inner join + `cloud`.`vlan` ON vlan.id = user_ip_address.vlan_db_id + and vlan.vlan_type = 'VirtualNetwork' + where + state = 'Free'; DROP VIEW IF EXISTS `cloud`.`account_view`; -CREATE VIEW account_view AS -select -account.id, -account.uuid, -account.account_name, -account.type, -account.state, -account.removed, -account.cleanup_needed, -account.network_domain, -domain.id domain_id, -domain.uuid domain_uuid, -domain.name domain_name, -domain.path domain_path, -data_center.id data_center_id, -data_center.uuid data_center_uuid, -data_center.name data_center_name, -account_netstats_view.bytesReceived, -account_netstats_view.bytesSent, -vmlimit.max vmLimit, -vmcount.count vmTotal, -runningvm.vmcount runningVms, -stoppedvm.vmcount stoppedVms, -iplimit.max ipLimit, -ipcount.count ipTotal, -free_ip_view.free_ip ipFree, -volumelimit.max volumeLimit, -volumecount.count volumeTotal, -snapshotlimit.max snapshotLimit, -snapshotcount.count snapshotTotal, -templatelimit.max templateLimit, -templatecount.count templateTotal, -vpclimit.max vpcLimit, -vpccount.count vpcTotal, -projectlimit.max projectLimit, -projectcount.count projectTotal, -networklimit.max networkLimit, -networkcount.count networkTotal, -async_job.id job_id, -async_job.uuid job_uuid, -async_job.job_status job_status, -async_job.account_id job_account_id -from free_ip_view, account -inner join domain on account.domain_id=domain.id -left join data_center on account.default_zone_id = data_center.id -left join account_netstats_view on account.id = account_netstats_view.account_id -left join resource_limit vmlimit on account.id = vmlimit.account_id and vmlimit.type = "user_vm" -left join resource_count vmcount on account.id = vmcount.account_id and vmcount.type = "user_vm" -left join account_vmstats_view runningvm on account.id = runningvm.account_id and runningvm.state = "Running" -left join account_vmstats_view stoppedvm on account.id = stoppedvm.account_id and stoppedvm.state = "Stopped" -left join resource_limit iplimit on account.id = iplimit.account_id and iplimit.type = "public_ip" -left join resource_count ipcount on account.id = ipcount.account_id and ipcount.type = "public_ip" -left join resource_limit volumelimit on account.id = volumelimit.account_id and volumelimit.type = "volume" -left join resource_count volumecount on account.id = volumecount.account_id and volumecount.type = "volume" -left join resource_limit snapshotlimit on account.id = snapshotlimit.account_id and snapshotlimit.type = "snapshot" -left join resource_count snapshotcount on account.id = snapshotcount.account_id and snapshotcount.type = "snapshot" -left join resource_limit templatelimit on account.id = templatelimit.account_id and templatelimit.type = "template" -left join resource_count templatecount on account.id = templatecount.account_id and templatecount.type = "template" -left join resource_limit vpclimit on account.id = vpclimit.account_id and vpclimit.type = "vpc" -left join resource_count vpccount on account.id = vpccount.account_id and vpccount.type = "vpc" -left join resource_limit projectlimit on account.id = projectlimit.account_id and projectlimit.type = "project" -left join resource_count projectcount on account.id = projectcount.account_id and projectcount.type = "project" -left join resource_limit networklimit on account.id = networklimit.account_id and networklimit.type = "network" -left join resource_count networkcount on account.id = networkcount.account_id and networkcount.type = "network" -left join async_job on async_job.instance_id = account.id and async_job.instance_type = "Account" and async_job.job_status = 0; +CREATE VIEW `cloud`.`account_view` AS + select + account.id, + account.uuid, + account.account_name, + account.type, + account.state, + account.removed, + account.cleanup_needed, + account.network_domain, + domain.id domain_id, + domain.uuid domain_uuid, + domain.name domain_name, + domain.path domain_path, + data_center.id data_center_id, + data_center.uuid data_center_uuid, + data_center.name data_center_name, + account_netstats_view.bytesReceived, + account_netstats_view.bytesSent, + vmlimit.max vmLimit, + vmcount.count vmTotal, + runningvm.vmcount runningVms, + stoppedvm.vmcount stoppedVms, + iplimit.max ipLimit, + ipcount.count ipTotal, + free_ip_view.free_ip ipFree, + volumelimit.max volumeLimit, + volumecount.count volumeTotal, + snapshotlimit.max snapshotLimit, + snapshotcount.count snapshotTotal, + templatelimit.max templateLimit, + templatecount.count templateTotal, + vpclimit.max vpcLimit, + vpccount.count vpcTotal, + projectlimit.max projectLimit, + projectcount.count projectTotal, + networklimit.max networkLimit, + networkcount.count networkTotal, + async_job.id job_id, + async_job.uuid job_uuid, + async_job.job_status job_status, + async_job.account_id job_account_id + from + `cloud`.`free_ip_view`, + `cloud`.`account` + inner join + `cloud`.`domain` ON account.domain_id = domain.id + left join + `cloud`.`data_center` ON account.default_zone_id = data_center.id + left join + `cloud`.`account_netstats_view` ON account.id = account_netstats_view.account_id + left join + `cloud`.`resource_limit` vmlimit ON account.id = vmlimit.account_id + and vmlimit.type = 'user_vm' + left join + `cloud`.`resource_count` vmcount ON account.id = vmcount.account_id + and vmcount.type = 'user_vm' + left join + `cloud`.`account_vmstats_view` runningvm ON account.id = runningvm.account_id + and runningvm.state = 'Running' + left join + `cloud`.`account_vmstats_view` stoppedvm ON account.id = stoppedvm.account_id + and stoppedvm.state = 'Stopped' + left join + `cloud`.`resource_limit` iplimit ON account.id = iplimit.account_id + and iplimit.type = 'public_ip' + left join + `cloud`.`resource_count` ipcount ON account.id = ipcount.account_id + and ipcount.type = 'public_ip' + left join + `cloud`.`resource_limit` volumelimit ON account.id = volumelimit.account_id + and volumelimit.type = 'volume' + left join + `cloud`.`resource_count` volumecount ON account.id = volumecount.account_id + and volumecount.type = 'volume' + left join + `cloud`.`resource_limit` snapshotlimit ON account.id = snapshotlimit.account_id + and snapshotlimit.type = 'snapshot' + left join + `cloud`.`resource_count` snapshotcount ON account.id = snapshotcount.account_id + and snapshotcount.type = 'snapshot' + left join + `cloud`.`resource_limit` templatelimit ON account.id = templatelimit.account_id + and templatelimit.type = 'template' + left join + `cloud`.`resource_count` templatecount ON account.id = templatecount.account_id + and templatecount.type = 'template' + left join + `cloud`.`resource_limit` vpclimit ON account.id = vpclimit.account_id + and vpclimit.type = 'vpc' + left join + `cloud`.`resource_count` vpccount ON account.id = vpccount.account_id + and vpccount.type = 'vpc' + left join + `cloud`.`resource_limit` projectlimit ON account.id = projectlimit.account_id + and projectlimit.type = 'project' + left join + `cloud`.`resource_count` projectcount ON account.id = projectcount.account_id + and projectcount.type = 'project' + left join + `cloud`.`resource_limit` networklimit ON account.id = networklimit.account_id + and networklimit.type = 'network' + left join + `cloud`.`resource_count` networkcount ON account.id = networkcount.account_id + and networkcount.type = 'network' + left join + `cloud`.`async_job` ON async_job.instance_id = account.id + and async_job.instance_type = 'Account' + and async_job.job_status = 0; DROP VIEW IF EXISTS `cloud`.`async_job_view`; -CREATE VIEW async_job_view AS -select -account.id account_id, -account.uuid account_uuid, -account.account_name account_name, -account.type account_type, -domain.id domain_id, -domain.uuid domain_uuid, -domain.name domain_name, -domain.path domain_path, -user.id user_id, -user.uuid user_uuid, -async_job.id, -async_job.uuid, -async_job.job_cmd, -async_job.job_status, -async_job.job_process_status, -async_job.job_result_code, -async_job.job_result, -async_job.created, -async_job.removed, -async_job.instance_type, -async_job.instance_id, -CASE -WHEN async_job.instance_type = 'Volume' THEN volumes.uuid -WHEN async_job.instance_type = 'Template' or async_job.instance_type = 'Iso' THEN vm_template.uuid -WHEN async_job.instance_type = 'VirtualMachine' or async_job.instance_type = 'ConsoleProxy' or async_job.instance_type = 'SystemVm' or async_job.instance_type = 'DomainRouter' THEN vm_instance.uuid -WHEN async_job.instance_type = 'Snapshot' THEN snapshots.uuid -WHEN async_job.instance_type = 'Host' THEN host.uuid -WHEN async_job.instance_type = 'StoragePool' THEN storage_pool.uuid -WHEN async_job.instance_type = 'IpAddress' THEN user_ip_address.uuid -WHEN async_job.instance_type = 'SecurityGroup' THEN security_group.uuid -WHEN async_job.instance_type = 'PhysicalNetwork' THEN physical_network.uuid -WHEN async_job.instance_type = 'TrafficType' THEN physical_network_traffic_types.uuid -WHEN async_job.instance_type = 'PhysicalNetworkServiceProvider' THEN physical_network_service_providers.uuid -WHEN async_job.instance_type = 'FirewallRule' THEN firewall_rules.uuid -WHEN async_job.instance_type = 'Account' THEN acct.uuid -WHEN async_job.instance_type = 'User' THEN us.uuid -WHEN async_job.instance_type = 'StaticRoute' THEN static_routes.uuid -WHEN async_job.instance_type = 'PrivateGateway' THEN vpc_gateways.uuid -WHEN async_job.instance_type = 'Counter' THEN counter.uuid -WHEN async_job.instance_type = 'Condition' THEN conditions.uuid -WHEN async_job.instance_type = 'AutoScalePolicy' THEN autoscale_policies.uuid -WHEN async_job.instance_type = 'AutoScaleVmProfile' THEN autoscale_vmprofiles.uuid -WHEN async_job.instance_type = 'AutoScaleVmGroup' THEN autoscale_vmgroups.uuid -ELSE null -END instance_uuid -from async_job -left join account on async_job.account_id = account.id -left join domain on domain.id = account.domain_id -left join user on async_job.user_id = user.id -left join volumes on async_job.instance_id = volumes.id -left join vm_template on async_job.instance_id = vm_template.id -left join vm_instance on async_job.instance_id = vm_instance.id -left join snapshots on async_job.instance_id = snapshots.id -left join host on async_job.instance_id = host.id -left join storage_pool on async_job.instance_id = storage_pool.id -left join user_ip_address on async_job.instance_id = user_ip_address.id -left join security_group on async_job.instance_id = security_group.id -left join physical_network on async_job.instance_id = physical_network.id -left join physical_network_traffic_types on async_job.instance_id = physical_network_traffic_types.id -left join physical_network_service_providers on async_job.instance_id = physical_network_service_providers.id -left join firewall_rules on async_job.instance_id = firewall_rules.id -left join account acct on async_job.instance_id = acct.id -left join user us on async_job.instance_id = us.id -left join static_routes on async_job.instance_id = static_routes.id -left join vpc_gateways on async_job.instance_id = vpc_gateways.id -left join counter on async_job.instance_id = counter.id -left join conditions on async_job.instance_id = conditions.id -left join autoscale_policies on async_job.instance_id = autoscale_policies.id -left join autoscale_vmprofiles on async_job.instance_id = autoscale_vmprofiles.id -left join autoscale_vmgroups on async_job.instance_id = autoscale_vmgroups.id; +CREATE VIEW `cloud`.`async_job_view` AS + select + account.id account_id, + account.uuid account_uuid, + account.account_name account_name, + account.type account_type, + domain.id domain_id, + domain.uuid domain_uuid, + domain.name domain_name, + domain.path domain_path, + user.id user_id, + user.uuid user_uuid, + async_job.id, + async_job.uuid, + async_job.job_cmd, + async_job.job_status, + async_job.job_process_status, + async_job.job_result_code, + async_job.job_result, + async_job.created, + async_job.removed, + async_job.instance_type, + async_job.instance_id, + CASE + WHEN async_job.instance_type = 'Volume' THEN volumes.uuid + WHEN + async_job.instance_type = 'Template' + or async_job.instance_type = 'Iso' + THEN + vm_template.uuid + WHEN + async_job.instance_type = 'VirtualMachine' + or async_job.instance_type = 'ConsoleProxy' + or async_job.instance_type = 'SystemVm' + or async_job.instance_type = 'DomainRouter' + THEN + vm_instance.uuid + WHEN async_job.instance_type = 'Snapshot' THEN snapshots.uuid + WHEN async_job.instance_type = 'Host' THEN host.uuid + WHEN async_job.instance_type = 'StoragePool' THEN storage_pool.uuid + WHEN async_job.instance_type = 'IpAddress' THEN user_ip_address.uuid + WHEN async_job.instance_type = 'SecurityGroup' THEN security_group.uuid + WHEN async_job.instance_type = 'PhysicalNetwork' THEN physical_network.uuid + WHEN async_job.instance_type = 'TrafficType' THEN physical_network_traffic_types.uuid + WHEN async_job.instance_type = 'PhysicalNetworkServiceProvider' THEN physical_network_service_providers.uuid + WHEN async_job.instance_type = 'FirewallRule' THEN firewall_rules.uuid + WHEN async_job.instance_type = 'Account' THEN acct.uuid + WHEN async_job.instance_type = 'User' THEN us.uuid + WHEN async_job.instance_type = 'StaticRoute' THEN static_routes.uuid + WHEN async_job.instance_type = 'PrivateGateway' THEN vpc_gateways.uuid + WHEN async_job.instance_type = 'Counter' THEN counter.uuid + WHEN async_job.instance_type = 'Condition' THEN conditions.uuid + WHEN async_job.instance_type = 'AutoScalePolicy' THEN autoscale_policies.uuid + WHEN async_job.instance_type = 'AutoScaleVmProfile' THEN autoscale_vmprofiles.uuid + WHEN async_job.instance_type = 'AutoScaleVmGroup' THEN autoscale_vmgroups.uuid + ELSE null + END instance_uuid + from + `cloud`.`async_job` + left join + `cloud`.`account` ON async_job.account_id = account.id + left join + `cloud`.`domain` ON domain.id = account.domain_id + left join + `cloud`.`user` ON async_job.user_id = user.id + left join + `cloud`.`volumes` ON async_job.instance_id = volumes.id + left join + `cloud`.`vm_template` ON async_job.instance_id = vm_template.id + left join + `cloud`.`vm_instance` ON async_job.instance_id = vm_instance.id + left join + `cloud`.`snapshots` ON async_job.instance_id = snapshots.id + left join + `cloud`.`host` ON async_job.instance_id = host.id + left join + `cloud`.`storage_pool` ON async_job.instance_id = storage_pool.id + left join + `cloud`.`user_ip_address` ON async_job.instance_id = user_ip_address.id + left join + `cloud`.`security_group` ON async_job.instance_id = security_group.id + left join + `cloud`.`physical_network` ON async_job.instance_id = physical_network.id + left join + `cloud`.`physical_network_traffic_types` ON async_job.instance_id = physical_network_traffic_types.id + left join + `cloud`.`physical_network_service_providers` ON async_job.instance_id = physical_network_service_providers.id + left join + `cloud`.`firewall_rules` ON async_job.instance_id = firewall_rules.id + left join + `cloud`.`account` acct ON async_job.instance_id = acct.id + left join + `cloud`.`user` us ON async_job.instance_id = us.id + left join + `cloud`.`static_routes` ON async_job.instance_id = static_routes.id + left join + `cloud`.`vpc_gateways` ON async_job.instance_id = vpc_gateways.id + left join + `cloud`.`counter` ON async_job.instance_id = counter.id + left join + `cloud`.`conditions` ON async_job.instance_id = conditions.id + left join + `cloud`.`autoscale_policies` ON async_job.instance_id = autoscale_policies.id + left join + `cloud`.`autoscale_vmprofiles` ON async_job.instance_id = autoscale_vmprofiles.id + left join + `cloud`.`autoscale_vmgroups` ON async_job.instance_id = autoscale_vmgroups.id; DROP VIEW IF EXISTS `cloud`.`storage_pool_view`; -CREATE VIEW storage_pool_view AS -select -storage_pool.id, -storage_pool.uuid, -storage_pool.name, -storage_pool.status, -storage_pool.path, -storage_pool.pool_type, -storage_pool.host_address, -storage_pool.created, -storage_pool.removed, -storage_pool.capacity_bytes, -cluster.id cluster_id, -cluster.uuid cluster_uuid, -cluster.name cluster_name, -cluster.cluster_type, -data_center.id data_center_id, -data_center.uuid data_center_uuid, -data_center.name data_center_name, -host_pod_ref.id pod_id, -host_pod_ref.uuid pod_uuid, -host_pod_ref.name pod_name, -storage_pool_details.name tag, -op_host_capacity.used_capacity disk_used_capacity, -op_host_capacity.reserved_capacity disk_reserved_capacity, -async_job.id job_id, -async_job.uuid job_uuid, -async_job.job_status job_status, -async_job.account_id job_account_id -from storage_pool -left join cluster on storage_pool.cluster_id = cluster.id -left join data_center on storage_pool.data_center_id = data_center.id -left join host_pod_ref on storage_pool.pod_id = host_pod_ref.id -left join storage_pool_details on storage_pool_details.pool_id = storage_pool.id and storage_pool_details.value = 'true' -left join op_host_capacity on storage_pool.id = op_host_capacity.host_id and op_host_capacity.capacity_type = 3 -left join async_job on async_job.instance_id = storage_pool.id and async_job.instance_type = "StoragePool" and async_job.job_status = 0; +CREATE VIEW `cloud`.`storage_pool_view` AS + select + storage_pool.id, + storage_pool.uuid, + storage_pool.name, + storage_pool.status, + storage_pool.path, + storage_pool.pool_type, + storage_pool.host_address, + storage_pool.created, + storage_pool.removed, + storage_pool.capacity_bytes, + cluster.id cluster_id, + cluster.uuid cluster_uuid, + cluster.name cluster_name, + cluster.cluster_type, + data_center.id data_center_id, + data_center.uuid data_center_uuid, + data_center.name data_center_name, + host_pod_ref.id pod_id, + host_pod_ref.uuid pod_uuid, + host_pod_ref.name pod_name, + storage_pool_details.name tag, + op_host_capacity.used_capacity disk_used_capacity, + op_host_capacity.reserved_capacity disk_reserved_capacity, + async_job.id job_id, + async_job.uuid job_uuid, + async_job.job_status job_status, + async_job.account_id job_account_id + from + `cloud`.`storage_pool` + left join + `cloud`.`cluster` ON storage_pool.cluster_id = cluster.id + left join + `cloud`.`data_center` ON storage_pool.data_center_id = data_center.id + left join + `cloud`.`host_pod_ref` ON storage_pool.pod_id = host_pod_ref.id + left join + `cloud`.`storage_pool_details` ON storage_pool_details.pool_id = storage_pool.id + and storage_pool_details.value = 'true' + left join + `cloud`.`op_host_capacity` ON storage_pool.id = op_host_capacity.host_id + and op_host_capacity.capacity_type = 3 + left join + `cloud`.`async_job` ON async_job.instance_id = storage_pool.id + and async_job.instance_type = 'StoragePool' + and async_job.job_status = 0; DROP VIEW IF EXISTS `cloud`.`disk_offering_view`; -CREATE VIEW disk_offering_view AS -select -disk_offering.id, -disk_offering.uuid, -disk_offering.name, -disk_offering.display_text, -disk_offering.disk_size, -disk_offering.created, -disk_offering.tags, -disk_offering.customized, -disk_offering.removed, -disk_offering.use_local_storage, -disk_offering.system_use, -disk_offering.sort_key, -disk_offering.type, -domain.id domain_id, -domain.uuid domain_uuid, -domain.name domain_name, -domain.path domain_path -from disk_offering -left join domain on disk_offering.domain_id=domain.id; +CREATE VIEW `cloud`.`disk_offering_view` AS + select + disk_offering.id, + disk_offering.uuid, + disk_offering.name, + disk_offering.display_text, + disk_offering.disk_size, + disk_offering.created, + disk_offering.tags, + disk_offering.customized, + disk_offering.removed, + disk_offering.use_local_storage, + disk_offering.system_use, + disk_offering.sort_key, + disk_offering.type, + domain.id domain_id, + domain.uuid domain_uuid, + domain.name domain_name, + domain.path domain_path + from + `cloud`.`disk_offering` + left join + `cloud`.`domain` ON disk_offering.domain_id = domain.id; DROP VIEW IF EXISTS `cloud`.`service_offering_view`; -CREATE VIEW service_offering_view AS -select -service_offering.id, -disk_offering.uuid, -disk_offering.name, -disk_offering.display_text, -disk_offering.created, -disk_offering.tags, -disk_offering.removed, -disk_offering.use_local_storage, -disk_offering.system_use, -service_offering.cpu, -service_offering.speed, -service_offering.ram_size, -service_offering.nw_rate, -service_offering.mc_rate, -service_offering.ha_enabled, -service_offering.limit_cpu_use, -service_offering.host_tag, -service_offering.default_use, -service_offering.vm_type, -service_offering.sort_key, -domain.id domain_id, -domain.uuid domain_uuid, -domain.name domain_name, -domain.path domain_path -from service_offering -inner join disk_offering on service_offering.id = disk_offering.id -left join domain on disk_offering.domain_id=domain.id; +CREATE VIEW `cloud`.`service_offering_view` AS + select + service_offering.id, + disk_offering.uuid, + disk_offering.name, + disk_offering.display_text, + disk_offering.created, + disk_offering.tags, + disk_offering.removed, + disk_offering.use_local_storage, + disk_offering.system_use, + service_offering.cpu, + service_offering.speed, + service_offering.ram_size, + service_offering.nw_rate, + service_offering.mc_rate, + service_offering.ha_enabled, + service_offering.limit_cpu_use, + service_offering.host_tag, + service_offering.default_use, + service_offering.vm_type, + service_offering.sort_key, + domain.id domain_id, + domain.uuid domain_uuid, + domain.name domain_name, + domain.path domain_path + from + `cloud`.`service_offering` + inner join + `cloud`.`disk_offering` ON service_offering.id = disk_offering.id + left join + `cloud`.`domain` ON disk_offering.domain_id = domain.id; diff --git a/setup/db/db/schema-40to410.sql b/setup/db/db/schema-40to410.sql index 947059e7f94..d10239be31d 100644 --- a/setup/db/db/schema-40to410.sql +++ b/setup/db/db/schema-40to410.sql @@ -194,16 +194,11 @@ CREATE VIEW `cloud`.`user_vm_view` AS vm_template.name template_name, vm_template.display_text template_display_text, vm_template.enable_password password_enabled, --- iso.id iso_id, --- iso.uuid iso_uuid, --- iso.name iso_name, --- iso.display_text iso_display_text, --- FIXME workaround - NULL iso_id, - NULL iso_uuid, - NULL iso_name, - NULL iso_display_text, service_offering.id service_offering_id, --- end of workaround + iso.id iso_id, + iso.uuid iso_uuid, + iso.name iso_name, + iso.display_text iso_display_text, + service_offering.id service_offering_id, disk_offering.uuid service_offering_uuid, service_offering.cpu cpu, service_offering.speed speed, @@ -278,8 +273,8 @@ CREATE VIEW `cloud`.`user_vm_view` AS `cloud`.`host` ON vm_instance.host_id = host.id left join `cloud`.`vm_template` ON vm_instance.vm_template_id = vm_template.id --- left join --- `cloud`.`vm_template iso` ON iso.id = user_vm.iso_id + left join + `cloud`.`vm_template` iso ON iso.id = user_vm.iso_id left join `cloud`.`service_offering` ON vm_instance.service_offering_id = service_offering.id left join From 22e70f2c8e0bd773147d83db2e8bd6ecb3f08121 Mon Sep 17 00:00:00 2001 From: Rohit Yadav Date: Tue, 22 Jan 2013 10:55:05 -0800 Subject: [PATCH 49/80] devcloud: Update a working p.a.o url in devcloud.sql Signed-off-by: Rohit Yadav --- tools/devcloud/devcloud.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/devcloud/devcloud.sql b/tools/devcloud/devcloud.sql index cebf5a3702e..009c2b5c0d5 100644 --- a/tools/devcloud/devcloud.sql +++ b/tools/devcloud/devcloud.sql @@ -37,4 +37,4 @@ INSERT INTO `cloud`.`configuration` (instance, name, value) VALUE('DEFAULT', 'se UPDATE `cloud`.`configuration` SET value='10' where name = 'storage.overprovisioning.factor'; UPDATE `cloud`.`configuration` SET value='10' where name = 'cpu.overprovisioning.factor'; UPDATE `cloud`.`configuration` SET value='10' where name = 'mem.overprovisioning.factor'; -UPDATE `cloud`.`vm_template` SET unique_name="tiny Linux",name="tiny Linux",url="https://github.com/downloads/bhaisaab/incubator-cloudstack/ttylinux_pv.vhd",checksum="046e134e642e6d344b34648223ba4bc1",display_text="tiny Linux" where id=5; +UPDATE `cloud`.`vm_template` SET unique_name="tiny Linux",name="tiny Linux",url="http://people.apache.org/~bhaisaab/vms/ttylinux_pv.vhd",checksum="046e134e642e6d344b34648223ba4bc1",display_text="tiny Linux" where id=5; From 2e14cf5b5772a6c19d3da0dfae71804200a76abe Mon Sep 17 00:00:00 2001 From: Marcus Sorensen Date: Tue, 22 Jan 2013 12:05:55 -0700 Subject: [PATCH 50/80] Summary: Allow for same vlan num on different physical NICs Detail: A previous bug in the database schema did not allow the same vlan num to exist on separate physical networks, even though this is possible and should be allowed. To fix this, the code was changed to also disallow the same vlan num on different physical networks, to avoid hitting the database constraint. The database constraint has now been changed to allow only one of a vlan num per physical nic per data center, so different physical nics can reuse vlan numbers. This fix adjusts the code to match by removing the old fix. BUG-ID: CLOUDSTACK-686 Signed-off-by: Marcus Sorensen 1358881555 -0700 --- .../com/cloud/network/NetworkServiceImpl.java | 24 ------------------- 1 file changed, 24 deletions(-) diff --git a/server/src/com/cloud/network/NetworkServiceImpl.java b/server/src/com/cloud/network/NetworkServiceImpl.java index b05aece918e..7530e943116 100755 --- a/server/src/com/cloud/network/NetworkServiceImpl.java +++ b/server/src/com/cloud/network/NetworkServiceImpl.java @@ -1814,9 +1814,6 @@ public class NetworkServiceImpl implements NetworkService, Manager { throw new InvalidParameterValueException("Please specify valid integers for the vlan range."); } - //check for vnet conflicts with other physical network(s) in the zone - checkGuestVnetsConflicts(zoneId, vnetStart, vnetEnd, null); - if ((vnetStart > vnetEnd) || (vnetStart < 0) || (vnetEnd > 4096)) { s_logger.warn("Invalid vnet range: start range:" + vnetStart + " end range:" + vnetEnd); throw new InvalidParameterValueException("Vnet range should be between 0-4096 and start range should be lesser than or equal to end range"); @@ -1995,9 +1992,6 @@ public class NetworkServiceImpl implements NetworkService, Manager { throw new InvalidParameterValueException("Vnet range has to be" + rangeMessage + " and start range should be lesser than or equal to stop range"); } - //check if new vnet conflicts with vnet ranges of other physical networks - checkGuestVnetsConflicts(network.getDataCenterId(), newStartVnet, newEndVnet, network.getId()); - if (physicalNetworkHasAllocatedVnets(network.getDataCenterId(), network.getId())) { String[] existingRange = network.getVnet().split("-"); int existingStartVnet = Integer.parseInt(existingRange[0]); @@ -2042,24 +2036,6 @@ public class NetworkServiceImpl implements NetworkService, Manager { return network; } - protected void checkGuestVnetsConflicts(long zoneId, int newStartVnet, int newEndVnet, Long pNtwkIdToSkip) { - List pNtwks = _physicalNetworkDao.listByZone(zoneId); - for (PhysicalNetwork pNtwk : pNtwks) { - // skip my own network and networks that don't have vnet range set - if ((pNtwk.getVnet() == null || pNtwk.getVnet().isEmpty()) || (pNtwkIdToSkip != null && pNtwkIdToSkip == pNtwk.getId())) { - continue; - } - String[] existingRange = pNtwk.getVnet().split("-"); - int startVnet = Integer.parseInt(existingRange[0]); - int endVnet = Integer.parseInt(existingRange[1]); - if ((newStartVnet >= startVnet && newStartVnet <= endVnet) - || (newEndVnet <= endVnet && newEndVnet >= startVnet)) { - throw new InvalidParameterValueException("Vnet range for physical network conflicts with another " + - "physical network's vnet in the zone"); - } - } - } - private boolean physicalNetworkHasAllocatedVnets(long zoneId, long physicalNetworkId) { return !_dcDao.listAllocatedVnets(physicalNetworkId).isEmpty(); } From 45d21c32021ee262004fd777aabe56e6e5dc5912 Mon Sep 17 00:00:00 2001 From: Chip Childers Date: Tue, 22 Jan 2013 16:44:34 -0500 Subject: [PATCH 51/80] Devcloud config for basic zone + management server. Added a devcloud config that supports having the management server run within devcloud, using the basic zone setup. Signed-off-by: Chip Childers --- tools/devcloud/devcloud_internal-mgt.cfg | 121 +++++++++++++++++++++++ 1 file changed, 121 insertions(+) create mode 100644 tools/devcloud/devcloud_internal-mgt.cfg diff --git a/tools/devcloud/devcloud_internal-mgt.cfg b/tools/devcloud/devcloud_internal-mgt.cfg new file mode 100644 index 00000000000..fe3dd1b41da --- /dev/null +++ b/tools/devcloud/devcloud_internal-mgt.cfg @@ -0,0 +1,121 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# + +{ + "zones": [ + { + "name": "DevCloud0", + "physical_networks": [ + { + "broadcastdomainrange": "Zone", + "name": "test-network", + "traffictypes": [ + { + "typ": "Guest" + }, + { + "typ": "Management" + } + ], + "providers": [ + { + "broadcastdomainrange": "ZONE", + "name": "VirtualRouter" + }, + { + "broadcastdomainrange": "Pod", + "name": "SecurityGroupProvider" + } + ] + } + ], + "dns2": "4.4.4.4", + "dns1": "8.8.8.8", + "securitygroupenabled": "true", + "localstorageenabled": "true", + "networktype": "Basic", + "pods": [ + { + "endip": "192.168.56.220", + "name": "test00", + "startip": "192.168.56.200", + "guestIpRanges": [ + { + "startip": "192.168.56.100", + "endip": "192.168.56.199", + "netmask": "255.255.255.0", + "gateway": "192.168.56.1" + } + ], + "netmask": "255.255.255.0", + "clusters": [ + { + "clustername": "test000", + "hypervisor": "XenServer", + "hosts": [ + { + "username": "root", + "url": "http://192.168.56.10/", + "password": "password" + } + ], + "clustertype": "CloudManaged" + } + ], + "gateway": "192.168.56.1" + } + ], + "internaldns1": "192.168.56.1", + "secondaryStorages": [ + { + "url": "nfs://192.168.56.10:/opt/storage/secondary" + } + ] + } + ], + "logger": [ + { + "name": "TestClient", + "file": "/tmp/testclient.log" + }, + { + "name": "TestCase", + "file": "/tmp/testcase.log" + } + ], + "mgtSvr": [ + { + "mgtSvrIp": "192.168.56.10", + "port": 8096 + } + ], + "dbSvr": + { + "dbSvr": "127.0.0.1", + "port": 3306, + "user": "cloud", + "passwd": "cloud", + "db": "cloud" + } + "globalConfig": [ + { + "name": "host", + "value": "192.168.56.10" + } + ] +} From 179db40e3adfefbc4f5b77e260c6a8c7fe46b472 Mon Sep 17 00:00:00 2001 From: Rohit Yadav Date: Tue, 22 Jan 2013 14:26:02 -0800 Subject: [PATCH 52/80] ApiDiscovery: Fix response and service impl to make them test-able --- .../api/response/ApiDiscoveryResponse.java | 16 ++++++++++++++++ .../discovery/ApiDiscoveryServiceImpl.java | 12 +++++------- 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/plugins/api/discovery/src/org/apache/cloudstack/api/response/ApiDiscoveryResponse.java b/plugins/api/discovery/src/org/apache/cloudstack/api/response/ApiDiscoveryResponse.java index de6a9f93965..77484f0f7e7 100644 --- a/plugins/api/discovery/src/org/apache/cloudstack/api/response/ApiDiscoveryResponse.java +++ b/plugins/api/discovery/src/org/apache/cloudstack/api/response/ApiDiscoveryResponse.java @@ -57,18 +57,34 @@ public class ApiDiscoveryResponse extends BaseResponse { this.name = name; } + public String getName() { + return name; + } + public void setDescription(String description) { this.description = description; } + public String getDescription() { + return description; + } + public void setSince(String since) { this.since = since; } + public String getSince() { + return since; + } + public void setAsync(Boolean isAsync) { this.isAsync = isAsync; } + public boolean getAsync() { + return isAsync; + } + public String getRelated() { return related; } diff --git a/plugins/api/discovery/src/org/apache/cloudstack/discovery/ApiDiscoveryServiceImpl.java b/plugins/api/discovery/src/org/apache/cloudstack/discovery/ApiDiscoveryServiceImpl.java index f06e2005552..5ac2281b84e 100644 --- a/plugins/api/discovery/src/org/apache/cloudstack/discovery/ApiDiscoveryServiceImpl.java +++ b/plugins/api/discovery/src/org/apache/cloudstack/discovery/ApiDiscoveryServiceImpl.java @@ -58,18 +58,16 @@ public class ApiDiscoveryServiceImpl implements ApiDiscoveryService { if (s_apiNameDiscoveryResponseMap == null) { long startTime = System.nanoTime(); s_apiNameDiscoveryResponseMap = new HashMap(); - cacheResponseMap(); + //TODO: Fix and use PluggableService to get the classes + Set> cmdClasses = ReflectUtil.getClassesWithAnnotation(APICommand.class, + new String[]{"org.apache.cloudstack.api", "com.cloud.api"}); + cacheResponseMap(cmdClasses); long endTime = System.nanoTime(); s_logger.info("Api Discovery Service: Annotation, docstrings, api relation graph processed in " + (endTime - startTime) / 1000000.0 + " ms"); } } - private void cacheResponseMap() { - Set> cmdClasses = ReflectUtil.getClassesWithAnnotation(APICommand.class, - new String[]{"org.apache.cloudstack.api", "com.cloud.api"}); - - //TODO: Fix and use PluggableService to get the classes - + protected void cacheResponseMap(Set> cmdClasses) { Map> responseApiNameListMap = new HashMap>(); for (Class cmdClass : cmdClasses) { From 26d8113f997b5e665d6a71d3d084875f8efbc128 Mon Sep 17 00:00:00 2001 From: Rohit Yadav Date: Tue, 22 Jan 2013 14:26:40 -0800 Subject: [PATCH 53/80] plugins: Indentation fix for pom.xml, add build/test rules for api discovery Signed-off-by: Rohit Yadav --- plugins/api/discovery/pom.xml | 64 +++++++++++++++++++++++------------ 1 file changed, 43 insertions(+), 21 deletions(-) diff --git a/plugins/api/discovery/pom.xml b/plugins/api/discovery/pom.xml index a61b275addc..1cfc5c2eaf2 100644 --- a/plugins/api/discovery/pom.xml +++ b/plugins/api/discovery/pom.xml @@ -20,25 +20,47 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - 4.0.0 - cloud-plugin-api-discovery - Apache CloudStack Plugin - API Discovery - - org.apache.cloudstack - cloudstack-plugins - 4.1.0-SNAPSHOT - ../../pom.xml - - - - org.apache.cloudstack - cloud-api - ${project.version} - - - org.apache.cloudstack - cloud-utils - ${project.version} - - + 4.0.0 + cloud-plugin-api-discovery + Apache CloudStack Plugin - API Discovery + + org.apache.cloudstack + cloudstack-plugins + 4.1.0-SNAPSHOT + ../../pom.xml + + + + org.apache.cloudstack + cloud-api + ${project.version} + + + org.apache.cloudstack + cloud-utils + ${project.version} + + + + install + src + test + + + test/resources + + + + + org.apache.maven.plugins + maven-surefire-plugin + + -Xmx1024m + + org/apache/cloudstack/discovery/integration/* + + + + + From 6482e270818b11cc0f2c8c1665c5e75d683b399a Mon Sep 17 00:00:00 2001 From: Rohit Yadav Date: Tue, 22 Jan 2013 14:27:48 -0800 Subject: [PATCH 54/80] ApiDiscovery: Add mockito, unit test for ApiDiscovery service impl Signed-off-by: Rohit Yadav --- .../discovery/ApiDiscoveryTest.java | 87 +++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 plugins/api/discovery/test/org/apache/cloudstack/discovery/ApiDiscoveryTest.java diff --git a/plugins/api/discovery/test/org/apache/cloudstack/discovery/ApiDiscoveryTest.java b/plugins/api/discovery/test/org/apache/cloudstack/discovery/ApiDiscoveryTest.java new file mode 100644 index 00000000000..a0e2a139164 --- /dev/null +++ b/plugins/api/discovery/test/org/apache/cloudstack/discovery/ApiDiscoveryTest.java @@ -0,0 +1,87 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.discovery; + +import com.cloud.user.User; +import com.cloud.user.UserVO; +import com.cloud.utils.component.Adapters; + +import java.util.*; +import javax.naming.ConfigurationException; + +import org.apache.cloudstack.acl.APIChecker; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.command.user.discovery.ListApisCmd; +import org.apache.cloudstack.api.response.ApiDiscoveryResponse; +import org.apache.cloudstack.api.response.ListResponse; + +import org.junit.BeforeClass; +import org.junit.Test; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; + +public class ApiDiscoveryTest { + + private static ApiDiscoveryServiceImpl _discoveryService = new ApiDiscoveryServiceImpl(); + private static APIChecker _apiChecker = mock(APIChecker.class); + + private static Class testCmdClass = ListApisCmd.class; + private static User testUser; + private static String testApiName; + private static String testApiDescription; + private static String testApiSince; + private static boolean testApiAsync; + + @BeforeClass + public static void setUp() throws ConfigurationException { + testApiName = testCmdClass.getAnnotation(APICommand.class).name(); + testApiDescription = testCmdClass.getAnnotation(APICommand.class).description(); + testApiSince = testCmdClass.getAnnotation(APICommand.class).since(); + testApiAsync = false; + testUser = new UserVO(); + + Set> cmdClasses = new HashSet>(); + cmdClasses.add(ListApisCmd.class); + _discoveryService.cacheResponseMap(cmdClasses); + _discoveryService.s_apiAccessCheckers = (Adapters) mock(Adapters.class); + + when(_apiChecker.checkAccess(any(User.class), anyString())).thenReturn(true); + when(_discoveryService.s_apiAccessCheckers.iterator()).thenReturn(Arrays.asList(_apiChecker).iterator()); + } + + @Test + public void verifyListSingleApi() throws Exception { + ListResponse responses = (ListResponse) _discoveryService.listApis(testUser, testApiName); + ApiDiscoveryResponse response = responses.getResponses().get(0); + assertTrue("No. of response items should be one", responses.getCount() == 1); + assertEquals("Error in api name", testApiName, response.getName()); + assertEquals("Error in api description", testApiDescription, response.getDescription()); + assertEquals("Error in api since", testApiSince, response.getSince()); + assertEquals("Error in api isAsync", testApiAsync, response.getAsync()); + } + + @Test + public void verifyListApis() throws Exception { + ListResponse responses = (ListResponse) _discoveryService.listApis(testUser, null); + assertTrue("No. of response items > 1", responses.getCount() > 1); + for (ApiDiscoveryResponse response: responses.getResponses()) { + assertFalse("API name is empty", response.getName().isEmpty()); + assertFalse("API description is empty", response.getDescription().isEmpty()); + } + } +} From a736f6b44fc25dcbf5373913a332e9b50ec928a6 Mon Sep 17 00:00:00 2001 From: Rohit Yadav Date: Tue, 22 Jan 2013 16:19:45 -0800 Subject: [PATCH 55/80] tools: Fix devcloud artifact name, avoid confusion Signed-off-by: Rohit Yadav --- tools/devcloud-kvm/pom.xml | 2 +- tools/devcloud/pom.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/tools/devcloud-kvm/pom.xml b/tools/devcloud-kvm/pom.xml index c9af192bee3..0f8168aa873 100644 --- a/tools/devcloud-kvm/pom.xml +++ b/tools/devcloud-kvm/pom.xml @@ -12,7 +12,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 cloud-devcloud-kvm - Apache CloudStack Developer Tools + Apache CloudStack DevCloud-KVM pom org.apache.cloudstack diff --git a/tools/devcloud/pom.xml b/tools/devcloud/pom.xml index 5c532c90a1b..fc6456a9e3d 100644 --- a/tools/devcloud/pom.xml +++ b/tools/devcloud/pom.xml @@ -12,7 +12,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 cloud-devcloud - Apache CloudStack Developer Tools + Apache CloudStack DevCloud pom org.apache.cloudstack From afb27700120fed84cd5fd8cb81c5adf503ebe888 Mon Sep 17 00:00:00 2001 From: Rohit Yadav Date: Tue, 22 Jan 2013 16:30:35 -0800 Subject: [PATCH 56/80] maven: create dependency, deploydb on developer first and then on devcloud Signed-off-by: Rohit Yadav --- tools/devcloud-kvm/pom.xml | 8 ++++++++ tools/devcloud/pom.xml | 8 ++++++++ 2 files changed, 16 insertions(+) diff --git a/tools/devcloud-kvm/pom.xml b/tools/devcloud-kvm/pom.xml index 0f8168aa873..f29e8375219 100644 --- a/tools/devcloud-kvm/pom.xml +++ b/tools/devcloud-kvm/pom.xml @@ -27,6 +27,14 @@ 5.1.21 runtime + + org.apache.cloudstack + cloud-developer + ${project.version} + pom + true + runtime + diff --git a/tools/devcloud/pom.xml b/tools/devcloud/pom.xml index fc6456a9e3d..8345e6468af 100644 --- a/tools/devcloud/pom.xml +++ b/tools/devcloud/pom.xml @@ -27,6 +27,14 @@ 5.1.21 runtime + + org.apache.cloudstack + cloud-developer + ${project.version} + pom + true + runtime + From 26be5ce2dfd00dd8a4ea3272ad7da2be6d060c5c Mon Sep 17 00:00:00 2001 From: Min Chen Date: Tue, 22 Jan 2013 16:39:17 -0800 Subject: [PATCH 57/80] CLOUDSTACK-355: create DB view for ZoneResponse to fix count for listZonesByCmd. --- .../com/cloud/server/ManagementService.java | 10 - .../api/command/user/zone/ListZonesByCmd.java | 11 +- .../cloudstack/api/response/ZoneResponse.java | 6 +- .../apache/cloudstack/query/QueryService.java | 4 + server/src/com/cloud/api/ApiDBUtils.java | 14 + .../src/com/cloud/api/ApiResponseHelper.java | 104 +++---- server/src/com/cloud/api/ApiServer.java | 2 + .../com/cloud/api/query/QueryManagerImpl.java | 138 +++++++++ .../cloud/api/query/ViewResponseHelper.java | 10 + .../api/query/dao/DataCenterJoinDao.java | 30 ++ .../api/query/dao/DataCenterJoinDaoImpl.java | 109 +++++++ .../cloud/api/query/vo/DataCenterJoinVO.java | 284 ++++++++++++++++++ .../DefaultComponentLibrary.java | 2 + .../cloud/server/ManagementServerImpl.java | 112 ------- setup/db/create-schema-view.sql | 29 ++ setup/db/db/schema-40to410.sql | 29 ++ 16 files changed, 691 insertions(+), 203 deletions(-) create mode 100644 server/src/com/cloud/api/query/dao/DataCenterJoinDao.java create mode 100644 server/src/com/cloud/api/query/dao/DataCenterJoinDaoImpl.java create mode 100644 server/src/com/cloud/api/query/vo/DataCenterJoinVO.java diff --git a/api/src/com/cloud/server/ManagementService.java b/api/src/com/cloud/server/ManagementService.java index 3bc7f934c04..32c2b053047 100755 --- a/api/src/com/cloud/server/ManagementService.java +++ b/api/src/com/cloud/server/ManagementService.java @@ -93,16 +93,6 @@ import com.cloud.vm.VirtualMachine.Type; public interface ManagementService { static final String Name = "management-server"; - /** - * Retrieves the list of data centers with search criteria. Currently the only search criteria is "available" zones - * for the - * account that invokes the API. By specifying available=true all zones which the account can access. By specifying - * available=false the zones where the account has virtual machine instances will be returned. - * - * @return a list of DataCenters - */ - List listDataCenters(ListZonesByCmd cmd); - /** * returns the a map of the names/values in the configuraton table * diff --git a/api/src/org/apache/cloudstack/api/command/user/zone/ListZonesByCmd.java b/api/src/org/apache/cloudstack/api/command/user/zone/ListZonesByCmd.java index 5f5f9e7bda0..ccacf060b19 100644 --- a/api/src/org/apache/cloudstack/api/command/user/zone/ListZonesByCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/zone/ListZonesByCmd.java @@ -27,6 +27,7 @@ import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.BaseListCmd; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.ServiceOfferingResponse; import org.apache.cloudstack.api.response.ZoneResponse; import com.cloud.dc.DataCenter; @@ -86,16 +87,8 @@ public class ListZonesByCmd extends BaseListCmd { @Override public void execute(){ - List dataCenters = _mgr.listDataCenters(this); - ListResponse response = new ListResponse(); - List zoneResponses = new ArrayList(); - for (DataCenter dataCenter : dataCenters) { - ZoneResponse zoneResponse = _responseGenerator.createZoneResponse(dataCenter, showCapacities); - zoneResponse.setObjectName("zone"); - zoneResponses.add(zoneResponse); - } - response.setResponses(zoneResponses); + ListResponse response = _queryService.listDataCenters(this); response.setResponseName(getCommandName()); this.setResponseObject(response); } diff --git a/api/src/org/apache/cloudstack/api/response/ZoneResponse.java b/api/src/org/apache/cloudstack/api/response/ZoneResponse.java index 72e0bb2844d..ca1cb57629c 100644 --- a/api/src/org/apache/cloudstack/api/response/ZoneResponse.java +++ b/api/src/org/apache/cloudstack/api/response/ZoneResponse.java @@ -65,8 +65,8 @@ public class ZoneResponse extends BaseResponse { @SerializedName(ApiConstants.DOMAIN) @Param(description="Network domain name for the networks in the zone") private String domain; - @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the ID of the containing domain, null for public zones") - private Long domainId; + @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the UUID of the containing domain, null for public zones") + private String domainId; @SerializedName("domainname") @Param(description="the name of the containing domain, null for public zones") private String domainName; @@ -140,7 +140,7 @@ public class ZoneResponse extends BaseResponse { this.domain = domain; } - public void setDomainId(Long domainId) { + public void setDomainId(String domainId) { this.domainId = domainId; } diff --git a/api/src/org/apache/cloudstack/query/QueryService.java b/api/src/org/apache/cloudstack/query/QueryService.java index add9d23943c..f3f6d3d5645 100644 --- a/api/src/org/apache/cloudstack/query/QueryService.java +++ b/api/src/org/apache/cloudstack/query/QueryService.java @@ -35,6 +35,7 @@ import org.apache.cloudstack.api.command.user.tag.ListTagsCmd; import org.apache.cloudstack.api.command.user.vm.ListVMsCmd; import org.apache.cloudstack.api.command.user.vmgroup.ListVMGroupsCmd; import org.apache.cloudstack.api.command.user.volume.ListVolumesCmd; +import org.apache.cloudstack.api.command.user.zone.ListZonesByCmd; import org.apache.cloudstack.api.response.AccountResponse; import org.apache.cloudstack.api.response.AsyncJobResponse; import org.apache.cloudstack.api.response.DiskOfferingResponse; @@ -53,6 +54,7 @@ import org.apache.cloudstack.api.response.StoragePoolResponse; import org.apache.cloudstack.api.response.UserResponse; import org.apache.cloudstack.api.response.UserVmResponse; import org.apache.cloudstack.api.response.VolumeResponse; +import org.apache.cloudstack.api.response.ZoneResponse; @@ -100,4 +102,6 @@ public interface QueryService { public ListResponse searchForDiskOfferings(ListDiskOfferingsCmd cmd); public ListResponse searchForServiceOfferings(ListServiceOfferingsCmd cmd); + + public ListResponse listDataCenters(ListZonesByCmd cmd); } diff --git a/server/src/com/cloud/api/ApiDBUtils.java b/server/src/com/cloud/api/ApiDBUtils.java index 9b88664fe2b..0b08b26cc32 100755 --- a/server/src/com/cloud/api/ApiDBUtils.java +++ b/server/src/com/cloud/api/ApiDBUtils.java @@ -41,9 +41,11 @@ import org.apache.cloudstack.api.response.StoragePoolResponse; import org.apache.cloudstack.api.response.UserResponse; import org.apache.cloudstack.api.response.UserVmResponse; import org.apache.cloudstack.api.response.VolumeResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import com.cloud.api.query.dao.AccountJoinDao; import com.cloud.api.query.dao.AsyncJobJoinDao; +import com.cloud.api.query.dao.DataCenterJoinDao; import com.cloud.api.query.dao.DiskOfferingJoinDao; import com.cloud.api.query.dao.DomainRouterJoinDao; import com.cloud.api.query.dao.HostJoinDao; @@ -60,6 +62,7 @@ import com.cloud.api.query.dao.UserVmJoinDao; import com.cloud.api.query.dao.VolumeJoinDao; import com.cloud.api.query.vo.AccountJoinVO; import com.cloud.api.query.vo.AsyncJobJoinVO; +import com.cloud.api.query.vo.DataCenterJoinVO; import com.cloud.api.query.vo.DiskOfferingJoinVO; import com.cloud.api.query.vo.DomainRouterJoinVO; import com.cloud.api.query.vo.EventJoinVO; @@ -88,6 +91,7 @@ import com.cloud.configuration.Resource.ResourceType; import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.dc.AccountVlanMapVO; import com.cloud.dc.ClusterVO; +import com.cloud.dc.DataCenter; import com.cloud.dc.DataCenterVO; import com.cloud.dc.HostPodVO; import com.cloud.dc.Vlan; @@ -342,6 +346,7 @@ public class ApiDBUtils { private static AsyncJobJoinDao _jobJoinDao; private static DiskOfferingJoinDao _diskOfferingJoinDao; private static ServiceOfferingJoinDao _srvOfferingJoinDao; + private static DataCenterJoinDao _dcJoinDao; private static PhysicalNetworkTrafficTypeDao _physicalNetworkTrafficTypeDao; private static PhysicalNetworkServiceProviderDao _physicalNetworkServiceProviderDao; @@ -448,6 +453,7 @@ public class ApiDBUtils { _asyncJobDao = locator.getDao(AsyncJobDao.class); _diskOfferingJoinDao = locator.getDao(DiskOfferingJoinDao.class); _srvOfferingJoinDao = locator.getDao(ServiceOfferingJoinDao.class); + _dcJoinDao = locator.getDao(DataCenterJoinDao.class); // Note: stats collector should already have been initialized by this time, otherwise a null instance is returned _statsCollector = StatsCollector.getInstance(); @@ -1426,4 +1432,12 @@ public class ApiDBUtils { public static ServiceOfferingJoinVO newServiceOfferingView(ServiceOffering offering){ return _srvOfferingJoinDao.newServiceOfferingView(offering); } + + public static ZoneResponse newDataCenterResponse(DataCenterJoinVO dc, Boolean showCapacities) { + return _dcJoinDao.newDataCenterResponse(dc, showCapacities); + } + + public static DataCenterJoinVO newDataCenterView(DataCenter dc){ + return _dcJoinDao.newDataCenterView(dc); + } } diff --git a/server/src/com/cloud/api/ApiResponseHelper.java b/server/src/com/cloud/api/ApiResponseHelper.java index 1965f333f35..1c8849a9e53 100755 --- a/server/src/com/cloud/api/ApiResponseHelper.java +++ b/server/src/com/cloud/api/ApiResponseHelper.java @@ -44,6 +44,7 @@ import com.cloud.api.query.ViewResponseHelper; import com.cloud.api.query.vo.AccountJoinVO; import com.cloud.api.query.vo.AsyncJobJoinVO; import com.cloud.api.query.vo.ControlledViewEntity; +import com.cloud.api.query.vo.DataCenterJoinVO; import com.cloud.api.query.vo.DiskOfferingJoinVO; import com.cloud.api.query.vo.DomainRouterJoinVO; import com.cloud.api.query.vo.EventJoinVO; @@ -717,77 +718,42 @@ public class ApiResponseHelper implements ResponseGenerator { @Override public ZoneResponse createZoneResponse(DataCenter dataCenter, Boolean showCapacities) { - Account account = UserContext.current().getCaller(); - ZoneResponse zoneResponse = new ZoneResponse(); - zoneResponse.setId(dataCenter.getUuid()); - zoneResponse.setName(dataCenter.getName()); - zoneResponse.setSecurityGroupsEnabled(ApiDBUtils.isSecurityGroupEnabledInZone(dataCenter.getId())); - zoneResponse.setLocalStorageEnabled(dataCenter.isLocalStorageEnabled()); - - if ((dataCenter.getDescription() != null) && !dataCenter.getDescription().equalsIgnoreCase("null")) { - zoneResponse.setDescription(dataCenter.getDescription()); - } - - if ((account == null) || (account.getType() == Account.ACCOUNT_TYPE_ADMIN)) { - zoneResponse.setDns1(dataCenter.getDns1()); - zoneResponse.setDns2(dataCenter.getDns2()); - zoneResponse.setInternalDns1(dataCenter.getInternalDns1()); - zoneResponse.setInternalDns2(dataCenter.getInternalDns2()); - // FIXME zoneResponse.setVlan(dataCenter.get.getVnet()); - zoneResponse.setGuestCidrAddress(dataCenter.getGuestNetworkCidr()); - } - - if (showCapacities != null && showCapacities) { - List capacities = ApiDBUtils.getCapacityByClusterPodZone(dataCenter.getId(), null, null); - Set capacityResponses = new HashSet(); - float cpuOverprovisioningFactor = ApiDBUtils.getCpuOverprovisioningFactor(); - - for (SummedCapacity capacity : capacities) { - CapacityResponse capacityResponse = new CapacityResponse(); - capacityResponse.setCapacityType(capacity.getCapacityType()); - capacityResponse.setCapacityUsed(capacity.getUsedCapacity()); - if (capacity.getCapacityType() == Capacity.CAPACITY_TYPE_CPU) { - capacityResponse.setCapacityTotal(new Long((long) (capacity.getTotalCapacity() * cpuOverprovisioningFactor))); - } else if (capacity.getCapacityType() == Capacity.CAPACITY_TYPE_STORAGE_ALLOCATED) { - List c = ApiDBUtils.findNonSharedStorageForClusterPodZone(dataCenter.getId(), null, null); - capacityResponse.setCapacityTotal(capacity.getTotalCapacity() - c.get(0).getTotalCapacity()); - capacityResponse.setCapacityUsed(capacity.getUsedCapacity() - c.get(0).getUsedCapacity()); - } else { - capacityResponse.setCapacityTotal(capacity.getTotalCapacity()); - } - if (capacityResponse.getCapacityTotal() != 0) { - capacityResponse.setPercentUsed(s_percentFormat.format((float) capacityResponse.getCapacityUsed() / (float) capacityResponse.getCapacityTotal() * 100f)); - } else { - capacityResponse.setPercentUsed(s_percentFormat.format(0L)); - } - capacityResponses.add(capacityResponse); - } - // Do it for stats as well. - capacityResponses.addAll(getStatsCapacityresponse(null, null, null, dataCenter.getId())); - - zoneResponse.setCapacitites(new ArrayList(capacityResponses)); - } - - // set network domain info - zoneResponse.setDomain(dataCenter.getDomain()); - - // set domain info - Long domainId = dataCenter.getDomainId(); - if (domainId != null) { - Domain domain = ApiDBUtils.findDomainById(domainId); - zoneResponse.setDomainId(domain.getId()); - zoneResponse.setDomainName(domain.getName()); - } - - zoneResponse.setType(dataCenter.getNetworkType().toString()); - zoneResponse.setAllocationState(dataCenter.getAllocationState().toString()); - zoneResponse.setZoneToken(dataCenter.getZoneToken()); - zoneResponse.setDhcpProvider(dataCenter.getDhcpProvider()); - zoneResponse.setObjectName("zone"); - return zoneResponse; + DataCenterJoinVO vOffering = ApiDBUtils.newDataCenterView(dataCenter); + return ApiDBUtils.newDataCenterResponse(vOffering, showCapacities); } - private List getStatsCapacityresponse(Long poolId, Long clusterId, Long podId, Long zoneId) { + public static List getDataCenterCapacityResponse(Long zoneId){ + List capacities = ApiDBUtils.getCapacityByClusterPodZone(zoneId, null, null); + Set capacityResponses = new HashSet(); + float cpuOverprovisioningFactor = ApiDBUtils.getCpuOverprovisioningFactor(); + + for (SummedCapacity capacity : capacities) { + CapacityResponse capacityResponse = new CapacityResponse(); + capacityResponse.setCapacityType(capacity.getCapacityType()); + capacityResponse.setCapacityUsed(capacity.getUsedCapacity()); + if (capacity.getCapacityType() == Capacity.CAPACITY_TYPE_CPU) { + capacityResponse.setCapacityTotal(new Long((long) (capacity.getTotalCapacity() * cpuOverprovisioningFactor))); + } else if (capacity.getCapacityType() == Capacity.CAPACITY_TYPE_STORAGE_ALLOCATED) { + List c = ApiDBUtils.findNonSharedStorageForClusterPodZone(zoneId, null, null); + capacityResponse.setCapacityTotal(capacity.getTotalCapacity() - c.get(0).getTotalCapacity()); + capacityResponse.setCapacityUsed(capacity.getUsedCapacity() - c.get(0).getUsedCapacity()); + } else { + capacityResponse.setCapacityTotal(capacity.getTotalCapacity()); + } + if (capacityResponse.getCapacityTotal() != 0) { + capacityResponse.setPercentUsed(s_percentFormat.format((float) capacityResponse.getCapacityUsed() / (float) capacityResponse.getCapacityTotal() * 100f)); + } else { + capacityResponse.setPercentUsed(s_percentFormat.format(0L)); + } + capacityResponses.add(capacityResponse); + } + // Do it for stats as well. + capacityResponses.addAll(getStatsCapacityresponse(null, null, null, zoneId)); + + return new ArrayList(capacityResponses); + } + + private static List getStatsCapacityresponse(Long poolId, Long clusterId, Long podId, Long zoneId) { List capacities = new ArrayList(); capacities.add(ApiDBUtils.getStoragePoolUsedStats(poolId, clusterId, podId, zoneId)); if (clusterId == null && podId == null) { diff --git a/server/src/com/cloud/api/ApiServer.java b/server/src/com/cloud/api/ApiServer.java index ad2a12f0068..ed2720082c4 100755 --- a/server/src/com/cloud/api/ApiServer.java +++ b/server/src/com/cloud/api/ApiServer.java @@ -61,6 +61,7 @@ import org.apache.cloudstack.api.command.user.event.ListEventsCmd; import org.apache.cloudstack.api.command.user.vm.ListVMsCmd; import org.apache.cloudstack.api.command.user.vmgroup.ListVMGroupsCmd; import org.apache.cloudstack.api.command.user.volume.ListVolumesCmd; +import org.apache.cloudstack.api.command.user.zone.ListZonesByCmd; import org.apache.commons.codec.binary.Base64; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.ConnectionClosedException; @@ -518,6 +519,7 @@ public class ApiServer implements HttpRequestHandler { && !(cmdObj instanceof ListStoragePoolsCmd) && !(cmdObj instanceof ListDiskOfferingsCmd) && !(cmdObj instanceof ListServiceOfferingsCmd) + && !(cmdObj instanceof ListZonesByCmd) ) { buildAsyncListResponse((BaseListCmd) cmdObj, caller); } diff --git a/server/src/com/cloud/api/query/QueryManagerImpl.java b/server/src/com/cloud/api/query/QueryManagerImpl.java index ee472961871..a943776a6c2 100644 --- a/server/src/com/cloud/api/query/QueryManagerImpl.java +++ b/server/src/com/cloud/api/query/QueryManagerImpl.java @@ -18,8 +18,11 @@ package com.cloud.api.query; import java.util.ArrayList; import java.util.Date; +import java.util.HashSet; +import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.Set; import javax.ejb.Local; import javax.naming.ConfigurationException; @@ -41,6 +44,7 @@ import org.apache.cloudstack.api.command.user.tag.ListTagsCmd; import org.apache.cloudstack.api.command.user.vm.ListVMsCmd; import org.apache.cloudstack.api.command.user.vmgroup.ListVMGroupsCmd; import org.apache.cloudstack.api.command.user.volume.ListVolumesCmd; +import org.apache.cloudstack.api.command.user.zone.ListZonesByCmd; import org.apache.cloudstack.api.response.AccountResponse; import org.apache.cloudstack.api.response.AsyncJobResponse; import org.apache.cloudstack.api.response.DiskOfferingResponse; @@ -59,11 +63,13 @@ import org.apache.cloudstack.api.response.StoragePoolResponse; import org.apache.cloudstack.api.response.UserResponse; import org.apache.cloudstack.api.response.UserVmResponse; import org.apache.cloudstack.api.response.VolumeResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.cloudstack.query.QueryService; import org.apache.log4j.Logger; import com.cloud.api.query.dao.AccountJoinDao; import com.cloud.api.query.dao.AsyncJobJoinDao; +import com.cloud.api.query.dao.DataCenterJoinDao; import com.cloud.api.query.dao.DiskOfferingJoinDao; import com.cloud.api.query.dao.DomainRouterJoinDao; import com.cloud.api.query.dao.HostJoinDao; @@ -80,6 +86,7 @@ import com.cloud.api.query.dao.UserVmJoinDao; import com.cloud.api.query.dao.VolumeJoinDao; import com.cloud.api.query.vo.AccountJoinVO; import com.cloud.api.query.vo.AsyncJobJoinVO; +import com.cloud.api.query.vo.DataCenterJoinVO; import com.cloud.api.query.vo.DiskOfferingJoinVO; import com.cloud.api.query.vo.DomainRouterJoinVO; import com.cloud.api.query.vo.EventJoinVO; @@ -96,6 +103,7 @@ import com.cloud.api.query.vo.UserAccountJoinVO; import com.cloud.api.query.vo.UserVmJoinVO; import com.cloud.api.query.vo.VolumeJoinVO; import com.cloud.configuration.dao.ConfigurationDao; +import com.cloud.dc.DataCenterVO; import com.cloud.domain.Domain; import com.cloud.domain.DomainVO; import com.cloud.domain.dao.DomainDao; @@ -107,6 +115,7 @@ import com.cloud.ha.HighAvailabilityManager; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.network.security.SecurityGroupVMMapVO; import com.cloud.network.security.dao.SecurityGroupVMMapDao; +import com.cloud.org.Grouping; import com.cloud.projects.ProjectInvitation; import com.cloud.projects.Project.ListProjectResourcesCriteria; import com.cloud.projects.Project; @@ -135,8 +144,10 @@ import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.SearchCriteria.Func; import com.cloud.utils.db.SearchCriteria.Op; +import com.cloud.vm.DomainRouterVO; import com.cloud.vm.UserVmVO; import com.cloud.vm.VirtualMachine; +import com.cloud.vm.dao.DomainRouterDao; import com.cloud.vm.dao.UserVmDao; /** @@ -233,6 +244,12 @@ public class QueryManagerImpl implements QueryService, Manager { @Inject private ServiceOfferingDao _srvOfferingDao; + @Inject + private DataCenterJoinDao _dcJoinDao; + + @Inject + private DomainRouterDao _routerDao; + @Inject private HighAvailabilityManager _haMgr; @@ -2187,6 +2204,125 @@ public class QueryManagerImpl implements QueryService, Manager { + @Override + public ListResponse listDataCenters(ListZonesByCmd cmd) { + Pair, Integer> result = listDataCentersInternal(cmd); + ListResponse response = new ListResponse(); + List dcResponses = ViewResponseHelper.createDataCenterResponse(cmd.getShowCapacities(), result.first().toArray(new DataCenterJoinVO[result.first().size()])); + response.setResponses(dcResponses, result.second()); + return response; + } + + + private Pair, Integer> listDataCentersInternal(ListZonesByCmd cmd) { + Account account = UserContext.current().getCaller(); + Long domainId = cmd.getDomainId(); + Long id = cmd.getId(); + String keyword = cmd.getKeyword(); + + Filter searchFilter = new Filter(DataCenterJoinVO.class, null, false, cmd.getStartIndex(), cmd.getPageSizeVal()); + SearchCriteria sc = _dcJoinDao.createSearchCriteria(); + + if (id != null) { + sc.addAnd("id", SearchCriteria.Op.EQ, id); + } else { + if (keyword != null) { + SearchCriteria ssc = _dcJoinDao.createSearchCriteria(); + ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + ssc.addOr("description", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + sc.addAnd("name", SearchCriteria.Op.SC, ssc); + } + + if (domainId != null) { + // for domainId != null + // right now, we made the decision to only list zones associated + // with this domain, private zone + sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId); + } else if (account.getType() == Account.ACCOUNT_TYPE_NORMAL) { + // it was decided to return all zones for the user's domain, and + // everything above till root + // list all zones belonging to this domain, and all of its + // parents + // check the parent, if not null, add zones for that parent to + // list + + + // find all domain Id up to root domain for this account + List domainIds = new ArrayList(); + DomainVO domainRecord = _domainDao.findById(account.getDomainId()); + if ( domainRecord == null ){ + s_logger.error("Could not find the domainId for account:" + account.getAccountName()); + throw new CloudAuthenticationException("Could not find the domainId for account:" + account.getAccountName()); + } + domainIds.add(domainRecord.getId()); + while (domainRecord.getParent() != null ){ + domainRecord = _domainDao.findById(domainRecord.getParent()); + domainIds.add(domainRecord.getId()); + } + // domainId == null (public zones) or domainId IN [all domain id up to root domain] + SearchCriteria sdc = _dcJoinDao.createSearchCriteria(); + sdc.addOr("domainIdIn", SearchCriteria.Op.IN, domainIds); + sdc.addOr("domainId", SearchCriteria.Op.NULL); + sc.addAnd("domain", SearchCriteria.Op.SC, sdc); + + // remove disabled zones + sc.addAnd("allocationState", SearchCriteria.Op.NEQ, Grouping.AllocationState.Disabled); + + } else if (account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN || account.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) { + // it was decided to return all zones for the domain admin, and + // everything above till root, as well as zones till the domain leaf + List domainIds = new ArrayList(); + DomainVO domainRecord = _domainDao.findById(account.getDomainId()); + if ( domainRecord == null ){ + s_logger.error("Could not find the domainId for account:" + account.getAccountName()); + throw new CloudAuthenticationException("Could not find the domainId for account:" + account.getAccountName()); + } + domainIds.add(domainRecord.getId()); + // find all domain Ids till leaf + List allChildDomains = _domainDao.findAllChildren(domainRecord.getPath(), domainRecord.getId()); + for (DomainVO domain : allChildDomains) { + domainIds.add(domain.getId()); + } + // then find all domain Id up to root domain for this account + while (domainRecord.getParent() != null ){ + domainRecord = _domainDao.findById(domainRecord.getParent()); + domainIds.add(domainRecord.getId()); + } + + // domainId == null (public zones) or domainId IN [all domain id up to root domain] + SearchCriteria sdc = _dcJoinDao.createSearchCriteria(); + sdc.addOr("domainIdIn", SearchCriteria.Op.IN, domainIds); + sdc.addOr("domainId", SearchCriteria.Op.NULL); + sc.addAnd("domain", SearchCriteria.Op.SC, sdc); + + // remove disabled zones + sc.addAnd("allocationState", SearchCriteria.Op.NEQ, Grouping.AllocationState.Disabled); + } + + // handle available=FALSE option, only return zones with at least one VM running there + Boolean available = cmd.isAvailable(); + if (account != null) { + if ((available != null) && Boolean.FALSE.equals(available)) { + Set dcIds = new HashSet(); //data centers with at least one VM running + List routers = _routerDao.listBy(account.getId()); + for (DomainRouterVO router : routers){ + dcIds.add(router.getDataCenterIdToDeployIn()); + } + if ( dcIds.size() == 0) { + return new Pair, Integer>(new ArrayList(), 0); + } + else{ + sc.addAnd("idIn", SearchCriteria.Op.IN, dcIds); + } + + } + } + } + + return _dcJoinDao.searchAndCount(sc, searchFilter); + } + + // This method is used for permissions check for both disk and service // offerings private boolean isPermissible(Long accountDomainId, Long offeringDomainId) { @@ -2214,4 +2350,6 @@ public class QueryManagerImpl implements QueryService, Manager { return false; } + + } diff --git a/server/src/com/cloud/api/query/ViewResponseHelper.java b/server/src/com/cloud/api/query/ViewResponseHelper.java index dfccdceb8d4..55d84bb5af4 100644 --- a/server/src/com/cloud/api/query/ViewResponseHelper.java +++ b/server/src/com/cloud/api/query/ViewResponseHelper.java @@ -40,11 +40,13 @@ import org.apache.cloudstack.api.response.StoragePoolResponse; import org.apache.cloudstack.api.response.UserResponse; import org.apache.cloudstack.api.response.UserVmResponse; import org.apache.cloudstack.api.response.VolumeResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.log4j.Logger; import com.cloud.api.ApiDBUtils; import com.cloud.api.query.vo.AccountJoinVO; import com.cloud.api.query.vo.AsyncJobJoinVO; +import com.cloud.api.query.vo.DataCenterJoinVO; import com.cloud.api.query.vo.DiskOfferingJoinVO; import com.cloud.api.query.vo.DomainRouterJoinVO; import com.cloud.api.query.vo.EventJoinVO; @@ -294,4 +296,12 @@ public class ViewResponseHelper { } return respList; } + + public static List createDataCenterResponse(Boolean showCapacities, DataCenterJoinVO... dcs) { + List respList = new ArrayList(); + for (DataCenterJoinVO vt : dcs){ + respList.add(ApiDBUtils.newDataCenterResponse(vt, showCapacities)); + } + return respList; + } } diff --git a/server/src/com/cloud/api/query/dao/DataCenterJoinDao.java b/server/src/com/cloud/api/query/dao/DataCenterJoinDao.java new file mode 100644 index 00000000000..340f86f247d --- /dev/null +++ b/server/src/com/cloud/api/query/dao/DataCenterJoinDao.java @@ -0,0 +1,30 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api.query.dao; + +import org.apache.cloudstack.api.response.ZoneResponse; + +import com.cloud.api.query.vo.DataCenterJoinVO; +import com.cloud.dc.DataCenter; +import com.cloud.utils.db.GenericDao; + +public interface DataCenterJoinDao extends GenericDao { + + ZoneResponse newDataCenterResponse(DataCenterJoinVO dof, Boolean showCapacities); + + DataCenterJoinVO newDataCenterView(DataCenter dof); +} diff --git a/server/src/com/cloud/api/query/dao/DataCenterJoinDaoImpl.java b/server/src/com/cloud/api/query/dao/DataCenterJoinDaoImpl.java new file mode 100644 index 00000000000..4ef182bb7ec --- /dev/null +++ b/server/src/com/cloud/api/query/dao/DataCenterJoinDaoImpl.java @@ -0,0 +1,109 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api.query.dao; + +import java.util.List; +import javax.ejb.Local; + +import org.apache.log4j.Logger; + +import com.cloud.api.ApiDBUtils; +import com.cloud.api.ApiResponseHelper; +import com.cloud.api.query.vo.DataCenterJoinVO; +import com.cloud.dc.DataCenter; +import org.apache.cloudstack.api.response.ZoneResponse; + +import com.cloud.user.Account; +import com.cloud.user.UserContext; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; + + +@Local(value={DataCenterJoinDao.class}) +public class DataCenterJoinDaoImpl extends GenericDaoBase implements DataCenterJoinDao { + public static final Logger s_logger = Logger.getLogger(DataCenterJoinDaoImpl.class); + + + private SearchBuilder dofIdSearch; + + protected DataCenterJoinDaoImpl() { + + dofIdSearch = createSearchBuilder(); + dofIdSearch.and("id", dofIdSearch.entity().getId(), SearchCriteria.Op.EQ); + dofIdSearch.done(); + + this._count = "select count(distinct id) from data_center_view WHERE "; + } + + + + @Override + public ZoneResponse newDataCenterResponse(DataCenterJoinVO dataCenter, Boolean showCapacities) { + + Account account = UserContext.current().getCaller(); + ZoneResponse zoneResponse = new ZoneResponse(); + zoneResponse.setId(dataCenter.getUuid()); + zoneResponse.setName(dataCenter.getName()); + zoneResponse.setSecurityGroupsEnabled(ApiDBUtils.isSecurityGroupEnabledInZone(dataCenter.getId())); + zoneResponse.setLocalStorageEnabled(dataCenter.isLocalStorageEnabled()); + + if ((dataCenter.getDescription() != null) && !dataCenter.getDescription().equalsIgnoreCase("null")) { + zoneResponse.setDescription(dataCenter.getDescription()); + } + + if ((account == null) || (account.getType() == Account.ACCOUNT_TYPE_ADMIN)) { + zoneResponse.setDns1(dataCenter.getDns1()); + zoneResponse.setDns2(dataCenter.getDns2()); + zoneResponse.setInternalDns1(dataCenter.getInternalDns1()); + zoneResponse.setInternalDns2(dataCenter.getInternalDns2()); + // FIXME zoneResponse.setVlan(dataCenter.get.getVnet()); + zoneResponse.setGuestCidrAddress(dataCenter.getGuestNetworkCidr()); + } + + if (showCapacities != null && showCapacities) { + zoneResponse.setCapacitites(ApiResponseHelper.getDataCenterCapacityResponse(dataCenter.getId())); + } + + // set network domain info + zoneResponse.setDomain(dataCenter.getDomain()); + + // set domain info + + zoneResponse.setDomainId(dataCenter.getDomainUuid()); + zoneResponse.setDomainName(dataCenter.getDomainName()); + + zoneResponse.setType(dataCenter.getNetworkType().toString()); + zoneResponse.setAllocationState(dataCenter.getAllocationState().toString()); + zoneResponse.setZoneToken(dataCenter.getZoneToken()); + zoneResponse.setDhcpProvider(dataCenter.getDhcpProvider()); + zoneResponse.setObjectName("zone"); + return zoneResponse; + } + + + @Override + public DataCenterJoinVO newDataCenterView(DataCenter dataCenter) { + SearchCriteria sc = dofIdSearch.create(); + sc.setParameters("id", dataCenter.getId()); + List dcs = searchIncludingRemoved(sc, null, null, false); + assert dcs != null && dcs.size() == 1 : "No data center found for data center id " + dataCenter.getId(); + return dcs.get(0); + } + + +} diff --git a/server/src/com/cloud/api/query/vo/DataCenterJoinVO.java b/server/src/com/cloud/api/query/vo/DataCenterJoinVO.java new file mode 100644 index 00000000000..67a3f2715f0 --- /dev/null +++ b/server/src/com/cloud/api/query/vo/DataCenterJoinVO.java @@ -0,0 +1,284 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api.query.vo; + +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.Id; +import javax.persistence.Table; + +import com.cloud.dc.DataCenter.NetworkType; +import com.cloud.org.Grouping.AllocationState; +import com.cloud.utils.db.GenericDao; + +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + +@Entity +@Table(name="data_center_view") +public class DataCenterJoinVO extends BaseViewVO implements InternalIdentity, Identity { + + @Id + @Column(name="id") + private long id; + + @Column(name="uuid") + private String uuid; + + @Column(name="name") + private String name; + + @Column(name="description") + private String description = null; + + @Column(name="dns1") + private String dns1 = null; + + @Column(name="dns2") + private String dns2 = null; + + @Column(name="internal_dns1") + private String internalDns1 = null; + + @Column(name="internal_dns2") + private String internalDns2 = null; + + @Column(name="guest_network_cidr") + private String guestNetworkCidr = null; + + @Column(name="domain") + private String domain; + + @Column(name="networktype") + @Enumerated(EnumType.STRING) + NetworkType networkType; + + @Column(name="dhcp_provider") + private String dhcpProvider; + + @Column(name="zone_token") + private String zoneToken; + + @Column(name="allocation_state") + @Enumerated(value=EnumType.STRING) + AllocationState allocationState; + + @Column(name="is_security_group_enabled") + boolean securityGroupEnabled; + + @Column(name="is_local_storage_enabled") + boolean localStorageEnabled; + + @Column(name=GenericDao.REMOVED_COLUMN) + private Date removed; + + @Column(name="domain_id") + private long domainId; + + @Column(name="domain_uuid") + private String domainUuid; + + @Column(name="domain_name") + private String domainName; + + @Column(name="domain_path") + private String domainPath; + + + public DataCenterJoinVO() { + } + + @Override + public long getId() { + return id; + } + + @Override + public void setId(long id) { + this.id = id; + } + + @Override + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getDns1() { + return dns1; + } + + public void setDns1(String dns1) { + this.dns1 = dns1; + } + + public String getDns2() { + return dns2; + } + + public void setDns2(String dns2) { + this.dns2 = dns2; + } + + public String getInternalDns1() { + return internalDns1; + } + + public void setInternalDns1(String internalDns1) { + this.internalDns1 = internalDns1; + } + + public String getInternalDns2() { + return internalDns2; + } + + public void setInternalDns2(String internalDns2) { + this.internalDns2 = internalDns2; + } + + public String getGuestNetworkCidr() { + return guestNetworkCidr; + } + + public void setGuestNetworkCidr(String guestNetworkCidr) { + this.guestNetworkCidr = guestNetworkCidr; + } + + public String getDomain() { + return domain; + } + + public void setDomain(String domain) { + this.domain = domain; + } + + public NetworkType getNetworkType() { + return networkType; + } + + public void setNetworkType(NetworkType networkType) { + this.networkType = networkType; + } + + public String getDhcpProvider() { + return dhcpProvider; + } + + public void setDhcpProvider(String dhcpProvider) { + this.dhcpProvider = dhcpProvider; + } + + public String getZoneToken() { + return zoneToken; + } + + public void setZoneToken(String zoneToken) { + this.zoneToken = zoneToken; + } + + public AllocationState getAllocationState() { + return allocationState; + } + + public void setAllocationState(AllocationState allocationState) { + this.allocationState = allocationState; + } + + public boolean isSecurityGroupEnabled() { + return securityGroupEnabled; + } + + public void setSecurityGroupEnabled(boolean securityGroupEnabled) { + this.securityGroupEnabled = securityGroupEnabled; + } + + + public boolean isLocalStorageEnabled() { + return localStorageEnabled; + } + + public void setLocalStorageEnabled(boolean localStorageEnabled) { + this.localStorageEnabled = localStorageEnabled; + } + + public Date getRemoved() { + return removed; + } + + public void setRemoved(Date removed) { + this.removed = removed; + } + + public long getDomainId() { + return domainId; + } + + public void setDomainId(long domainId) { + this.domainId = domainId; + } + + public String getDomainUuid() { + return domainUuid; + } + + public void setDomainUuid(String domainUuid) { + this.domainUuid = domainUuid; + } + + public String getDomainName() { + return domainName; + } + + public void setDomainName(String domainName) { + this.domainName = domainName; + } + + public String getDomainPath() { + return domainPath; + } + + public void setDomainPath(String domainPath) { + this.domainPath = domainPath; + } + + +} diff --git a/server/src/com/cloud/configuration/DefaultComponentLibrary.java b/server/src/com/cloud/configuration/DefaultComponentLibrary.java index 9652586124a..98da7adfa39 100755 --- a/server/src/com/cloud/configuration/DefaultComponentLibrary.java +++ b/server/src/com/cloud/configuration/DefaultComponentLibrary.java @@ -27,6 +27,7 @@ import com.cloud.alert.dao.AlertDaoImpl; import com.cloud.api.query.QueryManagerImpl; import com.cloud.api.query.dao.AccountJoinDaoImpl; import com.cloud.api.query.dao.AsyncJobJoinDaoImpl; +import com.cloud.api.query.dao.DataCenterJoinDaoImpl; import com.cloud.api.query.dao.DiskOfferingJoinDaoImpl; import com.cloud.api.query.dao.ServiceOfferingJoinDaoImpl; import com.cloud.api.query.dao.DomainRouterJoinDaoImpl; @@ -396,6 +397,7 @@ public class DefaultComponentLibrary extends ComponentLibraryBase implements Com addDao("StoragePoolJoinDao", StoragePoolJoinDaoImpl.class); addDao("DiskOfferingJoinDao", DiskOfferingJoinDaoImpl.class); addDao("ServiceOfferingJoinDao", ServiceOfferingJoinDaoImpl.class); + addDao("DataCenterJoinDao", DataCenterJoinDaoImpl.class); } @Override diff --git a/server/src/com/cloud/server/ManagementServerImpl.java b/server/src/com/cloud/server/ManagementServerImpl.java index 8182421bf02..a2a74c25a9a 100755 --- a/server/src/com/cloud/server/ManagementServerImpl.java +++ b/server/src/com/cloud/server/ManagementServerImpl.java @@ -416,119 +416,7 @@ public class ManagementServerImpl implements ManagementServer { return PasswordGenerator.generateRandomPassword(6); } - @Override - public List listDataCenters(ListZonesByCmd cmd) { - Account account = UserContext.current().getCaller(); - List dcs = null; - Long domainId = cmd.getDomainId(); - Long id = cmd.getId(); - boolean removeDisabledZones = false; - String keyword = cmd.getKeyword(); - if (domainId != null) { - // for domainId != null - // right now, we made the decision to only list zones associated - // with this domain - dcs = _dcDao.findZonesByDomainId(domainId, keyword); // private - // zones - } else if ((account == null || account.getType() == Account.ACCOUNT_TYPE_ADMIN)) { - if (keyword != null) { - dcs = _dcDao.findByKeyword(keyword); - } else { - dcs = _dcDao.listAll(); // all zones - } - } else if (account.getType() == Account.ACCOUNT_TYPE_NORMAL) { - // it was decided to return all zones for the user's domain, and - // everything above till root - // list all zones belonging to this domain, and all of its parents - // check the parent, if not null, add zones for that parent to list - dcs = new ArrayList(); - DomainVO domainRecord = _domainDao.findById(account.getDomainId()); - if (domainRecord != null) { - while (true) { - dcs.addAll(_dcDao.findZonesByDomainId(domainRecord.getId(), keyword)); - if (domainRecord.getParent() != null) { - domainRecord = _domainDao.findById(domainRecord.getParent()); - } else { - break; - } - } - } - // add all public zones too - dcs.addAll(_dcDao.listPublicZones(keyword)); - removeDisabledZones = true; - } else if (account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN || account.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) { - // it was decided to return all zones for the domain admin, and - // everything above till root - dcs = new ArrayList(); - DomainVO domainRecord = _domainDao.findById(account.getDomainId()); - // this covers path till root - if (domainRecord != null) { - DomainVO localRecord = domainRecord; - while (true) { - dcs.addAll(_dcDao.findZonesByDomainId(localRecord.getId(), keyword)); - if (localRecord.getParent() != null) { - localRecord = _domainDao.findById(localRecord.getParent()); - } else { - break; - } - } - } - // this covers till leaf - if (domainRecord != null) { - // find all children for this domain based on a like search by - // path - List allChildDomains = _domainDao.findAllChildren(domainRecord.getPath(), domainRecord.getId()); - List allChildDomainIds = new ArrayList(); - // create list of domainIds for search - for (DomainVO domain : allChildDomains) { - allChildDomainIds.add(domain.getId()); - } - // now make a search for zones based on this - if (allChildDomainIds.size() > 0) { - List childZones = _dcDao.findChildZones((allChildDomainIds.toArray()), keyword); - dcs.addAll(childZones); - } - } - // add all public zones too - dcs.addAll(_dcDao.listPublicZones(keyword)); - removeDisabledZones = true; - } - if (removeDisabledZones) { - dcs.removeAll(_dcDao.listDisabledZones()); - } - - Boolean available = cmd.isAvailable(); - if (account != null) { - if ((available != null) && Boolean.FALSE.equals(available)) { - List routers = _routerDao.listBy(account.getId()); - for (Iterator iter = dcs.iterator(); iter.hasNext();) { - DataCenterVO dc = iter.next(); - boolean found = false; - for (DomainRouterVO router : routers) { - if (dc.getId() == router.getDataCenterIdToDeployIn()) { - found = true; - break; - } - } - if (!found) { - iter.remove(); - } - } - } - } - - if (id != null) { - List singleZone = new ArrayList(); - for (DataCenterVO zone : dcs) { - if (zone.getId() == id) { - singleZone.add(zone); - } - } - return singleZone; - } - return dcs; - } @Override public HostVO getHostBy(long hostId) { diff --git a/setup/db/create-schema-view.sql b/setup/db/create-schema-view.sql index f5c0591c0aa..f68a6cadb71 100644 --- a/setup/db/create-schema-view.sql +++ b/setup/db/create-schema-view.sql @@ -1105,3 +1105,32 @@ CREATE VIEW `cloud`.`service_offering_view` AS `cloud`.`disk_offering` ON service_offering.id = disk_offering.id left join `cloud`.`domain` ON disk_offering.domain_id = domain.id; + +DROP VIEW IF EXISTS `cloud`.`data_center_view`; +CREATE VIEW `cloud`.`data_center_view` AS + select + data_center.id, + data_center.uuid, + data_center.name, + data_center.is_security_group_enabled, + data_center.is_local_storage_enabled, + data_center.description, + data_center.dns1, + data_center.dns2, + data_center.internal_dns1, + data_center.internal_dns2, + data_center.guest_network_cidr, + data_center.domain, + data_center.networktype, + data_center.allocation_state, + data_center.zone_token, + data_center.dhcp_provider, + data_center.removed, + domain.id domain_id, + domain.uuid domain_uuid, + domain.name domain_name, + domain.path domain_path + from + `cloud`.`data_center` + left join + `cloud`.`domain` ON data_center.domain_id = domain.id; \ No newline at end of file diff --git a/setup/db/db/schema-40to410.sql b/setup/db/db/schema-40to410.sql index d10239be31d..93949b8e4fa 100644 --- a/setup/db/db/schema-40to410.sql +++ b/setup/db/db/schema-40to410.sql @@ -1232,4 +1232,33 @@ CREATE VIEW `cloud`.`service_offering_view` AS left join `cloud`.`domain` ON disk_offering.domain_id = domain.id; +DROP VIEW IF EXISTS `cloud`.`data_center_view`; +CREATE VIEW `cloud`.`data_center_view` AS + select + data_center.id, + data_center.uuid, + data_center.name, + data_center.is_security_group_enabled, + data_center.is_local_storage_enabled, + data_center.description, + data_center.dns1, + data_center.dns2, + data_center.internal_dns1, + data_center.internal_dns2, + data_center.guest_network_cidr, + data_center.domain, + data_center.networktype, + data_center.allocation_state, + data_center.zone_token, + data_center.dhcp_provider, + data_center.removed, + domain.id domain_id, + domain.uuid domain_uuid, + domain.name domain_name, + domain.path domain_path + from + `cloud`.`data_center` + left join + `cloud`.`domain` ON data_center.domain_id = domain.id; + INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Advanced', 'DEFAULT', 'management-server', 'direct.agent.pool.size', '500', 'Default size for DirectAgentPool'); From c3f1a9d324ad01450df315242bdabe6edd0c7e60 Mon Sep 17 00:00:00 2001 From: Min Chen Date: Tue, 22 Jan 2013 17:14:44 -0800 Subject: [PATCH 58/80] CLOUDSTACK-355: fix count for listSwiftsCmd. --- api/src/com/cloud/resource/ResourceService.java | 5 +++-- .../api/command/admin/swift/ListSwiftsCmd.java | 10 +++++----- server/src/com/cloud/resource/ResourceManagerImpl.java | 5 +++-- server/src/com/cloud/storage/swift/SwiftManager.java | 3 ++- .../src/com/cloud/storage/swift/SwiftManagerImpl.java | 7 ++++--- .../com/cloud/resource/MockResourceManagerImpl.java | 2 +- 6 files changed, 18 insertions(+), 14 deletions(-) diff --git a/api/src/com/cloud/resource/ResourceService.java b/api/src/com/cloud/resource/ResourceService.java index b9db8e734d9..7348a5a6867 100755 --- a/api/src/com/cloud/resource/ResourceService.java +++ b/api/src/com/cloud/resource/ResourceService.java @@ -34,6 +34,7 @@ import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.org.Cluster; import com.cloud.storage.S3; import com.cloud.storage.Swift; +import com.cloud.utils.Pair; import com.cloud.utils.fsm.NoTransitionException; import org.apache.cloudstack.api.command.admin.host.ReconnectHostCmd; @@ -94,10 +95,10 @@ public interface ResourceService { Swift discoverSwift(AddSwiftCmd addSwiftCmd) throws DiscoveryException; S3 discoverS3(AddS3Cmd cmd) throws DiscoveryException; - + List getSupportedHypervisorTypes(long zoneId, boolean forVirtualRouter, Long podId); - List listSwifts(ListSwiftsCmd cmd); + Pair, Integer> listSwifts(ListSwiftsCmd cmd); List listS3s(ListS3sCmd cmd); diff --git a/api/src/org/apache/cloudstack/api/command/admin/swift/ListSwiftsCmd.java b/api/src/org/apache/cloudstack/api/command/admin/swift/ListSwiftsCmd.java index d7c151188e7..af266437932 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/swift/ListSwiftsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/swift/ListSwiftsCmd.java @@ -30,6 +30,7 @@ import org.apache.cloudstack.api.response.ListResponse; import org.apache.cloudstack.api.response.SwiftResponse; import com.cloud.storage.Swift; import com.cloud.user.Account; +import com.cloud.utils.Pair; @APICommand(name = "listSwifts", description = "List Swift.", responseObject = HostResponse.class, since="3.0.0") public class ListSwiftsCmd extends BaseListCmd { @@ -64,20 +65,19 @@ public class ListSwiftsCmd extends BaseListCmd { @Override public void execute(){ - List result = _resourceService.listSwifts(this); + Pair, Integer> result = _resourceService.listSwifts(this); ListResponse response = new ListResponse(); List swiftResponses = new ArrayList(); if (result != null) { - SwiftResponse swiftResponse = null; - for (Swift swift : result) { - swiftResponse = _responseGenerator.createSwiftResponse(swift); + for (Swift swift : result.first()) { + SwiftResponse swiftResponse = _responseGenerator.createSwiftResponse(swift); swiftResponse.setResponseName(getCommandName()); swiftResponse.setObjectName("swift"); swiftResponses.add(swiftResponse); } } - response.setResponses(swiftResponses); + response.setResponses(swiftResponses, result.second()); response.setResponseName(getCommandName()); this.setResponseObject(response); } diff --git a/server/src/com/cloud/resource/ResourceManagerImpl.java b/server/src/com/cloud/resource/ResourceManagerImpl.java index b6ee747bee9..f82424a10c2 100755 --- a/server/src/com/cloud/resource/ResourceManagerImpl.java +++ b/server/src/com/cloud/resource/ResourceManagerImpl.java @@ -560,8 +560,9 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma } @Override - public List listSwifts(ListSwiftsCmd cmd) { - return _swiftMgr.listSwifts(cmd); + public Pair, Integer> listSwifts(ListSwiftsCmd cmd) { + Pair, Integer> swifts = _swiftMgr.listSwifts(cmd); + return new Pair, Integer>(swifts.first(), swifts.second()); } @Override diff --git a/server/src/com/cloud/storage/swift/SwiftManager.java b/server/src/com/cloud/storage/swift/SwiftManager.java index 0dd6e1cf22a..2abdac7f807 100644 --- a/server/src/com/cloud/storage/swift/SwiftManager.java +++ b/server/src/com/cloud/storage/swift/SwiftManager.java @@ -27,6 +27,7 @@ import com.cloud.exception.DiscoveryException; import com.cloud.storage.Swift; import com.cloud.storage.SwiftVO; import com.cloud.storage.VMTemplateSwiftVO; +import com.cloud.utils.Pair; import com.cloud.utils.component.Manager; public interface SwiftManager extends Manager { @@ -50,7 +51,7 @@ public interface SwiftManager extends Manager { Long chooseZoneForTmpltExtract(Long tmpltId); - List listSwifts(ListSwiftsCmd cmd); + Pair, Integer> listSwifts(ListSwiftsCmd cmd); VMTemplateSwiftVO findByTmpltId(Long tmpltId); } diff --git a/server/src/com/cloud/storage/swift/SwiftManagerImpl.java b/server/src/com/cloud/storage/swift/SwiftManagerImpl.java index dab16ced985..d62dd63c068 100644 --- a/server/src/com/cloud/storage/swift/SwiftManagerImpl.java +++ b/server/src/com/cloud/storage/swift/SwiftManagerImpl.java @@ -50,6 +50,7 @@ import com.cloud.storage.dao.SwiftDao; import com.cloud.storage.dao.VMTemplateHostDao; import com.cloud.storage.dao.VMTemplateSwiftDao; import com.cloud.storage.dao.VMTemplateZoneDao; +import com.cloud.utils.Pair; import com.cloud.utils.component.Inject; import com.cloud.utils.db.Filter; import com.cloud.utils.db.SearchCriteria; @@ -242,7 +243,7 @@ public class SwiftManagerImpl implements SwiftManager { if (swift == null) { return null; } - + List tmpltHosts = _vmTmpltHostDao.listByOnlyTemplateId(tmpltId); if (tmpltHosts != null) { Collections.shuffle(tmpltHosts); @@ -260,13 +261,13 @@ public class SwiftManagerImpl implements SwiftManager { } @Override - public List listSwifts(ListSwiftsCmd cmd) { + public Pair, Integer> listSwifts(ListSwiftsCmd cmd) { Filter searchFilter = new Filter(SwiftVO.class, "id", Boolean.TRUE, cmd.getStartIndex(), cmd.getPageSizeVal()); SearchCriteria sc = _swiftDao.createSearchCriteria(); if (cmd.getId() != null) { sc.addAnd("id", SearchCriteria.Op.EQ, cmd.getId()); } - return _swiftDao.search(sc, searchFilter); + return _swiftDao.searchAndCount(sc, searchFilter); } diff --git a/server/test/com/cloud/resource/MockResourceManagerImpl.java b/server/test/com/cloud/resource/MockResourceManagerImpl.java index e94cdea9853..a0dad479144 100644 --- a/server/test/com/cloud/resource/MockResourceManagerImpl.java +++ b/server/test/com/cloud/resource/MockResourceManagerImpl.java @@ -202,7 +202,7 @@ public class MockResourceManagerImpl implements ResourceManager, Manager { * @see com.cloud.resource.ResourceService#listSwifts(com.cloud.api.commands.ListSwiftsCmd) */ @Override - public List listSwifts(ListSwiftsCmd cmd) { + public Pair, Integer> listSwifts(ListSwiftsCmd cmd) { // TODO Auto-generated method stub return null; } From 1e40551cd524506d44762f305358d530a2ad3319 Mon Sep 17 00:00:00 2001 From: Hugo Trippaers Date: Wed, 23 Jan 2013 08:46:53 +0100 Subject: [PATCH 59/80] Disabled test 'com.cloud.network.vpn.RemoteAccessVpnTest' as it requires a database connection which we don't have during unittest phase. --- server/pom.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/server/pom.xml b/server/pom.xml index 64bd2a206da..4c3ba6f9e76 100644 --- a/server/pom.xml +++ b/server/pom.xml @@ -105,6 +105,7 @@ com/cloud/vm/dao/* com/cloud/vpc/* com/cloud/api/ListPerfTest.java + com/cloud/network/vpn/RemoteAccessVpnTest.java From 75b059e6e4e482de3ad0629f9eb236beb0d257dd Mon Sep 17 00:00:00 2001 From: Prasanna Santhanam Date: Wed, 23 Jan 2013 16:01:45 +0530 Subject: [PATCH 60/80] cloudmonkey: misses a couple of verbs for 'lock' and 'disassociate' The following api commands have no cloudmonkey equivalent because cloudmonkey grammar misses the related verbs. ~/tools/cli/cloudmonkey/marvin/cloudstackAPI(branch:master*) $ ls disassociateIpAddress.py disassociateIpAddress.py ------------------------------------------------------------ ~/tools/cli/cloudmonkey/marvin/cloudstackAPI(branch:master*) $ ls lock* lockAccount.py lockUser.py ------------------------------------------------------------ Signed-off-by: Prasanna Santhanam --- tools/cli/cloudmonkey/common.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tools/cli/cloudmonkey/common.py b/tools/cli/cloudmonkey/common.py index 3199af26c85..0865a8ee8cc 100644 --- a/tools/cli/cloudmonkey/common.py +++ b/tools/cli/cloudmonkey/common.py @@ -40,9 +40,9 @@ config_fields = {'host': 'localhost', 'port': '8080', os.path.expanduser('~/.cloudmonkey_history')} # Add verbs in grammar -grammar = ['create', 'list', 'delete', 'update', +grammar = ['create', 'list', 'delete', 'update', 'lock', 'enable', 'activate', 'disable', 'add', 'remove', - 'attach', 'detach', 'associate', 'generate', 'ldap', + 'attach', 'detach', 'associate', 'disassociate', 'generate', 'ldap', 'assign', 'authorize', 'change', 'register', 'configure', 'start', 'restart', 'reboot', 'stop', 'reconnect', 'cancel', 'destroy', 'revoke', 'mark', 'reset', From 485761f0b4b74e7f8ad63221168485fdfe666678 Mon Sep 17 00:00:00 2001 From: Min Chen Date: Wed, 23 Jan 2013 10:16:17 -0800 Subject: [PATCH 61/80] Fix a bug for listZones and listServiceOfferings for normal user, caused by a misuse of SearchCriteria class. --- server/src/com/cloud/api/query/QueryManagerImpl.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/server/src/com/cloud/api/query/QueryManagerImpl.java b/server/src/com/cloud/api/query/QueryManagerImpl.java index a943776a6c2..cf240b17548 100644 --- a/server/src/com/cloud/api/query/QueryManagerImpl.java +++ b/server/src/com/cloud/api/query/QueryManagerImpl.java @@ -2131,7 +2131,7 @@ public class QueryManagerImpl implements QueryService, Manager { domainRecord = _domainDao.findById(domainRecord.getParent()); domainIds.add(domainRecord.getId()); } - sc.addAnd("domainIdIn", SearchCriteria.Op.IN, domainIds); + sc.addAnd("domainId", SearchCriteria.Op.IN, domainIds); // include also public offering if no keyword, name and id specified if ( keyword == null && name == null && id == null ){ @@ -2261,7 +2261,7 @@ public class QueryManagerImpl implements QueryService, Manager { } // domainId == null (public zones) or domainId IN [all domain id up to root domain] SearchCriteria sdc = _dcJoinDao.createSearchCriteria(); - sdc.addOr("domainIdIn", SearchCriteria.Op.IN, domainIds); + sdc.addOr("domainId", SearchCriteria.Op.IN, domainIds); sdc.addOr("domainId", SearchCriteria.Op.NULL); sc.addAnd("domain", SearchCriteria.Op.SC, sdc); @@ -2291,7 +2291,7 @@ public class QueryManagerImpl implements QueryService, Manager { // domainId == null (public zones) or domainId IN [all domain id up to root domain] SearchCriteria sdc = _dcJoinDao.createSearchCriteria(); - sdc.addOr("domainIdIn", SearchCriteria.Op.IN, domainIds); + sdc.addOr("domainId", SearchCriteria.Op.IN, domainIds); sdc.addOr("domainId", SearchCriteria.Op.NULL); sc.addAnd("domain", SearchCriteria.Op.SC, sdc); From dba413a3d4b1ea8320821c8ab15f193f98f01304 Mon Sep 17 00:00:00 2001 From: Rohit Yadav Date: Wed, 23 Jan 2013 10:57:08 -0800 Subject: [PATCH 62/80] CreateNetworkOfferingCmd: Fix correct annotation for serviceofferingId param Thanks to Hugo for pointing this out: http://markmail.org/thread/gbu4pkanncbe4xqt Signed-off-by: Rohit Yadav --- .../api/command/admin/network/CreateNetworkOfferingCmd.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/api/src/org/apache/cloudstack/api/command/admin/network/CreateNetworkOfferingCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/CreateNetworkOfferingCmd.java index 6733a35a5fd..9d3ceb828e1 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/network/CreateNetworkOfferingCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/network/CreateNetworkOfferingCmd.java @@ -24,7 +24,7 @@ import java.util.List; import java.util.Map; import org.apache.cloudstack.api.*; -import org.apache.cloudstack.api.response.DiskOfferingResponse; +import org.apache.cloudstack.api.response.ServiceOfferingResponse; import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; @@ -69,7 +69,7 @@ public class CreateNetworkOfferingCmd extends BaseCmd { @Parameter(name=ApiConstants.CONSERVE_MODE, type=CommandType.BOOLEAN, description="true if the network offering is IP conserve mode enabled") private Boolean conserveMode; - @Parameter(name=ApiConstants.SERVICE_OFFERING_ID, type=CommandType.UUID, entityType=DiskOfferingResponse.class, + @Parameter(name=ApiConstants.SERVICE_OFFERING_ID, type=CommandType.UUID, entityType=ServiceOfferingResponse.class, description="the service offering ID used by virtual router provider") private Long serviceOfferingId; From 31a5669c7c02b4bba3c44e44b9c3b6b1645d2e59 Mon Sep 17 00:00:00 2001 From: Brian Federle Date: Tue, 22 Jan 2013 11:42:23 -0800 Subject: [PATCH 63/80] Hide VPC drop-down for advanced SG zones --- ui/css/cloudstack3.css | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/ui/css/cloudstack3.css b/ui/css/cloudstack3.css index db101d21ec4..6519ed053e8 100644 --- a/ui/css/cloudstack3.css +++ b/ui/css/cloudstack3.css @@ -5859,6 +5859,10 @@ label.error { margin: 7px 0px 7px 7px; } +.multi-wizard.instance-wizard .select-network.no-add-network .select-vpc { + visibility: hidden !important; +} + .multi-wizard.instance-wizard .select-network .select-vpc select { width: 124px; } From 8273af7cbfaa3c0851821c44774f048b20f85b54 Mon Sep 17 00:00:00 2001 From: Rohit Yadav Date: Wed, 23 Jan 2013 11:35:21 -0800 Subject: [PATCH 64/80] CopyTemplateCmd: Fix correct annotation for id param in copytemplate Signed-off-by: Rohit Yadav --- .../cloudstack/api/command/user/template/CopyTemplateCmd.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/api/src/org/apache/cloudstack/api/command/user/template/CopyTemplateCmd.java b/api/src/org/apache/cloudstack/api/command/user/template/CopyTemplateCmd.java index 406f32cc958..f865dd6d493 100644 --- a/api/src/org/apache/cloudstack/api/command/user/template/CopyTemplateCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/template/CopyTemplateCmd.java @@ -51,7 +51,7 @@ public class CopyTemplateCmd extends BaseAsyncCmd { required=true, description="ID of the zone the template is being copied to.") private Long destZoneId; - @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = UserVmResponse.class, + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = TemplateResponse.class, required=true, description="Template ID.") private Long id; From cbdeeebc6c1864e9ccdae55d0a125929e7be7b30 Mon Sep 17 00:00:00 2001 From: Rohit Yadav Date: Wed, 23 Jan 2013 13:47:56 -0800 Subject: [PATCH 65/80] IteratorUtil: Add generic method to return sorted list out of a collection Signed-off-by: Rohit Yadav --- utils/src/com/cloud/utils/IteratorUtil.java | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/utils/src/com/cloud/utils/IteratorUtil.java b/utils/src/com/cloud/utils/IteratorUtil.java index d7a85f1e6d3..0a7fd72c882 100644 --- a/utils/src/com/cloud/utils/IteratorUtil.java +++ b/utils/src/com/cloud/utils/IteratorUtil.java @@ -16,8 +16,11 @@ // under the License. package com.cloud.utils; +import java.util.ArrayList; +import java.util.Collection; import java.util.Enumeration; import java.util.Iterator; +import java.util.List; public class IteratorUtil { public static Iterable enumerationAsIterable(final Enumeration e) { @@ -51,4 +54,11 @@ public class IteratorUtil { } }; } + + public static + > List asSortedList(Collection c) { + List list = new ArrayList(c); + java.util.Collections.sort(list); + return list; + } } From a8623bacd73a1b1026df8770be1c6a98bde11ba6 Mon Sep 17 00:00:00 2001 From: Rohit Yadav Date: Wed, 23 Jan 2013 13:50:59 -0800 Subject: [PATCH 66/80] ApiXmlDocWriter: Fix multiple field occurence in apidocs by using set Signed-off-by: Rohit Yadav --- .../com/cloud/api/doc/ApiXmlDocWriter.java | 20 +++++++++---------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/server/src/com/cloud/api/doc/ApiXmlDocWriter.java b/server/src/com/cloud/api/doc/ApiXmlDocWriter.java index 84851c389ad..c3c0cabdf17 100644 --- a/server/src/com/cloud/api/doc/ApiXmlDocWriter.java +++ b/server/src/com/cloud/api/doc/ApiXmlDocWriter.java @@ -28,6 +28,7 @@ import java.util.*; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; +import com.cloud.utils.IteratorUtil; import com.cloud.utils.ReflectUtil; import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; @@ -135,7 +136,7 @@ public class ApiXmlDocWriter { String commandRoleMask = preProcessedCommand.substring(splitIndex + 1); Class cmdClass = _apiNameCmdClassMap.get(key); if (cmdClass == null) { - System.out.println("Check, Null Value for key: " + key + " preProcessedCommand=" + preProcessedCommand); + System.out.println("Check, is this api part of another build profile? Null value for key: " + key + " preProcessedCommand=" + preProcessedCommand); continue; } String commandName = cmdClass.getName(); @@ -349,7 +350,7 @@ public class ApiXmlDocWriter { apiCommand.setAsync(isAsync); - Field[] fields = ReflectUtil.getAllFieldsForClass(clas, + Set fields = ReflectUtil.getAllFieldsForClass(clas, new Class[] {BaseCmd.class, BaseAsyncCmd.class, BaseAsyncCreateCmd.class}); request = setRequestFields(fields); @@ -422,10 +423,10 @@ public class ApiXmlDocWriter { out.writeObject(apiCommand); } - private static ArrayList setRequestFields(Field[] fields) { + private static ArrayList setRequestFields(Set fields) { ArrayList arguments = new ArrayList(); - ArrayList requiredArguments = new ArrayList(); - ArrayList optionalArguments = new ArrayList(); + Set requiredArguments = new HashSet(); + Set optionalArguments = new HashSet(); Argument id = null; for (Field f : fields) { Parameter parameterAnnotation = f.getAnnotation(Parameter.class); @@ -444,7 +445,7 @@ public class ApiXmlDocWriter { reqArg.setSinceVersion(parameterAnnotation.since()); } - if (reqArg.isRequired() == true) { + if (reqArg.isRequired()) { if (parameterAnnotation.name().equals("id")) { id = reqArg; } else { @@ -456,15 +457,12 @@ public class ApiXmlDocWriter { } } - Collections.sort(requiredArguments); - Collections.sort(optionalArguments); - // sort required and optional arguments here if (id != null) { arguments.add(id); } - arguments.addAll(requiredArguments); - arguments.addAll(optionalArguments); + arguments.addAll(IteratorUtil.asSortedList(requiredArguments)); + arguments.addAll(IteratorUtil.asSortedList(optionalArguments)); return arguments; } From 34f3e1c9a1ec07c9fbb34105732a9a431eb13910 Mon Sep 17 00:00:00 2001 From: Rohit Yadav Date: Wed, 23 Jan 2013 13:52:12 -0800 Subject: [PATCH 67/80] ApiDiscoveryServiceImpl: Fix fields variable definition from array to set Signed-off-by: Rohit Yadav --- .../apache/cloudstack/discovery/ApiDiscoveryServiceImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/api/discovery/src/org/apache/cloudstack/discovery/ApiDiscoveryServiceImpl.java b/plugins/api/discovery/src/org/apache/cloudstack/discovery/ApiDiscoveryServiceImpl.java index 5ac2281b84e..bfd2719d8bd 100644 --- a/plugins/api/discovery/src/org/apache/cloudstack/discovery/ApiDiscoveryServiceImpl.java +++ b/plugins/api/discovery/src/org/apache/cloudstack/discovery/ApiDiscoveryServiceImpl.java @@ -107,7 +107,7 @@ public class ApiDiscoveryServiceImpl implements ApiDiscoveryService { } } - Field[] fields = ReflectUtil.getAllFieldsForClass(cmdClass, + Set fields = ReflectUtil.getAllFieldsForClass(cmdClass, new Class[]{BaseCmd.class, BaseAsyncCmd.class, BaseAsyncCreateCmd.class}); boolean isAsync = ReflectUtil.isCmdClassAsync(cmdClass, From 7a927e36f0824f0a74d6a57f68ff38bfc0dcade6 Mon Sep 17 00:00:00 2001 From: Rohit Yadav Date: Wed, 23 Jan 2013 13:53:00 -0800 Subject: [PATCH 68/80] ReflectUtil: Use collections to grow list and not manual array memory management Fix usage in ApiDispatcher. Add two kinds of helpers: - One that gets list of exclude cmd whose fields are not be included - One that loops till a base class is asssignable from superclass Signed-off-by: Rohit Yadav --- server/src/com/cloud/api/ApiDispatcher.java | 4 +- utils/src/com/cloud/utils/ReflectUtil.java | 48 ++++++++++++++------- 2 files changed, 34 insertions(+), 18 deletions(-) diff --git a/server/src/com/cloud/api/ApiDispatcher.java b/server/src/com/cloud/api/ApiDispatcher.java index 129ef7d4a2e..4ca040ca92b 100755 --- a/server/src/com/cloud/api/ApiDispatcher.java +++ b/server/src/com/cloud/api/ApiDispatcher.java @@ -27,6 +27,7 @@ import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.StringTokenizer; import java.util.regex.Matcher; @@ -190,8 +191,7 @@ public class ApiDispatcher { } } - Field[] fields = ReflectUtil.getAllFieldsForClass(cmd.getClass(), - new Class[] {BaseCmd.class}); + List fields = ReflectUtil.getAllFieldsForClass(cmd.getClass(), BaseCmd.class); for (Field field : fields) { PlugService plugServiceAnnotation = field.getAnnotation(PlugService.class); diff --git a/utils/src/com/cloud/utils/ReflectUtil.java b/utils/src/com/cloud/utils/ReflectUtil.java index 09447059fe6..e5a890a28e2 100755 --- a/utils/src/com/cloud/utils/ReflectUtil.java +++ b/utils/src/com/cloud/utils/ReflectUtil.java @@ -19,7 +19,10 @@ package com.cloud.utils; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Collections; import java.util.HashSet; +import java.util.List; import java.util.Set; import com.cloud.utils.exception.CloudRuntimeException; @@ -87,26 +90,39 @@ public class ReflectUtil { return isAsync; } - // Returns all fields across the base class for a cmd - public static Field[] getAllFieldsForClass(Class cmdClass, - Class[] searchClasses) { - Field[] fields = cmdClass.getDeclaredFields(); + // Returns all fields until a base class for a cmd class + public static List getAllFieldsForClass(Class cmdClass, + Class baseClass) { + List fields = new ArrayList(); + Collections.addAll(fields, cmdClass.getDeclaredFields()); + Class superClass = cmdClass.getSuperclass(); + while (baseClass.isAssignableFrom(superClass)) { + Field[] superClassFields = superClass.getDeclaredFields(); + if (superClassFields != null) + Collections.addAll(fields, superClassFields); + superClass = superClass.getSuperclass(); + } + return fields; + } + + // Returns all unique fields except excludeClasses for a cmd class + public static Set getAllFieldsForClass(Class cmdClass, + Class[] excludeClasses) { + Set fields = new HashSet(); + Collections.addAll(fields, cmdClass.getDeclaredFields()); Class superClass = cmdClass.getSuperclass(); while (superClass != null && superClass != Object.class) { String superName = superClass.getName(); - for (Class baseClass: searchClasses) { - if(!baseClass.isAssignableFrom(superClass)) - continue; - if (!superName.equals(baseClass.getName())) { - Field[] superClassFields = superClass.getDeclaredFields(); - if (superClassFields != null) { - Field[] tmpFields = new Field[fields.length + superClassFields.length]; - System.arraycopy(fields, 0, tmpFields, 0, fields.length); - System.arraycopy(superClassFields, 0, tmpFields, fields.length, superClassFields.length); - fields = tmpFields; - } - } + boolean isNameEqualToSuperName = false; + for (Class baseClass: excludeClasses) + if (superName.equals(baseClass.getName())) + isNameEqualToSuperName = true; + + if (!isNameEqualToSuperName) { + Field[] superClassFields = superClass.getDeclaredFields(); + if (superClassFields != null) + Collections.addAll(fields, superClassFields); } superClass = superClass.getSuperclass(); } From 3c335bd88316a82e0295e061236233a5ca599993 Mon Sep 17 00:00:00 2001 From: Rohit Yadav Date: Wed, 23 Jan 2013 14:12:38 -0800 Subject: [PATCH 69/80] cli: Fix asyncblock to search for correct key instead of hardcoded index Signed-off-by: Rohit Yadav --- tools/cli/cloudmonkey/cloudmonkey.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/tools/cli/cloudmonkey/cloudmonkey.py b/tools/cli/cloudmonkey/cloudmonkey.py index 339a2014522..d679e5059f1 100644 --- a/tools/cli/cloudmonkey/cloudmonkey.py +++ b/tools/cli/cloudmonkey/cloudmonkey.py @@ -262,8 +262,9 @@ class CloudMonkeyShell(cmd.Cmd, object): return isAsync = isAsync and (self.asyncblock == "true") - if isAsync and 'jobid' in response[response.keys()[0]]: - jobId = response[response.keys()[0]]['jobid'] + responsekey = filter(lambda x: 'response' in x, response.keys())[0] + if isAsync and 'jobid' in response[responsekey]: + jobId = response[responsekey]['jobid'] command = "queryAsyncJobResult" requests = {'jobid': jobId} timeout = int(self.timeout) @@ -282,7 +283,7 @@ class CloudMonkeyShell(cmd.Cmd, object): jobstatus = result['jobstatus'] if jobstatus == 2: jobresult = result["jobresult"] - self.print_shell("Async query failed for jobid=", + self.print_shell("\rAsync query failed for jobid", jobId, "\nError", jobresult["errorcode"], jobresult["errortext"]) return @@ -293,7 +294,7 @@ class CloudMonkeyShell(cmd.Cmd, object): timeout = timeout - pollperiod progress += 1 logger.debug("job: %s to timeout in %ds" % (jobId, timeout)) - self.print_shell("Error:", "Async query timeout for jobid=", jobId) + self.print_shell("Error:", "Async query timeout for jobid", jobId) return response From b335684ec5122d65a79ca45b10d508e760d31945 Mon Sep 17 00:00:00 2001 From: Rohit Yadav Date: Wed, 23 Jan 2013 14:55:26 -0800 Subject: [PATCH 70/80] EntityManager: Implement method to search by uuid including removed entities Signed-off-by: Rohit Yadav --- api/src/com/cloud/dao/EntityManager.java | 9 +++++++++ server/src/com/cloud/dao/EntityManagerImpl.java | 7 +++++++ 2 files changed, 16 insertions(+) diff --git a/api/src/com/cloud/dao/EntityManager.java b/api/src/com/cloud/dao/EntityManager.java index 4e4b9c293b5..b8fdaa7e9a7 100644 --- a/api/src/com/cloud/dao/EntityManager.java +++ b/api/src/com/cloud/dao/EntityManager.java @@ -47,6 +47,15 @@ public interface EntityManager { */ public T findByUuid(Class entityType, String uuid); + /** + * Finds a unique entity by uuid string + * @param entity class + * @param entityType type of entity you're looking for. + * @param uuid the unique id + * @return T if found, null if not. + */ + public T findByUuidIncludingRemoved(Class entityType, String uuid); + /** * Finds an entity by external id which is always String * @param entity class diff --git a/server/src/com/cloud/dao/EntityManagerImpl.java b/server/src/com/cloud/dao/EntityManagerImpl.java index 2eee445f933..1d881927533 100644 --- a/server/src/com/cloud/dao/EntityManagerImpl.java +++ b/server/src/com/cloud/dao/EntityManagerImpl.java @@ -51,6 +51,13 @@ public class EntityManagerImpl implements EntityManager, Manager { return dao.findByUuid(uuid); } + @Override + public T findByUuidIncludingRemoved(Class entityType, String uuid) { + // Finds and returns a unique VO using uuid, null if entity not found in db + GenericDao dao = (GenericDao)GenericDaoBase.getDao(entityType); + return dao.findByUuidIncludingRemoved(uuid); + } + @Override public T findByXId(Class entityType, String xid) { return null; From 03d2c015ae70ff0f50adeb9551feca8d27752321 Mon Sep 17 00:00:00 2001 From: Rohit Yadav Date: Wed, 23 Jan 2013 14:55:55 -0800 Subject: [PATCH 71/80] GenericDao: Add method to find by uuid string including removed entities Signed-off-by: Rohit Yadav --- utils/src/com/cloud/utils/db/GenericDao.java | 3 +++ utils/src/com/cloud/utils/db/GenericDaoBase.java | 8 ++++++++ 2 files changed, 11 insertions(+) diff --git a/utils/src/com/cloud/utils/db/GenericDao.java b/utils/src/com/cloud/utils/db/GenericDao.java index 15d04b76a1c..31a25fd7088 100755 --- a/utils/src/com/cloud/utils/db/GenericDao.java +++ b/utils/src/com/cloud/utils/db/GenericDao.java @@ -57,6 +57,9 @@ public interface GenericDao { // Finds one unique VO using uuid T findByUuid(String uuid); + + // Finds one unique VO using uuid including removed entities + T findByUuidIncludingRemoved(String uuid); /** * @return VO object ready to be used for update. It won't have any fields filled in. diff --git a/utils/src/com/cloud/utils/db/GenericDaoBase.java b/utils/src/com/cloud/utils/db/GenericDaoBase.java index 880e9de22a8..0d73b902354 100755 --- a/utils/src/com/cloud/utils/db/GenericDaoBase.java +++ b/utils/src/com/cloud/utils/db/GenericDaoBase.java @@ -921,6 +921,14 @@ public abstract class GenericDaoBase implements Gene return findOneBy(sc); } + @Override @DB(txn=false) + @SuppressWarnings("unchecked") + public T findByUuidIncludingRemoved(final String uuid) { + SearchCriteria sc = createSearchCriteria(); + sc.addAnd("uuid", SearchCriteria.Op.EQ, uuid); + return findOneIncludingRemovedBy(sc); + } + @Override @DB(txn=false) public T findByIdIncludingRemoved(ID id) { return findById(id, true, null); From a7fd74f94a29ac64cd4ac03e079b38252005a0a7 Mon Sep 17 00:00:00 2001 From: Rohit Yadav Date: Wed, 23 Jan 2013 14:56:34 -0800 Subject: [PATCH 72/80] ApiDispatcher: Fix uuid->id translation and throw better debug statement Signed-off-by: Rohit Yadav --- server/src/com/cloud/api/ApiDispatcher.java | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/server/src/com/cloud/api/ApiDispatcher.java b/server/src/com/cloud/api/ApiDispatcher.java index 4ca040ca92b..f7d881dfe30 100755 --- a/server/src/com/cloud/api/ApiDispatcher.java +++ b/server/src/com/cloud/api/ApiDispatcher.java @@ -158,8 +158,7 @@ public class ApiDispatcher { } if (queueSizeLimit != null) { - _asyncMgr - .syncAsyncJobExecution(asyncCmd.getJob(), asyncCmd.getSyncObjType(), asyncCmd.getSyncObjId().longValue(), queueSizeLimit); + _asyncMgr.syncAsyncJobExecution(asyncCmd.getJob(), asyncCmd.getSyncObjType(), asyncCmd.getSyncObjId().longValue(), queueSizeLimit); } else { s_logger.trace("The queue size is unlimited, skipping the synchronizing"); } @@ -360,8 +359,9 @@ public class ApiDispatcher { // Go through each entity which is an interface to a VO class and get a VO object // Try to getId() for the object using reflection, break on first non-null value for (Class entity: entities) { - // findByUuid returns one VO object using uuid, use reflect to get the Id - Object objVO = s_instance._entityMgr.findByUuid(entity, uuid); + // For backward compatibility, we search within removed entities and let service layer deal + // with removed ones, return empty response or error + Object objVO = s_instance._entityMgr.findByUuidIncludingRemoved(entity, uuid); if (objVO == null) { continue; } @@ -377,11 +377,10 @@ public class ApiDispatcher { break; } if (internalId == null) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Object entity with uuid=" + uuid + " does not exist in the database."); - } + if (s_logger.isDebugEnabled()) + s_logger.debug("Object entity uuid = " + uuid + " does not exist in the database."); throw new InvalidParameterValueException("Invalid parameter value=" + uuid - + " due to incorrect long value, entity not found, or an annotation bug."); + + " due to incorrect long value format, or entity was not found as it may have been deleted, or due to incorrect parameter annotation for the field in api cmd."); } return internalId; } From 9e91584d07fd9c5e3890805274132bb4ce32809f Mon Sep 17 00:00:00 2001 From: Rohit Yadav Date: Wed, 23 Jan 2013 15:50:56 -0800 Subject: [PATCH 73/80] CLOUDSTACK-225: Fix redundant field values in class and apidocs Signed-off-by: Rohit Yadav --- .../api/BaseListAccountResourcesCmd.java | 2 +- .../api/command/user/vpc/ListVPCsCmd.java | 17 ----------------- 2 files changed, 1 insertion(+), 18 deletions(-) diff --git a/api/src/org/apache/cloudstack/api/BaseListAccountResourcesCmd.java b/api/src/org/apache/cloudstack/api/BaseListAccountResourcesCmd.java index 038da63ec4c..0586117f0c6 100644 --- a/api/src/org/apache/cloudstack/api/BaseListAccountResourcesCmd.java +++ b/api/src/org/apache/cloudstack/api/BaseListAccountResourcesCmd.java @@ -18,7 +18,7 @@ package org.apache.cloudstack.api; public abstract class BaseListAccountResourcesCmd extends BaseListDomainResourcesCmd { - @Parameter(name = ApiConstants.ACCOUNT, type = CommandType.STRING, description = "List resources by account. Must be used with the domainId parameter.") + @Parameter(name = ApiConstants.ACCOUNT, type = CommandType.STRING, description = "list resources by account. Must be used with the domainId parameter.") private String accountName; public String getAccountName() { diff --git a/api/src/org/apache/cloudstack/api/command/user/vpc/ListVPCsCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpc/ListVPCsCmd.java index 6d3c8bd06c7..2501574f241 100644 --- a/api/src/org/apache/cloudstack/api/command/user/vpc/ListVPCsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpc/ListVPCsCmd.java @@ -64,15 +64,6 @@ public class ListVPCsCmd extends BaseListTaggedResourcesCmd{ , description="list by ID of the VPC offering") private Long VpcOffId; - @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="list by account associated with the VPC. " + - "Must be used with the domainId parameter.") - private String accountName; - - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType=DomainResponse.class, - description="list by domain ID associated with the VPC. " + - "If used with the account parameter returns the VPC associated with the account for the specified domain.") - private Long domainId; - @Parameter(name=ApiConstants.SUPPORTED_SERVICES, type=CommandType.LIST, collectionType=CommandType.STRING, description="list VPC supporting certain services") private List supportedServices; @@ -87,14 +78,6 @@ public class ListVPCsCmd extends BaseListTaggedResourcesCmd{ /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - public String getAccountName() { - return accountName; - } - - public Long getDomainId() { - return domainId; - } - public Long getZoneId() { return zoneId; } From ec0c6b00b4a663af08527990bb019c239fcb2816 Mon Sep 17 00:00:00 2001 From: Rohit Yadav Date: Wed, 23 Jan 2013 16:00:39 -0800 Subject: [PATCH 74/80] api: Fix correct annotation value in template cmds for template id Signed-off-by: Rohit Yadav --- .../api/command/user/template/DeleteTemplateCmd.java | 4 ++-- .../api/command/user/template/ExtractTemplateCmd.java | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/api/src/org/apache/cloudstack/api/command/user/template/DeleteTemplateCmd.java b/api/src/org/apache/cloudstack/api/command/user/template/DeleteTemplateCmd.java index 8ee3041713c..12359bfe9ac 100644 --- a/api/src/org/apache/cloudstack/api/command/user/template/DeleteTemplateCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/template/DeleteTemplateCmd.java @@ -17,7 +17,7 @@ package org.apache.cloudstack.api.command.user.template; import org.apache.cloudstack.api.*; -import org.apache.cloudstack.api.response.UserVmResponse; +import org.apache.cloudstack.api.response.TemplateResponse; import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.log4j.Logger; @@ -38,7 +38,7 @@ public class DeleteTemplateCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = UserVmResponse.class, + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = TemplateResponse.class, required=true, description="the ID of the template") private Long id; diff --git a/api/src/org/apache/cloudstack/api/command/user/template/ExtractTemplateCmd.java b/api/src/org/apache/cloudstack/api/command/user/template/ExtractTemplateCmd.java index 54f3e3782fb..8b4e809f247 100644 --- a/api/src/org/apache/cloudstack/api/command/user/template/ExtractTemplateCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/template/ExtractTemplateCmd.java @@ -17,7 +17,7 @@ package org.apache.cloudstack.api.command.user.template; import org.apache.cloudstack.api.*; -import org.apache.cloudstack.api.response.UserVmResponse; +import org.apache.cloudstack.api.response.TemplateResponse; import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.log4j.Logger; @@ -40,7 +40,7 @@ public class ExtractTemplateCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = UserVmResponse.class, + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = TemplateResponse.class, required=true, description="the ID of the template") private Long id; From afb7e289fe3d6936d20b257ec2b753a265a7b9a9 Mon Sep 17 00:00:00 2001 From: Rohit Yadav Date: Wed, 23 Jan 2013 18:15:51 -0800 Subject: [PATCH 75/80] cli: Fix development status to stable. cloudmonkey v1 at its most stable form Signed-off-by: Rohit Yadav --- tools/cli/setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/cli/setup.py b/tools/cli/setup.py index 739c044f7dd..f1efa741a02 100644 --- a/tools/cli/setup.py +++ b/tools/cli/setup.py @@ -53,7 +53,7 @@ setup( include_package_data = True, zip_safe = False, classifiers = [ - "Development Status :: 4 - Beta", + "Development Status :: 5 - Production/Stable", "Environment :: Console", "Intended Audience :: Developers", "Intended Audience :: End Users/Desktop", From f1aee2cc505c7af37d0880135bf886ff8deaf9c8 Mon Sep 17 00:00:00 2001 From: Pranav Saxena Date: Thu, 24 Jan 2013 14:13:53 +0530 Subject: [PATCH 76/80] CLOUDSTACK-1029:Enter the token to specified project is malfunctioned --- ui/scripts/projects.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ui/scripts/projects.js b/ui/scripts/projects.js index 31b68e7a338..b62dcb4c6a2 100644 --- a/ui/scripts/projects.js +++ b/ui/scripts/projects.js @@ -1026,7 +1026,7 @@ createForm: { desc: 'message.enter.token', fields: { - projectid: { label: 'label.project.id', validation: { required: true, docID: 'helpEnterTokenProjectID' }}, + projectid: { label: 'label.project.id', validation: { required: true}, docID: 'helpEnterTokenProjectID' }, token: { label: 'label.token', docID: 'helpEnterTokenToken', validation: { required: true }} } }, From 531c2f030c883a9c9a81b20ce1d85380e5a61739 Mon Sep 17 00:00:00 2001 From: Rohit Yadav Date: Thu, 24 Jan 2013 10:32:35 -0800 Subject: [PATCH 77/80] api: Fix annotations on iso related cmd Signed-off-by: Rohit Yadav --- .../apache/cloudstack/api/command/user/iso/AttachIsoCmd.java | 2 +- .../apache/cloudstack/api/command/user/iso/DetachIsoCmd.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/api/src/org/apache/cloudstack/api/command/user/iso/AttachIsoCmd.java b/api/src/org/apache/cloudstack/api/command/user/iso/AttachIsoCmd.java index 2a0b2c61617..89e72920db0 100644 --- a/api/src/org/apache/cloudstack/api/command/user/iso/AttachIsoCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/iso/AttachIsoCmd.java @@ -47,7 +47,7 @@ public class AttachIsoCmd extends BaseAsyncCmd { required=true, description="the ID of the ISO file") private Long id; - @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.UUID, entityType = TemplateResponse.class, + @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.UUID, entityType = UserVmResponse.class, required=true, description="the ID of the virtual machine") private Long virtualMachineId; diff --git a/api/src/org/apache/cloudstack/api/command/user/iso/DetachIsoCmd.java b/api/src/org/apache/cloudstack/api/command/user/iso/DetachIsoCmd.java index c8a87cbdb3e..2a6ecf4ce10 100644 --- a/api/src/org/apache/cloudstack/api/command/user/iso/DetachIsoCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/iso/DetachIsoCmd.java @@ -42,7 +42,7 @@ public class DetachIsoCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.UUID, entityType = TemplateResponse.class, + @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.UUID, entityType = UserVmResponse.class, required=true, description="The ID of the virtual machine") private Long virtualMachineId; From 71257d6bb4dfa1651f21c78d6ca6ede6dce91f34 Mon Sep 17 00:00:00 2001 From: Rohit Yadav Date: Thu, 24 Jan 2013 11:28:49 -0800 Subject: [PATCH 78/80] cli: give filter option only when output 'tabularized' is enabled Signed-off-by: Rohit Yadav --- tools/cli/cloudmonkey/cloudmonkey.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tools/cli/cloudmonkey/cloudmonkey.py b/tools/cli/cloudmonkey/cloudmonkey.py index d679e5059f1..ace6a8b9b7a 100644 --- a/tools/cli/cloudmonkey/cloudmonkey.py +++ b/tools/cli/cloudmonkey/cloudmonkey.py @@ -388,7 +388,8 @@ class CloudMonkeyShell(cmd.Cmd, object): self.cache_verbs[verb][subject][1]) search_string = text - autocompletions.append("filter=") + if self.tabularize == "true": + autocompletions.append("filter=") return [s for s in autocompletions if s.startswith(search_string)] def do_api(self, args): From 6f90a86b13ae91441870a008e1e2ff0adc3c26a3 Mon Sep 17 00:00:00 2001 From: Rohit Yadav Date: Thu, 24 Jan 2013 14:47:45 -0800 Subject: [PATCH 79/80] cli: fix cloudmonkey's pipe-ability Signed-off-by: Rohit Yadav --- tools/cli/cloudmonkey/cloudmonkey.py | 30 +++++++++++++++++++--------- 1 file changed, 21 insertions(+), 9 deletions(-) diff --git a/tools/cli/cloudmonkey/cloudmonkey.py b/tools/cli/cloudmonkey/cloudmonkey.py index ace6a8b9b7a..eadf23ff173 100644 --- a/tools/cli/cloudmonkey/cloudmonkey.py +++ b/tools/cli/cloudmonkey/cloudmonkey.py @@ -75,7 +75,8 @@ class CloudMonkeyShell(cmd.Cmd, object): # datastructure {'verb': {cmd': ['api', [params], doc, required=[]]}} cache_verbs = precached_verbs - def __init__(self): + def __init__(self, pname): + self.program_name = pname if os.path.exists(self.config_file): config = self.read_config() else: @@ -307,7 +308,19 @@ class CloudMonkeyShell(cmd.Cmd, object): return None return api_mod + def pipe_runner(self, args): + if args.find(' |') > -1: + pname = self.program_name + if '.py' in pname: + pname = "python " + pname + self.do_shell("%s %s" % (pname, args)) + return True + return False + def default(self, args): + if self.pipe_runner(args): + return + lexp = shlex.shlex(args.strip()) lexp.whitespace = " " lexp.whitespace_split = True @@ -506,22 +519,21 @@ def main(): for rule in grammar: def add_grammar(rule): def grammar_closure(self, args): - if '|' in args: # FIXME: Consider parsing issues - prog_name = sys.argv[0] - if '.py' in prog_name: - prog_name = "python " + prog_name - self.do_shell("%s %s %s" % (prog_name, rule, args)) + if self.pipe_runner("%s %s" % (rule, args)): return try: args_partition = args.partition(" ") res = self.cache_verbs[rule][args_partition[0]] + cmd = res[0] + helpdoc = res[2] + args = args_partition[2] except KeyError, e: self.print_shell("Error: invalid %s api arg" % rule, e) return if ' --help' in args or ' -h' in args: - self.print_shell(res[2]) + self.print_shell(helpdoc) return - self.default(res[0] + " " + args_partition[2]) + self.default("%s %s" % (cmd, args)) return grammar_closure grammar_handler = add_grammar(rule) @@ -529,7 +541,7 @@ def main(): grammar_handler.__name__ = 'do_' + rule setattr(self, grammar_handler.__name__, grammar_handler) - shell = CloudMonkeyShell() + shell = CloudMonkeyShell(sys.argv[0]) if len(sys.argv) > 1: shell.onecmd(' '.join(sys.argv[1:])) else: From a2b2d45e401bd73a2261db461368b030c56f69c8 Mon Sep 17 00:00:00 2001 From: Brian Federle Date: Thu, 24 Jan 2013 13:43:15 -0800 Subject: [PATCH 80/80] Conditionally show select SG step Only show select security group step if at least one guest network with SecurityGroup service is selected. --- ui/scripts/instanceWizard.js | 33 +++++++++++++++++++++++--- ui/scripts/ui-custom/instanceWizard.js | 10 ++++++++ 2 files changed, 40 insertions(+), 3 deletions(-) diff --git a/ui/scripts/instanceWizard.js b/ui/scripts/instanceWizard.js index 8ebee623bf5..070f7e7b98d 100644 --- a/ui/scripts/instanceWizard.js +++ b/ui/scripts/instanceWizard.js @@ -16,7 +16,7 @@ // under the License. (function($, cloudStack) { - var zoneObjs, hypervisorObjs, featuredTemplateObjs, communityTemplateObjs, myTemplateObjs, featuredIsoObjs, community; + var zoneObjs, hypervisorObjs, featuredTemplateObjs, communityTemplateObjs, myTemplateObjs, featuredIsoObjs, community, networkObjs; var selectedZoneObj, selectedTemplateObj, selectedHypervisor, selectedDiskOfferingObj; var step5ContainerType = 'nothing-to-select'; //'nothing-to-select', 'select-network', 'select-security-group' @@ -40,6 +40,33 @@ !data.vpcid; }, + // Runs when advanced SG-enabled zone is run, before + // the security group step + // + // -- if it returns false, then 'Select Security Group' is skipped. + // + advSGFilter: function(args) { + var selectedNetworks; + + if ($.isArray(args.data['my-networks'])) { + selectedNetworks = $(args.data['my-networks']).map(function(index, myNetwork) { + return $.grep(networkObjs, function(networkObj) { + return networkObj.id == myNetwork; + }); + }); + } else { + selectedNetworks = $.grep(networkObjs, function(networkObj) { + return networkObj.id == args.data['my-networks']; + }); + } + + return $.grep(selectedNetworks, function(network) { + return $.grep(network.service, function(service) { + return service.name == 'SecurityGroup'; + }).length; + }).length; + }, + // Data providers for each wizard step steps: [ @@ -347,7 +374,7 @@ networkData.account = g_account; } - var networkObjs, vpcObjs; + var vpcObjs; //listVPCs without account/domainid/listAll parameter will return only VPCs belonging to the current login. That's what should happen in Instances page's VM Wizard. //i.e. If the current login is root-admin, do not show VPCs belonging to regular-user/domain-admin in Instances page's VM Wizard. @@ -365,7 +392,7 @@ async: false, success: function(json) { networkObjs = json.listnetworksresponse.network ? json.listnetworksresponse.network : []; - + if(networkObjs.length > 0) { for(var i = 0; i < networkObjs.length; i++) { var networkObj = networkObjs[i]; diff --git a/ui/scripts/ui-custom/instanceWizard.js b/ui/scripts/ui-custom/instanceWizard.js index d1f2507e120..67d2a69c968 100644 --- a/ui/scripts/ui-custom/instanceWizard.js +++ b/ui/scripts/ui-custom/instanceWizard.js @@ -821,6 +821,16 @@ cloudStack.dialog.notice({ message: 'message.step.4.continue' }); return false; } + + if ($activeStep.hasClass('next-use-security-groups')) { + var advSGFilter = args.advSGFilter({ + data: cloudStack.serializeForm($form) + }); + + if (!advSGFilter) { + showStep(6); + } + } } //step 6 - review (spcifiy displyname, group as well)