diff --git a/api/src/com/cloud/user/AccountService.java b/api/src/com/cloud/user/AccountService.java index ce16f5ee063..9f5f4d225e0 100755 --- a/api/src/com/cloud/user/AccountService.java +++ b/api/src/com/cloud/user/AccountService.java @@ -20,6 +20,7 @@ import java.util.List; import java.util.Map; import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.command.admin.user.DeleteUserCmd; @@ -193,6 +194,8 @@ public interface AccountService { UserAccount getUserByApiKey(String apiKey); + RoleType getRoleType(Account account); + void checkAccess(Account account, Domain domain) throws PermissionDeniedException; void checkAccess(Account account, AccessType accessType, boolean sameOwner, ControlledEntity... entities) throws PermissionDeniedException; diff --git a/api/src/org/apache/cloudstack/acl/RoleType.java b/api/src/org/apache/cloudstack/acl/RoleType.java new file mode 100644 index 00000000000..0d1c4460c1e --- /dev/null +++ b/api/src/org/apache/cloudstack/acl/RoleType.java @@ -0,0 +1,37 @@ +// 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; + +// Enum for default roles in CloudStack +public enum RoleType { + + Admin(1), + ResourceAdmin(2), + DomainAdmin(4), + User(8), + Unknown(0); + + private int mask; + + private RoleType(int mask) { + this.mask = mask; + } + + public int getValue() { + return mask; + } +} diff --git a/client/tomcatconf/api-discovery_commands.properties.in b/client/tomcatconf/api-discovery_commands.properties.in deleted file mode 100644 index 49ddfde42d8..00000000000 --- a/client/tomcatconf/api-discovery_commands.properties.in +++ /dev/null @@ -1,23 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. - -# 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 Discovery service command -listApis=15 diff --git a/plugins/acl/static-role-based/src/org/apache/cloudstack/acl/StaticRoleBasedAPIAccessChecker.java b/plugins/acl/static-role-based/src/org/apache/cloudstack/acl/StaticRoleBasedAPIAccessChecker.java index e0c35a5426a..32de0705f53 100644 --- a/plugins/acl/static-role-based/src/org/apache/cloudstack/acl/StaticRoleBasedAPIAccessChecker.java +++ b/plugins/acl/static-role-based/src/org/apache/cloudstack/acl/StaticRoleBasedAPIAccessChecker.java @@ -16,17 +16,15 @@ // under the License. package org.apache.cloudstack.acl; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Arrays; +import static org.apache.cloudstack.acl.RoleType.Admin; +import static org.apache.cloudstack.acl.RoleType.DomainAdmin; +import static org.apache.cloudstack.acl.RoleType.ResourceAdmin; +import static org.apache.cloudstack.acl.RoleType.User; + +import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; -import java.util.Properties; import java.util.Set; import javax.ejb.Local; @@ -37,7 +35,6 @@ import org.apache.log4j.Logger; import com.cloud.exception.PermissionDeniedException; import com.cloud.user.AccountManager; -import com.cloud.utils.PropertiesUtil; import com.cloud.utils.component.AdapterBase; import com.cloud.utils.component.PluggableService; @@ -70,104 +67,70 @@ public class StaticRoleBasedAPIAccessChecker extends AdapterBase implements APIA } @Override - public boolean canAccessAPI(RoleType roleType, String apiCommandName) - throws PermissionDeniedException{ + public boolean canAccessAPI(RoleType roleType, String commandName) + throws PermissionDeniedException { - boolean commandExists = s_allCommands.contains(apiCommandName); + boolean commandExists = s_allCommands.contains(commandName); + boolean commandAccessible = false; - if(commandExists) { - return isCommandAvailableForAccount(roleType, apiCommandName); + if (commandExists) { + switch (roleType) { + case Admin: + commandAccessible = s_adminCommands.contains(commandName); + break; + case DomainAdmin: + commandAccessible = s_resellerCommands.contains(commandName); + break; + case ResourceAdmin: + commandAccessible = s_resourceDomainAdminCommands.contains(commandName); + break; + case User: + commandAccessible = s_userCommands.contains(commandName); + break; + } } - - return commandExists; - } - - private static boolean isCommandAvailableForAccount(RoleType roleType, String commandName) { - boolean isCommandAvailable = false; - switch (roleType) { - case Admin: - isCommandAvailable = s_adminCommands.contains(commandName); - break; - case DomainAdmin: - isCommandAvailable = s_resellerCommands.contains(commandName); - break; - case ResourceAdmin: - isCommandAvailable = s_resourceDomainAdminCommands.contains(commandName); - break; - case User: - isCommandAvailable = s_userCommands.contains(commandName); - break; - } - return isCommandAvailable; + return commandExists && commandAccessible; } @Override public boolean configure(String name, Map params) throws ConfigurationException { super.configure(name, params); - List configFiles = new ArrayList(); + // Read command properties files to build the static map per role. + Map configPropertiesMap = new HashMap(); for (PluggableService service : _services) { - configFiles.addAll(Arrays.asList(service.getPropertiesFiles())); + configPropertiesMap.putAll(service.getProperties()); } - processConfigFiles(configFiles); + processConfigFiles(configPropertiesMap); return true; } - private void processConfigFiles(List configFiles) { - Properties preProcessedCommands = new Properties(); - - for (String configFile : configFiles) { - File commandsFile = PropertiesUtil.findConfigFile(configFile); - if (commandsFile != null) { - try { - preProcessedCommands.load(new FileInputStream(commandsFile)); - } catch (FileNotFoundException fnfex) { - // in case of a file within a jar in classpath, try to open stream using url - InputStream stream = PropertiesUtil.openStreamFromURL(configFile); - if (stream != null) { - try { - preProcessedCommands.load(stream); - } catch (IOException e) { - s_logger.error("IO Exception, unable to find properties file:", fnfex); - } - } else { - s_logger.error("Unable to find properites file", fnfex); - } - } catch (IOException ioe) { - s_logger.error("IO Exception loading properties file", ioe); - } - } - } - - for (Object key : preProcessedCommands.keySet()) { - String preProcessedCommand = preProcessedCommands.getProperty((String) key); - int splitIndex = preProcessedCommand.lastIndexOf(";"); - // Backward compatible to old style, apiname=pkg;mask - String mask = preProcessedCommand.substring(splitIndex+1); - + private void processConfigFiles(Map config) { + for (Map.Entry entry: config.entrySet()) { + String apiName = entry.getKey(); + String roleMask = entry.getValue(); try { - short cmdPermissions = Short.parseShort(mask); + short cmdPermissions = Short.parseShort(roleMask); if ((cmdPermissions & Admin.getValue()) != 0) { - s_adminCommands.add((String) key); + s_adminCommands.add(apiName); } if ((cmdPermissions & ResourceAdmin.getValue()) != 0) { - s_resourceDomainAdminCommands.add((String) key); + s_resourceDomainAdminCommands.add(apiName); } if ((cmdPermissions & DomainAdmin.getValue()) != 0) { - s_resellerCommands.add((String) key); + s_resellerCommands.add(apiName); } if ((cmdPermissions & User.getValue()) != 0) { - s_userCommands.add((String) key); + s_userCommands.add(apiName); } - s_allCommands.addAll(s_adminCommands); - s_allCommands.addAll(s_resourceDomainAdminCommands); - s_allCommands.addAll(s_userCommands); - s_allCommands.addAll(s_resellerCommands); } catch (NumberFormatException nfe) { - s_logger.info("Malformed command.properties permissions value, key = " + key + ", value = " + preProcessedCommand); + s_logger.info("Malformed commands.properties permissions value, for entry: " + entry.toString()); } } + s_allCommands.addAll(s_adminCommands); + s_allCommands.addAll(s_resourceDomainAdminCommands); + s_allCommands.addAll(s_userCommands); + s_allCommands.addAll(s_resellerCommands); } - } 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 dcbaec1d160..feab20ac5cf 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 @@ -16,6 +16,9 @@ // under the License. package org.apache.cloudstack.api.command.user.discovery; +import com.cloud.user.Account; +import com.cloud.user.UserContext; +import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.BaseListCmd; @@ -39,7 +42,9 @@ public class ListApisCmd extends BaseListCmd { @Override public void execute() throws ServerApiException { if (_apiDiscoveryService != null) { - ListResponse response = (ListResponse) _apiDiscoveryService.listApis(); + Account caller = UserContext.current().getCaller(); + RoleType roleType = _accountService.getRoleType(UserContext.current().getCaller()); + ListResponse response = (ListResponse) _apiDiscoveryService.listApis(roleType); if (response == null) { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Api Discovery plugin was unable to find and process any apis"); } diff --git a/plugins/api/discovery/src/org/apache/cloudstack/discovery/ApiDiscoveryService.java b/plugins/api/discovery/src/org/apache/cloudstack/discovery/ApiDiscoveryService.java index 96ea3ee4d34..a1d440e9ccf 100644 --- a/plugins/api/discovery/src/org/apache/cloudstack/discovery/ApiDiscoveryService.java +++ b/plugins/api/discovery/src/org/apache/cloudstack/discovery/ApiDiscoveryService.java @@ -17,9 +17,10 @@ package org.apache.cloudstack.discovery; import com.cloud.utils.component.PluggableService; +import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.api.BaseResponse; import org.apache.cloudstack.api.response.ListResponse; public interface ApiDiscoveryService extends PluggableService { - ListResponse listApis(); + ListResponse listApis(RoleType roleType); } 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 ea6b206fa44..2bc17bdbf4d 100644 --- a/plugins/api/discovery/src/org/apache/cloudstack/discovery/ApiDiscoveryServiceImpl.java +++ b/plugins/api/discovery/src/org/apache/cloudstack/discovery/ApiDiscoveryServiceImpl.java @@ -16,7 +16,9 @@ // under the License. package org.apache.cloudstack.discovery; +import com.cloud.utils.PropertiesUtil; import com.cloud.utils.ReflectUtil; +import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.BaseAsyncCmd; @@ -108,12 +110,14 @@ public class ApiDiscoveryServiceImpl implements ApiDiscoveryService { } @Override - public ListResponse listApis() { + public ListResponse listApis(RoleType roleType) { return _discoveryResponse; } @Override - public String[] getPropertiesFiles() { - return new String[] { "api-discovery_commands.properties" }; + public Map getProperties() { + Map apiDiscoveryPropertyMap = new HashMap(); + apiDiscoveryPropertyMap.put("listApis", "15"); + return apiDiscoveryPropertyMap; } } diff --git a/plugins/hypervisors/simulator/src/com/cloud/server/ManagementServerSimulatorImpl.java b/plugins/hypervisors/simulator/src/com/cloud/server/ManagementServerSimulatorImpl.java index ad42c23380e..44ab26a020a 100644 --- a/plugins/hypervisors/simulator/src/com/cloud/server/ManagementServerSimulatorImpl.java +++ b/plugins/hypervisors/simulator/src/com/cloud/server/ManagementServerSimulatorImpl.java @@ -17,16 +17,16 @@ package com.cloud.server; +import com.cloud.utils.PropertiesUtil; + +import java.util.Map; + public class ManagementServerSimulatorImpl extends ManagementServerExtImpl { @Override - public String[] getPropertiesFiles() { - String[] apis = super.getPropertiesFiles(); - String[] newapis = new String[apis.length + 1]; - for (int i = 0; i < apis.length; i++) { - newapis[i] = apis[i]; - } - - newapis[apis.length] = "commands-simulator.properties"; - return newapis; + public Map getProperties() { + Map apiNameRoleMaskMapping = super.getProperties(); + apiNameRoleMaskMapping.putAll(PropertiesUtil.processConfigFile(new String[] + {"commands-simulator.properties"})); + return apiNameRoleMaskMapping; } } diff --git a/plugins/hypervisors/vmware/src/com/cloud/network/element/CiscoNexusVSMElement.java b/plugins/hypervisors/vmware/src/com/cloud/network/element/CiscoNexusVSMElement.java index 71683dc306a..f6a812deca4 100644 --- a/plugins/hypervisors/vmware/src/com/cloud/network/element/CiscoNexusVSMElement.java +++ b/plugins/hypervisors/vmware/src/com/cloud/network/element/CiscoNexusVSMElement.java @@ -17,6 +17,7 @@ package com.cloud.network.element; +import java.lang.String; import java.util.List; import java.util.Map; import java.util.ArrayList; @@ -25,6 +26,7 @@ import java.util.Set; import javax.ejb.Local; import javax.inject.Inject; +import com.cloud.utils.PropertiesUtil; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; @@ -239,7 +241,8 @@ public class CiscoNexusVSMElement extends CiscoNexusVSMDeviceManagerImpl impleme } @Override - public String[] getPropertiesFiles() { - return new String[] { "cisconexusvsm_commands.properties" }; + public Map getProperties() { + return PropertiesUtil.processConfigFile(new String[] + { "cisconexusvsm_commands.properties" }); } } diff --git a/plugins/network-elements/f5/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java b/plugins/network-elements/f5/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java index 8c01d5f5f7f..177302660b5 100644 --- a/plugins/network-elements/f5/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java +++ b/plugins/network-elements/f5/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java @@ -16,6 +16,7 @@ // under the License. package com.cloud.network.element; +import java.lang.String; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -25,6 +26,7 @@ import java.util.Set; import javax.ejb.Local; import javax.inject.Inject; +import com.cloud.utils.PropertiesUtil; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; @@ -262,8 +264,9 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan } @Override - public String[] getPropertiesFiles() { - return new String[] { "f5bigip_commands.properties" }; + public Map getProperties() { + return PropertiesUtil.processConfigFile(new String[] + { "f5bigip_commands.properties" }); } @Override diff --git a/plugins/network-elements/juniper-srx/src/com/cloud/network/element/JuniperSRXExternalFirewallElement.java b/plugins/network-elements/juniper-srx/src/com/cloud/network/element/JuniperSRXExternalFirewallElement.java index 93d3fb7a71f..63781bb2339 100644 --- a/plugins/network-elements/juniper-srx/src/com/cloud/network/element/JuniperSRXExternalFirewallElement.java +++ b/plugins/network-elements/juniper-srx/src/com/cloud/network/element/JuniperSRXExternalFirewallElement.java @@ -16,6 +16,7 @@ // under the License. package com.cloud.network.element; +import java.lang.String; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -25,6 +26,7 @@ import java.util.Set; import javax.ejb.Local; import javax.inject.Inject; +import com.cloud.utils.PropertiesUtil; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; @@ -404,8 +406,9 @@ public class JuniperSRXExternalFirewallElement extends ExternalFirewallDeviceMan } @Override - public String[] getPropertiesFiles() { - return new String[] { "junipersrx_commands.properties"}; + public Map getProperties() { + return PropertiesUtil.processConfigFile(new String[] + { "junipersrx_commands.properties"}); } @Override diff --git a/plugins/network-elements/netscaler/src/com/cloud/network/element/NetscalerElement.java b/plugins/network-elements/netscaler/src/com/cloud/network/element/NetscalerElement.java index 19907061f1b..faff153084c 100644 --- a/plugins/network-elements/netscaler/src/com/cloud/network/element/NetscalerElement.java +++ b/plugins/network-elements/netscaler/src/com/cloud/network/element/NetscalerElement.java @@ -27,6 +27,7 @@ import java.util.Set; import javax.ejb.Local; import javax.inject.Inject; +import com.cloud.utils.PropertiesUtil; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; @@ -466,8 +467,9 @@ StaticNatServiceProvider { } @Override - public String[] getPropertiesFiles() { - return new String[] { "netscalerloadbalancer_commands.properties" }; + public Map getProperties() { + return PropertiesUtil.processConfigFile(new String[] + { "netscalerloadbalancer_commands.properties" }); } @Override diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/element/NiciraNvpElement.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/element/NiciraNvpElement.java index 78fa0832518..36d4580ccb8 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/element/NiciraNvpElement.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/element/NiciraNvpElement.java @@ -28,6 +28,7 @@ import javax.ejb.Local; import javax.inject.Inject; import javax.naming.ConfigurationException; +import org.apache.cloudstack.network.ExternalNetworkDeviceManager.NetworkDevice; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; @@ -72,16 +73,15 @@ import com.cloud.host.Host; import com.cloud.host.HostVO; import com.cloud.host.dao.HostDao; import com.cloud.host.dao.HostDetailsDao; +import com.cloud.network.IpAddress; import com.cloud.network.Network; -import org.apache.cloudstack.network.ExternalNetworkDeviceManager.NetworkDevice; import com.cloud.network.Network.Capability; import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; +import com.cloud.network.NetworkManager; import com.cloud.network.NetworkVO; import com.cloud.network.Networks; import com.cloud.network.Networks.BroadcastDomainType; -import com.cloud.network.IpAddress; -import com.cloud.network.NetworkManager; import com.cloud.network.NiciraNvpDeviceVO; import com.cloud.network.NiciraNvpNicMappingVO; import com.cloud.network.NiciraNvpRouterMappingVO; @@ -108,6 +108,7 @@ import com.cloud.resource.ResourceStateAdapter; import com.cloud.resource.ServerResource; import com.cloud.resource.UnableDeleteHostException; import com.cloud.user.Account; +import com.cloud.utils.PropertiesUtil; import com.cloud.utils.component.AdapterBase; import com.cloud.utils.db.DB; import com.cloud.utils.db.Transaction; @@ -123,14 +124,14 @@ import com.cloud.vm.dao.NicDao; @Component @Local(value = NetworkElement.class) public class NiciraNvpElement extends AdapterBase implements - ConnectivityProvider, SourceNatServiceProvider, - PortForwardingServiceProvider, StaticNatServiceProvider, - NiciraNvpElementService, ResourceStateAdapter, IpDeployer { - private static final Logger s_logger = Logger - .getLogger(NiciraNvpElement.class); - +ConnectivityProvider, SourceNatServiceProvider, +PortForwardingServiceProvider, StaticNatServiceProvider, +NiciraNvpElementService, ResourceStateAdapter, IpDeployer { + private static final Logger s_logger = Logger + .getLogger(NiciraNvpElement.class); + private static final Map> capabilities = setCapabilities(); - + @Inject NicDao _nicDao; @Inject @@ -150,18 +151,18 @@ public class NiciraNvpElement extends AdapterBase implements @Inject NiciraNvpNicMappingDao _niciraNvpNicMappingDao; @Inject - NiciraNvpRouterMappingDao _niciraNvpRouterMappingDao; - @Inject + NiciraNvpRouterMappingDao _niciraNvpRouterMappingDao; + @Inject NetworkDao _networkDao; - @Inject - NetworkManager _networkManager; - @Inject - ConfigurationManager _configMgr; - @Inject - NetworkServiceMapDao _ntwkSrvcDao; - @Inject - VlanDao _vlanDao; - + @Inject + NetworkManager _networkManager; + @Inject + ConfigurationManager _configMgr; + @Inject + NetworkServiceMapDao _ntwkSrvcDao; + @Inject + VlanDao _vlanDao; + @Override public Map> getCapabilities() { return capabilities; @@ -171,130 +172,130 @@ public class NiciraNvpElement extends AdapterBase implements public Provider getProvider() { return Provider.NiciraNvp; } - - protected boolean canHandle(Network network, Service service) { - s_logger.debug("Checking if NiciraNvpElement can handle service " - + service.getName() + " on network " + network.getDisplayText()); + + protected boolean canHandle(Network network, Service service) { + s_logger.debug("Checking if NiciraNvpElement can handle service " + + service.getName() + " on network " + network.getDisplayText()); if (network.getBroadcastDomainType() != BroadcastDomainType.Lswitch) { return false; } - - if (!_networkManager.isProviderForNetwork(getProvider(), - network.getId())) { - s_logger.debug("NiciraNvpElement is not a provider for network " - + network.getDisplayText()); - return false; - } - if (!_ntwkSrvcDao.canProviderSupportServiceInNetwork(network.getId(), - service, Network.Provider.NiciraNvp)) { - s_logger.debug("NiciraNvpElement can't provide the " - + service.getName() + " service on network " - + network.getDisplayText()); - return false; - } + if (!_networkManager.isProviderForNetwork(getProvider(), + network.getId())) { + s_logger.debug("NiciraNvpElement is not a provider for network " + + network.getDisplayText()); + return false; + } + + if (!_ntwkSrvcDao.canProviderSupportServiceInNetwork(network.getId(), + service, Network.Provider.NiciraNvp)) { + s_logger.debug("NiciraNvpElement can't provide the " + + service.getName() + " service on network " + + network.getDisplayText()); + return false; + } return true; } - + @Override public boolean configure(String name, Map params) throws ConfigurationException { super.configure(name, params); - _resourceMgr.registerResourceStateAdapter(this.getClass() - .getSimpleName(), this); + _resourceMgr.registerResourceStateAdapter(this.getClass() + .getSimpleName(), this); return true; } @Override public boolean implement(Network network, NetworkOffering offering, DeployDestination dest, ReservationContext context) - throws ConcurrentOperationException, ResourceUnavailableException, - InsufficientCapacityException { - s_logger.debug("entering NiciraNvpElement implement function for network " - + network.getDisplayText() - + " (state " - + network.getState() - + ")"); + throws ConcurrentOperationException, ResourceUnavailableException, + InsufficientCapacityException { + s_logger.debug("entering NiciraNvpElement implement function for network " + + network.getDisplayText() + + " (state " + + network.getState() + + ")"); - if (!canHandle(network, Service.Connectivity)) { - return false; - } - - if (network.getBroadcastUri() == null) { - s_logger.error("Nic has no broadcast Uri with the LSwitch Uuid"); + if (!canHandle(network, Service.Connectivity)) { return false; } - - List devices = _niciraNvpDao - .listByPhysicalNetwork(network.getPhysicalNetworkId()); - if (devices.isEmpty()) { - s_logger.error("No NiciraNvp Controller on physical network " - + network.getPhysicalNetworkId()); - return false; - } - NiciraNvpDeviceVO niciraNvpDevice = devices.get(0); - HostVO niciraNvpHost = _hostDao.findById(niciraNvpDevice.getHostId()); - _hostDao.loadDetails(niciraNvpHost); - Account owner = context.getAccount(); + if (network.getBroadcastUri() == null) { + s_logger.error("Nic has no broadcast Uri with the LSwitch Uuid"); + return false; + } - /** - * Lock the network as we might need to do multiple operations that - * should be done only once. - */ - Network lock = _networkDao.acquireInLockTable(network.getId(), - _networkManager.getNetworkLockTimeout()); - if (lock == null) { - throw new ConcurrentOperationException("Unable to lock network " - + network.getId()); - } - try { - // Implement SourceNat immediately as we have al the info already - if (_networkManager.isProviderSupportServiceInNetwork( - network.getId(), Service.SourceNat, Provider.NiciraNvp)) { - s_logger.debug("Apparently we are supposed to provide SourceNat on this network"); + List devices = _niciraNvpDao + .listByPhysicalNetwork(network.getPhysicalNetworkId()); + if (devices.isEmpty()) { + s_logger.error("No NiciraNvp Controller on physical network " + + network.getPhysicalNetworkId()); + return false; + } + NiciraNvpDeviceVO niciraNvpDevice = devices.get(0); + HostVO niciraNvpHost = _hostDao.findById(niciraNvpDevice.getHostId()); + _hostDao.loadDetails(niciraNvpHost); - PublicIp sourceNatIp = _networkManager - .assignSourceNatIpAddressToGuestNetwork(owner, network); - String publicCidr = sourceNatIp.getAddress().addr() + "/" - + NetUtils.getCidrSize(sourceNatIp.getVlanNetmask()); - String internalCidr = network.getGateway() + "/" - + network.getCidr().split("/")[1]; - long vlanid = (Vlan.UNTAGGED.equals(sourceNatIp.getVlanTag())) ? 0 - : Long.parseLong(sourceNatIp.getVlanTag()); + Account owner = context.getAccount(); - CreateLogicalRouterCommand cmd = new CreateLogicalRouterCommand( - niciraNvpHost.getDetail("l3gatewayserviceuuid"), vlanid, - network.getBroadcastUri().getSchemeSpecificPart(), - "router-" + network.getDisplayText(), publicCidr, - sourceNatIp.getGateway(), internalCidr, context - .getDomain().getName() - + "-" - + context.getAccount().getAccountName()); - CreateLogicalRouterAnswer answer = (CreateLogicalRouterAnswer) _agentMgr - .easySend(niciraNvpHost.getId(), cmd); - if (answer.getResult() == false) { - s_logger.error("Failed to create Logical Router for network " - + network.getDisplayText()); - return false; - } + /** + * Lock the network as we might need to do multiple operations that + * should be done only once. + */ + Network lock = _networkDao.acquireInLockTable(network.getId(), + _networkManager.getNetworkLockTimeout()); + if (lock == null) { + throw new ConcurrentOperationException("Unable to lock network " + + network.getId()); + } + try { + // Implement SourceNat immediately as we have al the info already + if (_networkManager.isProviderSupportServiceInNetwork( + network.getId(), Service.SourceNat, Provider.NiciraNvp)) { + s_logger.debug("Apparently we are supposed to provide SourceNat on this network"); - // Store the uuid so we can easily find it during cleanup - NiciraNvpRouterMappingVO routermapping = - new NiciraNvpRouterMappingVO(answer.getLogicalRouterUuid(), network.getId()); - _niciraNvpRouterMappingDao.persist(routermapping); - } - } finally { - if (lock != null) { - _networkDao.releaseFromLockTable(lock.getId()); - if (s_logger.isDebugEnabled()) { - s_logger.debug("Lock is released for network id " - + lock.getId() + " as a part of router startup in " - + dest); - } - } - } + PublicIp sourceNatIp = _networkManager + .assignSourceNatIpAddressToGuestNetwork(owner, network); + String publicCidr = sourceNatIp.getAddress().addr() + "/" + + NetUtils.getCidrSize(sourceNatIp.getVlanNetmask()); + String internalCidr = network.getGateway() + "/" + + network.getCidr().split("/")[1]; + long vlanid = (Vlan.UNTAGGED.equals(sourceNatIp.getVlanTag())) ? 0 + : Long.parseLong(sourceNatIp.getVlanTag()); + + CreateLogicalRouterCommand cmd = new CreateLogicalRouterCommand( + niciraNvpHost.getDetail("l3gatewayserviceuuid"), vlanid, + network.getBroadcastUri().getSchemeSpecificPart(), + "router-" + network.getDisplayText(), publicCidr, + sourceNatIp.getGateway(), internalCidr, context + .getDomain().getName() + + "-" + + context.getAccount().getAccountName()); + CreateLogicalRouterAnswer answer = (CreateLogicalRouterAnswer) _agentMgr + .easySend(niciraNvpHost.getId(), cmd); + if (answer.getResult() == false) { + s_logger.error("Failed to create Logical Router for network " + + network.getDisplayText()); + return false; + } + + // Store the uuid so we can easily find it during cleanup + NiciraNvpRouterMappingVO routermapping = + new NiciraNvpRouterMappingVO(answer.getLogicalRouterUuid(), network.getId()); + _niciraNvpRouterMappingDao.persist(routermapping); + } + } finally { + if (lock != null) { + _networkDao.releaseFromLockTable(lock.getId()); + if (s_logger.isDebugEnabled()) { + s_logger.debug("Lock is released for network id " + + lock.getId() + " as a part of router startup in " + + dest); + } + } + } return true; } @@ -302,10 +303,10 @@ public class NiciraNvpElement extends AdapterBase implements public boolean prepare(Network network, NicProfile nic, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) - throws ConcurrentOperationException, ResourceUnavailableException, - InsufficientCapacityException { - - if (!canHandle(network, Service.Connectivity)) { + throws ConcurrentOperationException, ResourceUnavailableException, + InsufficientCapacityException { + + if (!canHandle(network, Service.Connectivity)) { return false; } @@ -316,60 +317,60 @@ public class NiciraNvpElement extends AdapterBase implements NicVO nicVO = _nicDao.findById(nic.getId()); - List devices = _niciraNvpDao - .listByPhysicalNetwork(network.getPhysicalNetworkId()); + List devices = _niciraNvpDao + .listByPhysicalNetwork(network.getPhysicalNetworkId()); if (devices.isEmpty()) { - s_logger.error("No NiciraNvp Controller on physical network " - + network.getPhysicalNetworkId()); + s_logger.error("No NiciraNvp Controller on physical network " + + network.getPhysicalNetworkId()); return false; } NiciraNvpDeviceVO niciraNvpDevice = devices.get(0); HostVO niciraNvpHost = _hostDao.findById(niciraNvpDevice.getHostId()); - NiciraNvpNicMappingVO existingNicMap = _niciraNvpNicMappingDao - .findByNicUuid(nicVO.getUuid()); + NiciraNvpNicMappingVO existingNicMap = _niciraNvpNicMappingDao + .findByNicUuid(nicVO.getUuid()); if (existingNicMap != null) { - FindLogicalSwitchPortCommand findCmd = new FindLogicalSwitchPortCommand( - existingNicMap.getLogicalSwitchUuid(), - existingNicMap.getLogicalSwitchPortUuid()); - FindLogicalSwitchPortAnswer answer = (FindLogicalSwitchPortAnswer) _agentMgr - .easySend(niciraNvpHost.getId(), findCmd); - + FindLogicalSwitchPortCommand findCmd = new FindLogicalSwitchPortCommand( + existingNicMap.getLogicalSwitchUuid(), + existingNicMap.getLogicalSwitchPortUuid()); + FindLogicalSwitchPortAnswer answer = (FindLogicalSwitchPortAnswer) _agentMgr + .easySend(niciraNvpHost.getId(), findCmd); + if (answer.getResult()) { - s_logger.warn("Existing Logical Switchport found for nic " - + nic.getName() + " with uuid " - + existingNicMap.getLogicalSwitchPortUuid()); - UpdateLogicalSwitchPortCommand cmd = new UpdateLogicalSwitchPortCommand( - existingNicMap.getLogicalSwitchPortUuid(), network - .getBroadcastUri().getSchemeSpecificPart(), - nicVO.getUuid(), context.getDomain().getName() + "-" - + context.getAccount().getAccountName(), - nic.getName()); - _agentMgr.easySend(niciraNvpHost.getId(), cmd); - return true; - } else { - s_logger.error("Stale entry found for nic " + nic.getName() - + " with logical switchport uuid " - + existingNicMap.getLogicalSwitchPortUuid()); - _niciraNvpNicMappingDao.remove(existingNicMap.getId()); + s_logger.warn("Existing Logical Switchport found for nic " + + nic.getName() + " with uuid " + + existingNicMap.getLogicalSwitchPortUuid()); + UpdateLogicalSwitchPortCommand cmd = new UpdateLogicalSwitchPortCommand( + existingNicMap.getLogicalSwitchPortUuid(), network + .getBroadcastUri().getSchemeSpecificPart(), + nicVO.getUuid(), context.getDomain().getName() + "-" + + context.getAccount().getAccountName(), + nic.getName()); + _agentMgr.easySend(niciraNvpHost.getId(), cmd); + return true; + } else { + s_logger.error("Stale entry found for nic " + nic.getName() + + " with logical switchport uuid " + + existingNicMap.getLogicalSwitchPortUuid()); + _niciraNvpNicMappingDao.remove(existingNicMap.getId()); } } - - CreateLogicalSwitchPortCommand cmd = new CreateLogicalSwitchPortCommand( - network.getBroadcastUri().getSchemeSpecificPart(), - nicVO.getUuid(), context.getDomain().getName() + "-" - + context.getAccount().getAccountName(), nic.getName()); - CreateLogicalSwitchPortAnswer answer = (CreateLogicalSwitchPortAnswer) _agentMgr - .easySend(niciraNvpHost.getId(), cmd); - + + CreateLogicalSwitchPortCommand cmd = new CreateLogicalSwitchPortCommand( + network.getBroadcastUri().getSchemeSpecificPart(), + nicVO.getUuid(), context.getDomain().getName() + "-" + + context.getAccount().getAccountName(), nic.getName()); + CreateLogicalSwitchPortAnswer answer = (CreateLogicalSwitchPortAnswer) _agentMgr + .easySend(niciraNvpHost.getId(), cmd); + if (answer == null || !answer.getResult()) { - s_logger.error("CreateLogicalSwitchPortCommand failed"); + s_logger.error("CreateLogicalSwitchPortCommand failed"); return false; } - - NiciraNvpNicMappingVO nicMap = new NiciraNvpNicMappingVO(network - .getBroadcastUri().getSchemeSpecificPart(), - answer.getLogicalSwitchPortUuid(), nicVO.getUuid()); + + NiciraNvpNicMappingVO nicMap = new NiciraNvpNicMappingVO(network + .getBroadcastUri().getSchemeSpecificPart(), + answer.getLogicalSwitchPortUuid(), nicVO.getUuid()); _niciraNvpNicMappingDao.persist(nicMap); return true; @@ -381,7 +382,7 @@ public class NiciraNvpElement extends AdapterBase implements ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException { - if (!canHandle(network, Service.Connectivity)) { + if (!canHandle(network, Service.Connectivity)) { return false; } @@ -389,39 +390,39 @@ public class NiciraNvpElement extends AdapterBase implements s_logger.error("Nic has no broadcast Uri with the LSwitch Uuid"); return false; } - + NicVO nicVO = _nicDao.findById(nic.getId()); - List devices = _niciraNvpDao - .listByPhysicalNetwork(network.getPhysicalNetworkId()); + List devices = _niciraNvpDao + .listByPhysicalNetwork(network.getPhysicalNetworkId()); if (devices.isEmpty()) { - s_logger.error("No NiciraNvp Controller on physical network " - + network.getPhysicalNetworkId()); + s_logger.error("No NiciraNvp Controller on physical network " + + network.getPhysicalNetworkId()); return false; } NiciraNvpDeviceVO niciraNvpDevice = devices.get(0); HostVO niciraNvpHost = _hostDao.findById(niciraNvpDevice.getHostId()); - - NiciraNvpNicMappingVO nicMap = _niciraNvpNicMappingDao - .findByNicUuid(nicVO.getUuid()); + + NiciraNvpNicMappingVO nicMap = _niciraNvpNicMappingDao + .findByNicUuid(nicVO.getUuid()); if (nicMap == null) { s_logger.error("No mapping for nic " + nic.getName()); return false; } - - DeleteLogicalSwitchPortCommand cmd = new DeleteLogicalSwitchPortCommand( - nicMap.getLogicalSwitchUuid(), - nicMap.getLogicalSwitchPortUuid()); - DeleteLogicalSwitchPortAnswer answer = (DeleteLogicalSwitchPortAnswer) _agentMgr - .easySend(niciraNvpHost.getId(), cmd); - + + DeleteLogicalSwitchPortCommand cmd = new DeleteLogicalSwitchPortCommand( + nicMap.getLogicalSwitchUuid(), + nicMap.getLogicalSwitchPortUuid()); + DeleteLogicalSwitchPortAnswer answer = (DeleteLogicalSwitchPortAnswer) _agentMgr + .easySend(niciraNvpHost.getId(), cmd); + if (answer == null || !answer.getResult()) { - s_logger.error("DeleteLogicalSwitchPortCommand failed"); + s_logger.error("DeleteLogicalSwitchPortCommand failed"); return false; } - + _niciraNvpNicMappingDao.remove(nicMap.getId()); - + return true; } @@ -429,54 +430,54 @@ public class NiciraNvpElement extends AdapterBase implements public boolean shutdown(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException { - if (!canHandle(network, Service.Connectivity)) { - return false; - } - - List devices = _niciraNvpDao - .listByPhysicalNetwork(network.getPhysicalNetworkId()); - if (devices.isEmpty()) { - s_logger.error("No NiciraNvp Controller on physical network " - + network.getPhysicalNetworkId()); - return false; - } - NiciraNvpDeviceVO niciraNvpDevice = devices.get(0); - HostVO niciraNvpHost = _hostDao.findById(niciraNvpDevice.getHostId()); - - if (_networkManager.isProviderSupportServiceInNetwork(network.getId(), - Service.SourceNat, Provider.NiciraNvp)) { - s_logger.debug("Apparently we were providing SourceNat on this network"); - - // Deleting the LogicalRouter will also take care of all provisioned - // nat rules. - NiciraNvpRouterMappingVO routermapping = _niciraNvpRouterMappingDao - .findByNetworkId(network.getId()); - if (routermapping == null) { - s_logger.warn("No logical router uuid found for network " - + network.getDisplayText()); - // This might be cause by a failed deployment, so don't make shutdown fail as well. - return true; - } - - DeleteLogicalRouterCommand cmd = new DeleteLogicalRouterCommand(routermapping.getLogicalRouterUuid()); - DeleteLogicalRouterAnswer answer = - (DeleteLogicalRouterAnswer) _agentMgr.easySend(niciraNvpHost.getId(), cmd); - if (answer.getResult() == false) { - s_logger.error("Failed to delete LogicalRouter for network " - + network.getDisplayText()); + if (!canHandle(network, Service.Connectivity)) { return false; } - _niciraNvpRouterMappingDao.remove(routermapping.getId()); - } + List devices = _niciraNvpDao + .listByPhysicalNetwork(network.getPhysicalNetworkId()); + if (devices.isEmpty()) { + s_logger.error("No NiciraNvp Controller on physical network " + + network.getPhysicalNetworkId()); + return false; + } + NiciraNvpDeviceVO niciraNvpDevice = devices.get(0); + HostVO niciraNvpHost = _hostDao.findById(niciraNvpDevice.getHostId()); + + if (_networkManager.isProviderSupportServiceInNetwork(network.getId(), + Service.SourceNat, Provider.NiciraNvp)) { + s_logger.debug("Apparently we were providing SourceNat on this network"); + + // Deleting the LogicalRouter will also take care of all provisioned + // nat rules. + NiciraNvpRouterMappingVO routermapping = _niciraNvpRouterMappingDao + .findByNetworkId(network.getId()); + if (routermapping == null) { + s_logger.warn("No logical router uuid found for network " + + network.getDisplayText()); + // This might be cause by a failed deployment, so don't make shutdown fail as well. + return true; + } + + DeleteLogicalRouterCommand cmd = new DeleteLogicalRouterCommand(routermapping.getLogicalRouterUuid()); + DeleteLogicalRouterAnswer answer = + (DeleteLogicalRouterAnswer) _agentMgr.easySend(niciraNvpHost.getId(), cmd); + if (answer.getResult() == false) { + s_logger.error("Failed to delete LogicalRouter for network " + + network.getDisplayText()); + return false; + } + + _niciraNvpRouterMappingDao.remove(routermapping.getId()); + } return true; } @Override - public boolean destroy(Network network, ReservationContext context) + public boolean destroy(Network network, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException { - if (!canHandle(network, Service.Connectivity)) { + if (!canHandle(network, Service.Connectivity)) { return false; } @@ -491,59 +492,60 @@ public class NiciraNvpElement extends AdapterBase implements @Override public boolean shutdownProviderInstances( PhysicalNetworkServiceProvider provider, ReservationContext context) - throws ConcurrentOperationException, ResourceUnavailableException { + throws ConcurrentOperationException, ResourceUnavailableException { // Nothing to do here. return true; } @Override public boolean canEnableIndividualServices() { - return true; + return true; } @Override public boolean verifyServicesCombination(Set services) { - // This element can only function in a Nicra Nvp based - // SDN network, so Connectivity needs to be present here - if (!services.contains(Service.Connectivity)) { - s_logger.warn("Unable to provide services without Connectivity service enabled for this element"); - return false; - } - if ((services.contains(Service.PortForwarding) || services.contains(Service.StaticNat)) && !services.contains(Service.SourceNat)) { - s_logger.warn("Unable to provide StaticNat and/or PortForwarding without the SourceNat service"); - return false; - } + // This element can only function in a Nicra Nvp based + // SDN network, so Connectivity needs to be present here + if (!services.contains(Service.Connectivity)) { + s_logger.warn("Unable to provide services without Connectivity service enabled for this element"); + return false; + } + if ((services.contains(Service.PortForwarding) || services.contains(Service.StaticNat)) && !services.contains(Service.SourceNat)) { + s_logger.warn("Unable to provide StaticNat and/or PortForwarding without the SourceNat service"); + return false; + } return true; } private static Map> setCapabilities() { Map> capabilities = new HashMap>(); - // L2 Support : SDN provisioning + // L2 Support : SDN provisioning capabilities.put(Service.Connectivity, null); - // L3 Support : Generic? - capabilities.put(Service.Gateway, null); + // L3 Support : Generic? + capabilities.put(Service.Gateway, null); - // L3 Support : SourceNat - Map sourceNatCapabilities = new HashMap(); - sourceNatCapabilities.put(Capability.SupportedSourceNatTypes, - "peraccount"); - sourceNatCapabilities.put(Capability.RedundantRouter, "false"); - capabilities.put(Service.SourceNat, sourceNatCapabilities); + // L3 Support : SourceNat + Map sourceNatCapabilities = new HashMap(); + sourceNatCapabilities.put(Capability.SupportedSourceNatTypes, + "peraccount"); + sourceNatCapabilities.put(Capability.RedundantRouter, "false"); + capabilities.put(Service.SourceNat, sourceNatCapabilities); - // L3 Support : Port Forwarding - capabilities.put(Service.PortForwarding, null); + // L3 Support : Port Forwarding + capabilities.put(Service.PortForwarding, null); - // L3 support : StaticNat - capabilities.put(Service.StaticNat, null); + // L3 support : StaticNat + capabilities.put(Service.StaticNat, null); return capabilities; } @Override - public String[] getPropertiesFiles() { - return new String[] { "nicira-nvp_commands.properties" }; + public Map getProperties() { + return PropertiesUtil.processConfigFile(new String[] + { "nicira-nvp_commands.properties" }); } @Override @@ -551,41 +553,41 @@ public class NiciraNvpElement extends AdapterBase implements public NiciraNvpDeviceVO addNiciraNvpDevice(AddNiciraNvpDeviceCmd cmd) { ServerResource resource = new NiciraNvpResource(); String deviceName = Network.Provider.NiciraNvp.getName(); - NetworkDevice networkDevice = NetworkDevice - .getNetworkDevice(deviceName); + NetworkDevice networkDevice = NetworkDevice + .getNetworkDevice(deviceName); Long physicalNetworkId = cmd.getPhysicalNetworkId(); NiciraNvpDeviceVO niciraNvpDevice = null; - - PhysicalNetworkVO physicalNetwork = _physicalNetworkDao - .findById(physicalNetworkId); + + PhysicalNetworkVO physicalNetwork = _physicalNetworkDao + .findById(physicalNetworkId); if (physicalNetwork == null) { - throw new InvalidParameterValueException( - "Could not find phyical network with ID: " - + physicalNetworkId); + throw new InvalidParameterValueException( + "Could not find phyical network with ID: " + + physicalNetworkId); } long zoneId = physicalNetwork.getDataCenterId(); - PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao - .findByServiceProvider(physicalNetwork.getId(), - networkDevice.getNetworkServiceProvder()); + PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao + .findByServiceProvider(physicalNetwork.getId(), + networkDevice.getNetworkServiceProvder()); if (ntwkSvcProvider == null) { - throw new CloudRuntimeException("Network Service Provider: " - + networkDevice.getNetworkServiceProvder() - + " is not enabled in the physical network: " - + physicalNetworkId + "to add this device"); + throw new CloudRuntimeException("Network Service Provider: " + + networkDevice.getNetworkServiceProvder() + + " is not enabled in the physical network: " + + physicalNetworkId + "to add this device"); } else if (ntwkSvcProvider.getState() == PhysicalNetworkServiceProvider.State.Shutdown) { - throw new CloudRuntimeException("Network Service Provider: " - + ntwkSvcProvider.getProviderName() - + " is in shutdown state in the physical network: " - + physicalNetworkId + "to add this device"); + throw new CloudRuntimeException("Network Service Provider: " + + ntwkSvcProvider.getProviderName() + + " is in shutdown state in the physical network: " + + physicalNetworkId + "to add this device"); } - + if (_niciraNvpDao.listByPhysicalNetwork(physicalNetworkId).size() != 0) { - throw new CloudRuntimeException( - "A NiciraNvp device is already configured on this physical network"); + throw new CloudRuntimeException( + "A NiciraNvp device is already configured on this physical network"); } - - Map params = new HashMap(); + + Map params = new HashMap(); params.put("guid", UUID.randomUUID().toString()); params.put("zoneId", String.valueOf(physicalNetwork.getDataCenterId())); params.put("physicalNetworkId", String.valueOf(physicalNetwork.getId())); @@ -594,40 +596,40 @@ public class NiciraNvpElement extends AdapterBase implements params.put("adminuser", cmd.getUsername()); params.put("adminpass", cmd.getPassword()); params.put("transportzoneuuid", cmd.getTransportzoneUuid()); - // FIXME What to do with multiple isolation types - params.put("transportzoneisotype", - physicalNetwork.getIsolationMethods().get(0).toLowerCase()); - if (cmd.getL3GatewayServiceUuid() != null) { - params.put("l3gatewayserviceuuid", cmd.getL3GatewayServiceUuid()); - } + // FIXME What to do with multiple isolation types + params.put("transportzoneisotype", + physicalNetwork.getIsolationMethods().get(0).toLowerCase()); + if (cmd.getL3GatewayServiceUuid() != null) { + params.put("l3gatewayserviceuuid", cmd.getL3GatewayServiceUuid()); + } - Map hostdetails = new HashMap(); + Map hostdetails = new HashMap(); hostdetails.putAll(params); - + Transaction txn = Transaction.currentTxn(); try { resource.configure(cmd.getHost(), hostdetails); - - Host host = _resourceMgr.addHost(zoneId, resource, - Host.Type.L2Networking, params); + + Host host = _resourceMgr.addHost(zoneId, resource, + Host.Type.L2Networking, params); if (host != null) { txn.start(); - - niciraNvpDevice = new NiciraNvpDeviceVO(host.getId(), - physicalNetworkId, ntwkSvcProvider.getProviderName(), - deviceName); + + niciraNvpDevice = new NiciraNvpDeviceVO(host.getId(), + physicalNetworkId, ntwkSvcProvider.getProviderName(), + deviceName); _niciraNvpDao.persist(niciraNvpDevice); - - DetailVO detail = new DetailVO(host.getId(), - "niciranvpdeviceid", String.valueOf(niciraNvpDevice - .getId())); + + DetailVO detail = new DetailVO(host.getId(), + "niciranvpdeviceid", String.valueOf(niciraNvpDevice + .getId())); _hostDetailsDao.persist(detail); txn.commit(); return niciraNvpDevice; } else { - throw new CloudRuntimeException( - "Failed to add Nicira Nvp Device due to internal error."); + throw new CloudRuntimeException( + "Failed to add Nicira Nvp Device due to internal error."); } } catch (ConfigurationException e) { txn.rollback(); @@ -638,8 +640,8 @@ public class NiciraNvpElement extends AdapterBase implements @Override public NiciraNvpDeviceResponse createNiciraNvpDeviceResponse( NiciraNvpDeviceVO niciraNvpDeviceVO) { - HostVO niciraNvpHost = _hostDao.findById(niciraNvpDeviceVO.getHostId()); - _hostDao.loadDetails(niciraNvpHost); + HostVO niciraNvpHost = _hostDao.findById(niciraNvpDeviceVO.getHostId()); + _hostDao.loadDetails(niciraNvpHost); NiciraNvpDeviceResponse response = new NiciraNvpDeviceResponse(); response.setDeviceName(niciraNvpDeviceVO.getDeviceName()); @@ -647,118 +649,118 @@ public class NiciraNvpElement extends AdapterBase implements if (pnw != null) { response.setPhysicalNetworkId(pnw.getUuid()); } - response.setId(niciraNvpDeviceVO.getUuid()); + response.setId(niciraNvpDeviceVO.getUuid()); response.setProviderName(niciraNvpDeviceVO.getProviderName()); - response.setHostName(niciraNvpHost.getDetail("ip")); - response.setTransportZoneUuid(niciraNvpHost.getDetail("transportzoneuuid")); - response.setL3GatewayServiceUuid(niciraNvpHost.getDetail("l3gatewayserviceuuid")); - response.setObjectName("niciranvpdevice"); + response.setHostName(niciraNvpHost.getDetail("ip")); + response.setTransportZoneUuid(niciraNvpHost.getDetail("transportzoneuuid")); + response.setL3GatewayServiceUuid(niciraNvpHost.getDetail("l3gatewayserviceuuid")); + response.setObjectName("niciranvpdevice"); return response; } - + @Override public boolean deleteNiciraNvpDevice(DeleteNiciraNvpDeviceCmd cmd) { Long niciraDeviceId = cmd.getNiciraNvpDeviceId(); - NiciraNvpDeviceVO niciraNvpDevice = _niciraNvpDao - .findById(niciraDeviceId); + NiciraNvpDeviceVO niciraNvpDevice = _niciraNvpDao + .findById(niciraDeviceId); if (niciraNvpDevice == null) { - throw new InvalidParameterValueException( - "Could not find a nicira device with id " + niciraDeviceId); + throw new InvalidParameterValueException( + "Could not find a nicira device with id " + niciraDeviceId); } - + // Find the physical network we work for Long physicalNetworkId = niciraNvpDevice.getPhysicalNetworkId(); - PhysicalNetworkVO physicalNetwork = _physicalNetworkDao - .findById(physicalNetworkId); + PhysicalNetworkVO physicalNetwork = _physicalNetworkDao + .findById(physicalNetworkId); if (physicalNetwork != null) { // Lets see if there are networks that use us // Find the nicira networks on this physical network - List networkList = _networkDao - .listByPhysicalNetwork(physicalNetworkId); - + List networkList = _networkDao + .listByPhysicalNetwork(physicalNetworkId); + // Networks with broadcast type lswitch are ours for (NetworkVO network : networkList) { if (network.getBroadcastDomainType() == Networks.BroadcastDomainType.Lswitch) { - if ((network.getState() != Network.State.Shutdown) - && (network.getState() != Network.State.Destroy)) { - throw new CloudRuntimeException( - "This Nicira Nvp device can not be deleted as there are one or more logical networks provisioned by cloudstack."); + if ((network.getState() != Network.State.Shutdown) + && (network.getState() != Network.State.Destroy)) { + throw new CloudRuntimeException( + "This Nicira Nvp device can not be deleted as there are one or more logical networks provisioned by cloudstack."); } } } } - + HostVO niciraHost = _hostDao.findById(niciraNvpDevice.getHostId()); Long hostId = niciraHost.getId(); - + niciraHost.setResourceState(ResourceState.Maintenance); _hostDao.update(hostId, niciraHost); _resourceMgr.deleteHost(hostId, false, false); - + _niciraNvpDao.remove(niciraDeviceId); return true; } - + @Override - public List listNiciraNvpDevices( - ListNiciraNvpDevicesCmd cmd) { + public List listNiciraNvpDevices( + ListNiciraNvpDevicesCmd cmd) { Long physicalNetworkId = cmd.getPhysicalNetworkId(); Long niciraNvpDeviceId = cmd.getNiciraNvpDeviceId(); List responseList = new ArrayList(); - + if (physicalNetworkId == null && niciraNvpDeviceId == null) { - throw new InvalidParameterValueException( - "Either physical network Id or nicira device Id must be specified"); + throw new InvalidParameterValueException( + "Either physical network Id or nicira device Id must be specified"); } - + if (niciraNvpDeviceId != null) { - NiciraNvpDeviceVO niciraNvpDevice = _niciraNvpDao - .findById(niciraNvpDeviceId); + NiciraNvpDeviceVO niciraNvpDevice = _niciraNvpDao + .findById(niciraNvpDeviceId); if (niciraNvpDevice == null) { - throw new InvalidParameterValueException( - "Could not find Nicira Nvp device with id: " - + niciraNvpDevice); + throw new InvalidParameterValueException( + "Could not find Nicira Nvp device with id: " + + niciraNvpDevice); } responseList.add(niciraNvpDevice); - } else { - PhysicalNetworkVO physicalNetwork = _physicalNetworkDao - .findById(physicalNetworkId); + } else { + PhysicalNetworkVO physicalNetwork = _physicalNetworkDao + .findById(physicalNetworkId); if (physicalNetwork == null) { - throw new InvalidParameterValueException( - "Could not find a physical network with id: " - + physicalNetworkId); + throw new InvalidParameterValueException( + "Could not find a physical network with id: " + + physicalNetworkId); } - responseList = _niciraNvpDao - .listByPhysicalNetwork(physicalNetworkId); + responseList = _niciraNvpDao + .listByPhysicalNetwork(physicalNetworkId); } - + return responseList; } - + @Override - public List listNiciraNvpDeviceNetworks( - ListNiciraNvpDeviceNetworksCmd cmd) { + public List listNiciraNvpDeviceNetworks( + ListNiciraNvpDeviceNetworksCmd cmd) { Long niciraDeviceId = cmd.getNiciraNvpDeviceId(); - NiciraNvpDeviceVO niciraNvpDevice = _niciraNvpDao - .findById(niciraDeviceId); + NiciraNvpDeviceVO niciraNvpDevice = _niciraNvpDao + .findById(niciraDeviceId); if (niciraNvpDevice == null) { - throw new InvalidParameterValueException( - "Could not find a nicira device with id " + niciraDeviceId); + throw new InvalidParameterValueException( + "Could not find a nicira device with id " + niciraDeviceId); } - + // Find the physical network we work for Long physicalNetworkId = niciraNvpDevice.getPhysicalNetworkId(); - PhysicalNetworkVO physicalNetwork = _physicalNetworkDao - .findById(physicalNetworkId); + PhysicalNetworkVO physicalNetwork = _physicalNetworkDao + .findById(physicalNetworkId); if (physicalNetwork == null) { // No such physical network, so no provisioned networks return Collections.emptyList(); } - + // Find the nicira networks on this physical network - List networkList = _networkDao - .listByPhysicalNetwork(physicalNetworkId); - + List networkList = _networkDao + .listByPhysicalNetwork(physicalNetworkId); + // Networks with broadcast type lswitch are ours List responseList = new ArrayList(); for (NetworkVO network : networkList) { @@ -766,10 +768,10 @@ public class NiciraNvpElement extends AdapterBase implements responseList.add(network); } } - + return responseList; } - + @Override public HostVO createHostVOForConnectedAgent(HostVO host, StartupCommand[] cmd) { @@ -797,156 +799,156 @@ public class NiciraNvpElement extends AdapterBase implements return new DeleteHostAnswer(true); } - /** - * From interface SourceNatServiceProvider - */ - @Override - public IpDeployer getIpDeployer(Network network) { - return this; - } + /** + * From interface SourceNatServiceProvider + */ + @Override + public IpDeployer getIpDeployer(Network network) { + return this; + } - /** - * From interface IpDeployer - * - * @param network - * @param ipAddress - * @param services - * @return - * @throws ResourceUnavailableException - */ - @Override - public boolean applyIps(Network network, - List ipAddress, Set services) - throws ResourceUnavailableException { - if (services.contains(Service.SourceNat)) { - // Only if we need to provide SourceNat we need to configure the logical router - // SourceNat is required for StaticNat and PortForwarding - List devices = _niciraNvpDao - .listByPhysicalNetwork(network.getPhysicalNetworkId()); - if (devices.isEmpty()) { - s_logger.error("No NiciraNvp Controller on physical network " - + network.getPhysicalNetworkId()); - return false; - } - NiciraNvpDeviceVO niciraNvpDevice = devices.get(0); - HostVO niciraNvpHost = _hostDao.findById(niciraNvpDevice.getHostId()); - _hostDao.loadDetails(niciraNvpHost); + /** + * From interface IpDeployer + * + * @param network + * @param ipAddress + * @param services + * @return + * @throws ResourceUnavailableException + */ + @Override + public boolean applyIps(Network network, + List ipAddress, Set services) + throws ResourceUnavailableException { + if (services.contains(Service.SourceNat)) { + // Only if we need to provide SourceNat we need to configure the logical router + // SourceNat is required for StaticNat and PortForwarding + List devices = _niciraNvpDao + .listByPhysicalNetwork(network.getPhysicalNetworkId()); + if (devices.isEmpty()) { + s_logger.error("No NiciraNvp Controller on physical network " + + network.getPhysicalNetworkId()); + return false; + } + NiciraNvpDeviceVO niciraNvpDevice = devices.get(0); + HostVO niciraNvpHost = _hostDao.findById(niciraNvpDevice.getHostId()); + _hostDao.loadDetails(niciraNvpHost); - NiciraNvpRouterMappingVO routermapping = _niciraNvpRouterMappingDao - .findByNetworkId(network.getId()); - if (routermapping == null) { - s_logger.error("No logical router uuid found for network " - + network.getDisplayText()); - return false; - } + NiciraNvpRouterMappingVO routermapping = _niciraNvpRouterMappingDao + .findByNetworkId(network.getId()); + if (routermapping == null) { + s_logger.error("No logical router uuid found for network " + + network.getDisplayText()); + return false; + } - List cidrs = new ArrayList(); - for (PublicIpAddress ip : ipAddress) { - cidrs.add(ip.getAddress().addr() + "/" + NetUtils.getCidrSize(ip.getNetmask())); - } - ConfigurePublicIpsOnLogicalRouterCommand cmd = new ConfigurePublicIpsOnLogicalRouterCommand(routermapping.getLogicalRouterUuid(), - niciraNvpHost.getDetail("l3gatewayserviceuuid"), cidrs); - ConfigurePublicIpsOnLogicalRouterAnswer answer = (ConfigurePublicIpsOnLogicalRouterAnswer) _agentMgr.easySend(niciraNvpHost.getId(), cmd); - //FIXME answer can be null if the host is down - return answer.getResult(); - } - else { - s_logger.debug("No need to provision ip addresses as we are not providing L3 services."); - } + List cidrs = new ArrayList(); + for (PublicIpAddress ip : ipAddress) { + cidrs.add(ip.getAddress().addr() + "/" + NetUtils.getCidrSize(ip.getNetmask())); + } + ConfigurePublicIpsOnLogicalRouterCommand cmd = new ConfigurePublicIpsOnLogicalRouterCommand(routermapping.getLogicalRouterUuid(), + niciraNvpHost.getDetail("l3gatewayserviceuuid"), cidrs); + ConfigurePublicIpsOnLogicalRouterAnswer answer = (ConfigurePublicIpsOnLogicalRouterAnswer) _agentMgr.easySend(niciraNvpHost.getId(), cmd); + //FIXME answer can be null if the host is down + return answer.getResult(); + } + else { + s_logger.debug("No need to provision ip addresses as we are not providing L3 services."); + } - return true; - } + return true; + } - /** - * From interface StaticNatServiceProvider - */ - @Override - public boolean applyStaticNats(Network network, - List rules) - throws ResourceUnavailableException { + /** + * From interface StaticNatServiceProvider + */ + @Override + public boolean applyStaticNats(Network network, + List rules) + throws ResourceUnavailableException { if (!canHandle(network, Service.StaticNat)) { return false; } - List devices = _niciraNvpDao - .listByPhysicalNetwork(network.getPhysicalNetworkId()); - if (devices.isEmpty()) { - s_logger.error("No NiciraNvp Controller on physical network " - + network.getPhysicalNetworkId()); - return false; - } - NiciraNvpDeviceVO niciraNvpDevice = devices.get(0); - HostVO niciraNvpHost = _hostDao.findById(niciraNvpDevice.getHostId()); + List devices = _niciraNvpDao + .listByPhysicalNetwork(network.getPhysicalNetworkId()); + if (devices.isEmpty()) { + s_logger.error("No NiciraNvp Controller on physical network " + + network.getPhysicalNetworkId()); + return false; + } + NiciraNvpDeviceVO niciraNvpDevice = devices.get(0); + HostVO niciraNvpHost = _hostDao.findById(niciraNvpDevice.getHostId()); - NiciraNvpRouterMappingVO routermapping = _niciraNvpRouterMappingDao - .findByNetworkId(network.getId()); - if (routermapping == null) { - s_logger.error("No logical router uuid found for network " - + network.getDisplayText()); - return false; - } + NiciraNvpRouterMappingVO routermapping = _niciraNvpRouterMappingDao + .findByNetworkId(network.getId()); + if (routermapping == null) { + s_logger.error("No logical router uuid found for network " + + network.getDisplayText()); + return false; + } - List staticNatRules = new ArrayList(); + List staticNatRules = new ArrayList(); for (StaticNat rule : rules) { IpAddress sourceIp = _networkManager.getIp(rule.getSourceIpAddressId()); // Force the nat rule into the StaticNatRuleTO, no use making a new TO object // we only need the source and destination ip. Unfortunately no mention if a rule // is new. StaticNatRuleTO ruleTO = new StaticNatRuleTO(1, - sourceIp.getAddress().addr(), 0, 65535, - rule.getDestIpAddress(), 0, 65535, - "any", rule.isForRevoke(), false); + sourceIp.getAddress().addr(), 0, 65535, + rule.getDestIpAddress(), 0, 65535, + "any", rule.isForRevoke(), false); staticNatRules.add(ruleTO); } ConfigureStaticNatRulesOnLogicalRouterCommand cmd = - new ConfigureStaticNatRulesOnLogicalRouterCommand(routermapping.getLogicalRouterUuid(), staticNatRules); + new ConfigureStaticNatRulesOnLogicalRouterCommand(routermapping.getLogicalRouterUuid(), staticNatRules); ConfigureStaticNatRulesOnLogicalRouterAnswer answer = (ConfigureStaticNatRulesOnLogicalRouterAnswer) _agentMgr.easySend(niciraNvpHost.getId(), cmd); return answer.getResult(); - } + } - /** - * From interface PortForwardingServiceProvider - */ - @Override - public boolean applyPFRules(Network network, List rules) - throws ResourceUnavailableException { + /** + * From interface PortForwardingServiceProvider + */ + @Override + public boolean applyPFRules(Network network, List rules) + throws ResourceUnavailableException { if (!canHandle(network, Service.PortForwarding)) { return false; } - List devices = _niciraNvpDao - .listByPhysicalNetwork(network.getPhysicalNetworkId()); - if (devices.isEmpty()) { - s_logger.error("No NiciraNvp Controller on physical network " - + network.getPhysicalNetworkId()); - return false; - } - NiciraNvpDeviceVO niciraNvpDevice = devices.get(0); - HostVO niciraNvpHost = _hostDao.findById(niciraNvpDevice.getHostId()); + List devices = _niciraNvpDao + .listByPhysicalNetwork(network.getPhysicalNetworkId()); + if (devices.isEmpty()) { + s_logger.error("No NiciraNvp Controller on physical network " + + network.getPhysicalNetworkId()); + return false; + } + NiciraNvpDeviceVO niciraNvpDevice = devices.get(0); + HostVO niciraNvpHost = _hostDao.findById(niciraNvpDevice.getHostId()); - NiciraNvpRouterMappingVO routermapping = _niciraNvpRouterMappingDao - .findByNetworkId(network.getId()); - if (routermapping == null) { - s_logger.error("No logical router uuid found for network " - + network.getDisplayText()); - return false; - } + NiciraNvpRouterMappingVO routermapping = _niciraNvpRouterMappingDao + .findByNetworkId(network.getId()); + if (routermapping == null) { + s_logger.error("No logical router uuid found for network " + + network.getDisplayText()); + return false; + } - List portForwardingRules = new ArrayList(); + List portForwardingRules = new ArrayList(); for (PortForwardingRule rule : rules) { IpAddress sourceIp = _networkManager.getIp(rule.getSourceIpAddressId()); Vlan vlan = _vlanDao.findById(sourceIp.getVlanId()); - PortForwardingRuleTO ruleTO = new PortForwardingRuleTO((PortForwardingRule) rule, vlan.getVlanTag(), sourceIp.getAddress().addr()); + PortForwardingRuleTO ruleTO = new PortForwardingRuleTO(rule, vlan.getVlanTag(), sourceIp.getAddress().addr()); portForwardingRules.add(ruleTO); } ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = - new ConfigurePortForwardingRulesOnLogicalRouterCommand(routermapping.getLogicalRouterUuid(), portForwardingRules); + new ConfigurePortForwardingRulesOnLogicalRouterCommand(routermapping.getLogicalRouterUuid(), portForwardingRules); ConfigurePortForwardingRulesOnLogicalRouterAnswer answer = (ConfigurePortForwardingRulesOnLogicalRouterAnswer) _agentMgr.easySend(niciraNvpHost.getId(), cmd); return answer.getResult(); - } + } } diff --git a/server/src/com/cloud/api/ApiServer.java b/server/src/com/cloud/api/ApiServer.java index c9cabf0c5ef..c0eedc15751 100755 --- a/server/src/com/cloud/api/ApiServer.java +++ b/server/src/com/cloud/api/ApiServer.java @@ -52,6 +52,8 @@ import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.cloudstack.acl.APIAccessChecker; +import org.apache.cloudstack.acl.RoleType; +import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseAsyncCreateCmd; import org.apache.cloudstack.api.BaseCmd; @@ -62,9 +64,6 @@ 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.acl.ControlledEntity; -import org.apache.cloudstack.acl.RoleType; -import org.apache.cloudstack.api.*; 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; @@ -75,12 +74,8 @@ 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; -<<<<<<< HEAD import org.apache.cloudstack.api.response.ExceptionResponse; import org.apache.cloudstack.api.response.ListResponse; -import org.apache.cloudstack.discovery.ApiDiscoveryService; -======= ->>>>>>> master import org.apache.commons.codec.binary.Base64; import org.apache.http.ConnectionClosedException; import org.apache.http.HttpException; @@ -133,6 +128,7 @@ import com.cloud.user.UserAccount; import com.cloud.user.UserContext; import com.cloud.user.UserVO; import com.cloud.utils.Pair; +import com.cloud.utils.ReflectUtil; import com.cloud.utils.StringUtils; import com.cloud.utils.component.ComponentContext; import com.cloud.utils.component.PluggableService; @@ -179,7 +175,7 @@ public class ApiServer implements HttpRequestHandler { if (s_instance == null) { s_instance = new ApiServer(); s_instance = ComponentContext.inject(s_instance); - s_instance.init(apiConfig); + s_instance.init(); } } @@ -798,37 +794,14 @@ public class ApiServer implements HttpRequestHandler { return true; } - private boolean isCommandAvailable(User user, String commandName) { + private boolean isCommandAvailable(User user, String commandName) + throws PermissionDeniedException { if (user == null) { return false; } Account account = _accountMgr.getAccount(user.getAccountId()); - if (account == null) { - return false; - } - - RoleType roleType = RoleType.Unknown; - short accountType = account.getType(); - - // Account type to role type translation - switch (accountType) { - case Account.ACCOUNT_TYPE_ADMIN: - roleType = RoleType.Admin; - break; - case Account.ACCOUNT_TYPE_DOMAIN_ADMIN: - roleType = RoleType.DomainAdmin; - break; - case Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN: - roleType = RoleType.ResourceAdmin; - break; - case Account.ACCOUNT_TYPE_NORMAL: - roleType = RoleType.User; - break; - default: - return false; - } - + RoleType roleType = _accountMgr.getRoleType(account); for (APIAccessChecker apiChecker : _apiAccessCheckers) { // Fail the checking if any checker fails to verify if (!apiChecker.canAccessAPI(roleType, commandName)) diff --git a/server/src/com/cloud/network/element/VirtualRouterElement.java b/server/src/com/cloud/network/element/VirtualRouterElement.java index 481844364a6..b25d4c47876 100755 --- a/server/src/com/cloud/network/element/VirtualRouterElement.java +++ b/server/src/com/cloud/network/element/VirtualRouterElement.java @@ -25,6 +25,7 @@ import java.util.Set; import javax.ejb.Local; import javax.inject.Inject; +import com.cloud.utils.PropertiesUtil; import org.apache.cloudstack.api.command.admin.router.ConfigureVirtualRouterElementCmd; import org.apache.cloudstack.api.command.admin.router.ListVirtualRouterElementsCmd; import org.apache.log4j.Logger; @@ -682,8 +683,9 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl } @Override - public String[] getPropertiesFiles() { - return new String[] { "virtualrouter_commands.properties" }; + public Map getProperties() { + return PropertiesUtil.processConfigFile(new String[] + { "virtualrouter_commands.properties" }); } @Override diff --git a/server/src/com/cloud/server/ManagementServerExtImpl.java b/server/src/com/cloud/server/ManagementServerExtImpl.java index 03e50ebbe69..310698536b0 100644 --- a/server/src/com/cloud/server/ManagementServerExtImpl.java +++ b/server/src/com/cloud/server/ManagementServerExtImpl.java @@ -32,6 +32,7 @@ import com.cloud.domain.dao.DomainDao; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.PermissionDeniedException; import com.cloud.projects.Project; +import com.cloud.utils.PropertiesUtil; import org.apache.cloudstack.api.response.UsageTypeResponse; import org.springframework.stereotype.Component; @@ -209,8 +210,9 @@ public class ManagementServerExtImpl extends ManagementServerImpl implements Man } @Override - public String[] getPropertiesFiles() { - return new String[] { "commands.properties", "commands-ext.properties" }; + public Map getProperties() { + return PropertiesUtil.processConfigFile(new String[] + { "commands.properties", "commands-ext.properties" }); } private Date computeAdjustedTime(Date initialDate, TimeZone targetTZ, boolean adjustToDayStart) { diff --git a/server/src/com/cloud/server/ManagementServerImpl.java b/server/src/com/cloud/server/ManagementServerImpl.java index 60bab003d9e..d8525d63c7f 100755 --- a/server/src/com/cloud/server/ManagementServerImpl.java +++ b/server/src/com/cloud/server/ManagementServerImpl.java @@ -223,6 +223,7 @@ 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.Adapter; import com.cloud.utils.component.ComponentContext; @@ -2392,8 +2393,9 @@ public class ManagementServerImpl implements ManagementServer { } @Override - public String[] getPropertiesFiles() { - return new String[] { "commands.properties" }; + public Map getProperties() { + return PropertiesUtil.processConfigFile(new String[] + { "commands.properties" }); } protected class EventPurgeTask implements Runnable { diff --git a/server/src/com/cloud/user/AccountManagerImpl.java b/server/src/com/cloud/user/AccountManagerImpl.java index dc0370bc94b..cf8602c22d2 100755 --- a/server/src/com/cloud/user/AccountManagerImpl.java +++ b/server/src/com/cloud/user/AccountManagerImpl.java @@ -38,6 +38,7 @@ import javax.inject.Inject; import javax.naming.ConfigurationException; import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.acl.SecurityChecker; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.command.admin.account.UpdateAccountCmd; @@ -1537,6 +1538,31 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag } } + @Override + public RoleType getRoleType(Account account) { + RoleType roleType = RoleType.Unknown; + if (account == null) + return roleType; + short accountType = account.getType(); + + // Account type to role type translation + switch (accountType) { + case Account.ACCOUNT_TYPE_ADMIN: + roleType = RoleType.Admin; + break; + case Account.ACCOUNT_TYPE_DOMAIN_ADMIN: + roleType = RoleType.DomainAdmin; + break; + case Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN: + roleType = RoleType.ResourceAdmin; + break; + case Account.ACCOUNT_TYPE_NORMAL: + roleType = RoleType.User; + break; + } + return roleType; + } + @Override public User getActiveUser(long userId) { return _userDao.findById(userId); diff --git a/server/test/com/cloud/user/MockAccountManagerImpl.java b/server/test/com/cloud/user/MockAccountManagerImpl.java index ae5d0e5de4b..550304adfff 100644 --- a/server/test/com/cloud/user/MockAccountManagerImpl.java +++ b/server/test/com/cloud/user/MockAccountManagerImpl.java @@ -23,6 +23,7 @@ import javax.ejb.Local; import javax.naming.ConfigurationException; import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import com.cloud.api.query.vo.ControlledViewEntity; @@ -344,4 +345,9 @@ public class MockAccountManagerImpl implements Manager, AccountManager, AccountS return null; } + @Override + public RoleType getRoleType(Account account) { + return null; + } + } diff --git a/utils/src/com/cloud/utils/PropertiesUtil.java b/utils/src/com/cloud/utils/PropertiesUtil.java index 3909ca876b6..90f8af8b33f 100755 --- a/utils/src/com/cloud/utils/PropertiesUtil.java +++ b/utils/src/com/cloud/utils/PropertiesUtil.java @@ -17,6 +17,8 @@ package com.cloud.utils; import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; @@ -28,6 +30,7 @@ import java.util.Set; import org.apache.log4j.Logger; public class PropertiesUtil { + private static final Logger s_logger = Logger.getLogger(PropertiesUtil.class); /** * Searches the class path and local paths to find the config file. * @param path path to find. if it starts with / then it's absolute path. @@ -116,4 +119,41 @@ public class PropertiesUtil { } return null; } + + // Returns key=value pairs by parsing a commands.properties/config file + // with syntax; key=cmd;value (with this syntax cmd is stripped) and key=value + public static Map processConfigFile(String[] configFiles) { + Map configMap = new HashMap(); + Properties preProcessedCommands = new Properties(); + for (String configFile : configFiles) { + File commandsFile = findConfigFile(configFile); + if (commandsFile != null) { + try { + preProcessedCommands.load(new FileInputStream(commandsFile)); + } catch (FileNotFoundException fnfex) { + // in case of a file within a jar in classpath, try to open stream using url + InputStream stream = PropertiesUtil.openStreamFromURL(configFile); + if (stream != null) { + try { + preProcessedCommands.load(stream); + } catch (IOException e) { + s_logger.error("IO Exception, unable to find properties file:", fnfex); + } + } else { + s_logger.error("Unable to find properites file", fnfex); + } + } catch (IOException ioe) { + s_logger.error("IO Exception loading properties file", ioe); + } + } + } + + for (Object key : preProcessedCommands.keySet()) { + String preProcessedCommand = preProcessedCommands.getProperty((String) key); + int splitIndex = preProcessedCommand.lastIndexOf(";"); + String value = preProcessedCommand.substring(splitIndex+1); + configMap.put((String)key, value); + } + return configMap; + } } diff --git a/utils/src/com/cloud/utils/component/PluggableService.java b/utils/src/com/cloud/utils/component/PluggableService.java index d2199394a69..f6f72a904d0 100644 --- a/utils/src/com/cloud/utils/component/PluggableService.java +++ b/utils/src/com/cloud/utils/component/PluggableService.java @@ -16,9 +16,11 @@ // under the License. package com.cloud.utils.component; +import java.util.Map; + // This interface defines methods for pluggable code within the Cloud Stack. public interface PluggableService { // The config command properties filenames that lists allowed API commands // and role masks supported by this pluggable service - String[] getPropertiesFiles(); + Map getProperties(); }