Port forwarding rules and load balancing rules rewrite

This commit is contained in:
Alex Huang 2010-12-02 08:50:06 -08:00
parent 94cb30a745
commit 223688d0bf
77 changed files with 5389 additions and 4234 deletions

View File

@ -0,0 +1,44 @@
/**
* Copyright (C) 2010 Cloud.com, Inc. All rights reserved.
*
* This software is licensed under the GNU General Public License v3 or later.
*
* It is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.cloud.agent.api.routing;
import java.util.HashMap;
import com.cloud.agent.api.Command;
public abstract class RoutingCommand extends Command {
HashMap<String, String> accessDetails = new HashMap<String, String>(0);
protected RoutingCommand() {
super();
}
public void setAccessDetail(String name, String value) {
accessDetails.put(name, value);
}
public String getAccessDetail(String name) {
return accessDetails.get(name);
}
@Override
public boolean executeInSequence() {
return false;
}
}

View File

@ -0,0 +1,38 @@
/**
* Copyright (C) 2010 Cloud.com, Inc. All rights reserved.
*
* This software is licensed under the GNU General Public License v3 or later.
*
* It is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.cloud.agent.api.routing;
import com.cloud.agent.api.Answer;
public class SetFirewallRulesAnswer extends Answer {
String[] results;
protected SetFirewallRulesAnswer() {
}
public SetFirewallRulesAnswer(SetFirewallRulesCommand cmd, String[] results) {
super(cmd, true, null);
assert (cmd.getRules().length == results.length) : "rules and their results should be the same length don't you think?";
this.results = results;
}
public String[] getResults() {
return results;
}
}

View File

@ -0,0 +1,43 @@
/**
* Copyright (C) 2010 Cloud.com, Inc. All rights reserved.
*
* This software is licensed under the GNU General Public License v3 or later.
*
* It is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.cloud.agent.api.routing;
import java.util.List;
import com.cloud.agent.api.to.FirewallRuleTO;
/**
* SetFirewallRulesCommand is the transport for firewall rules.
*
* AccessDetails allow different components to put in information about
* how to access the components inside the command.
*/
public class SetFirewallRulesCommand extends RoutingCommand {
FirewallRuleTO[] rules;
protected SetFirewallRulesCommand() {
}
public SetFirewallRulesCommand(List<FirewallRuleTO> rules) {
this.rules = rules.toArray(new FirewallRuleTO[rules.size()]);
}
public FirewallRuleTO[] getRules() {
return rules;
}
}

View File

@ -0,0 +1,38 @@
/**
* Copyright (C) 2010 Cloud.com, Inc. All rights reserved.
*
* This software is licensed under the GNU General Public License v3 or later.
*
* It is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.cloud.agent.api.routing;
import com.cloud.agent.api.Answer;
public class SetPortForwardingRulesAnswer extends Answer {
String[] results;
protected SetPortForwardingRulesAnswer() {
super();
}
public SetPortForwardingRulesAnswer(SetPortForwardingRulesCommand cmd, String[] results) {
super(cmd, true, null);
assert(cmd.getRules().length == results.length) : "Shouldn't the results match the commands?";
this.results = results;
}
String[] getResults() {
return results;
}
}

View File

@ -0,0 +1,37 @@
/**
* Copyright (C) 2010 Cloud.com, Inc. All rights reserved.
*
* This software is licensed under the GNU General Public License v3 or later.
*
* It is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.cloud.agent.api.routing;
import java.util.List;
import com.cloud.agent.api.to.PortForwardingRuleTO;
public class SetPortForwardingRulesCommand extends RoutingCommand {
PortForwardingRuleTO[] rules;
protected SetPortForwardingRulesCommand() {
}
public SetPortForwardingRulesCommand(List<PortForwardingRuleTO> rules) {
this.rules = rules.toArray(new PortForwardingRuleTO[rules.size()]);
}
public PortForwardingRuleTO[] getRules() {
return rules;
}
}

View File

@ -0,0 +1,56 @@
/**
* Copyright (C) 2010 Cloud.com, Inc. All rights reserved.
*
* This software is licensed under the GNU General Public License v3 or later.
*
* It is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.cloud.agent.api.to;
public class FirewallRuleTO {
String srcIp;
String protocol;
int[] srcPortRange;
boolean revoked;
String vlanNetmask; // FIXME: Get rid of this!
protected FirewallRuleTO() {
}
public FirewallRuleTO(String srcIp, String protocol, int srcPortStart, int srcPortEnd, boolean revoked) {
this.srcIp = srcIp;
this.protocol = protocol;
this.srcPortRange = new int[] {srcPortStart, srcPortEnd};
this.revoked = revoked;
}
public String getSrcIp() {
return srcIp;
}
public String getProtocol() {
return protocol;
}
public int[] getSrcPortRange() {
return srcPortRange;
}
public boolean revoked() {
return revoked;
}
public String getVlanNetmask() {
return vlanNetmask;
}
}

View File

@ -0,0 +1,41 @@
/**
* Copyright (C) 2010 Cloud.com, Inc. All rights reserved.
*
* This software is licensed under the GNU General Public License v3 or later.
*
* It is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.cloud.agent.api.to;
public class PortForwardingRuleTO extends FirewallRuleTO {
String dstIp;
int[] dstPortRange;
protected PortForwardingRuleTO() {
super();
}
public PortForwardingRuleTO(String srcIp, int srcPortStart, int srcPortEnd, String dstIp, int dstPortStart, int dstPortEnd, String protocol, boolean revoked) {
super(srcIp, protocol, srcPortStart, srcPortEnd, revoked);
this.dstIp = dstIp;
this.dstPortRange = new int[] { dstPortStart, dstPortEnd };
}
public String getDstIp() {
return dstIp;
}
public int[] getDstPortRange() {
return dstPortRange;
}
}

View File

@ -35,6 +35,8 @@ import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.network.DomainRouterService;
import com.cloud.network.NetworkService;
import com.cloud.network.lb.LoadBalancingRulesService;
import com.cloud.network.rules.RulesService;
import com.cloud.network.security.NetworkGroupService;
import com.cloud.resource.ResourceService;
import com.cloud.server.ManagementService;
@ -76,7 +78,6 @@ public abstract class BaseCmd {
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");
private static final DateFormat _outputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
@ -100,9 +101,11 @@ public abstract class BaseCmd {
public static DomainRouterService _routerService;
public static ResponseGenerator _responseGenerator;
public static EntityManager _entityMgr;
public static RulesService _rulesService;
public static LoadBalancingRulesService _lbService;
static void setComponents(ResponseGenerator generator){
static void setComponents(ResponseGenerator generator) {
ComponentLocator locator = ComponentLocator.getLocator(ManagementService.Name);
_mgr = (ManagementService)ComponentLocator.getComponent(ManagementService.Name);
_accountService = locator.getManager(AccountService.class);
@ -117,6 +120,8 @@ public abstract class BaseCmd {
_consoleProxyMgr = locator.getManager(ConsoleProxyService.class);
_routerService = locator.getManager(DomainRouterService.class);
_entityMgr = locator.getManager(EntityManager.class);
_rulesService = locator.getManager(RulesService.class);
_lbService = locator.getManager(LoadBalancingRulesService.class);
_responseGenerator = generator;
}
@ -366,7 +371,9 @@ public abstract class BaseCmd {
Object tagValue = tagData.second();
if (tagValue instanceof Object[]) {
Object[] subObjects = (Object[])tagValue;
if (subObjects.length < 1) continue;
if (subObjects.length < 1) {
continue;
}
writeObjectArray(responseType, suffixSb, i++, tagName, subObjects);
} else {
writeNameValuePair(suffixSb, tagName, tagValue, responseType, i++);
@ -395,7 +402,9 @@ public abstract class BaseCmd {
if (tagValue instanceof Object[]) {
Object[] subObjects = (Object[])tagValue;
if (subObjects.length < 1) return;
if (subObjects.length < 1) {
return;
}
writeObjectArray(responseType, sb, propertyCount, tagName, subObjects);
} else {
if (RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)) {
@ -461,24 +470,26 @@ public abstract class BaseCmd {
return xml;
}
int iLen = xml.length();
if (iLen == 0)
return xml;
if (iLen == 0) {
return xml;
}
StringBuffer sOUT = new StringBuffer(iLen + 256);
int i = 0;
for (; i < iLen; i++) {
char c = xml.charAt(i);
if (c == '<')
sOUT.append("&lt;");
else if (c == '>')
sOUT.append("&gt;");
else if (c == '&')
sOUT.append("&amp;");
else if (c == '"')
sOUT.append("&quot;");
else if (c == '\'')
sOUT.append("&apos;");
else
sOUT.append(c);
if (c == '<') {
sOUT.append("&lt;");
} else if (c == '>') {
sOUT.append("&gt;");
} else if (c == '&') {
sOUT.append("&amp;");
} else if (c == '"') {
sOUT.append("&quot;");
} else if (c == '\'') {
sOUT.append("&apos;");
} else {
sOUT.append(c);
}
}
return sOUT.toString();
}

View File

@ -70,12 +70,12 @@ import com.cloud.domain.Domain;
import com.cloud.event.Event;
import com.cloud.host.Host;
import com.cloud.network.IpAddress;
import com.cloud.network.LoadBalancer;
import com.cloud.network.Network;
import com.cloud.network.RemoteAccessVpn;
import com.cloud.network.VpnUser;
import com.cloud.network.router.VirtualRouter;
import com.cloud.network.rules.FirewallRule;
import com.cloud.network.rules.LoadBalancer;
import com.cloud.network.rules.PortForwardingRule;
import com.cloud.network.security.IngressRule;
import com.cloud.network.security.NetworkGroup;
import com.cloud.network.security.NetworkGroupRules;
@ -142,9 +142,9 @@ public interface ResponseGenerator {
ClusterResponse createClusterResponse(Cluster cluster);
FirewallRuleResponse createFirewallRuleResponse(FirewallRule fwRule);
FirewallRuleResponse createFirewallRuleResponse(PortForwardingRule fwRule);
IpForwardingRuleResponse createIpForwardingRuleResponse(FirewallRule fwRule);
IpForwardingRuleResponse createIpForwardingRuleResponse(PortForwardingRule fwRule);
UserVmResponse createUserVm2Response(UserVm userVm);

View File

@ -17,6 +17,7 @@
*/
package com.cloud.api.commands;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
@ -29,8 +30,8 @@ import com.cloud.api.Parameter;
import com.cloud.api.ServerApiException;
import com.cloud.api.response.SuccessResponse;
import com.cloud.event.EventTypes;
import com.cloud.exception.NetworkRuleConflictException;
import com.cloud.network.LoadBalancer;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.network.rules.LoadBalancer;
import com.cloud.user.Account;
@Implementation(description="Assigns virtual machine or a list of virtual machines to a load balancer rule.", responseObject=SuccessResponse.class)
@ -98,16 +99,22 @@ public class AssignToLoadBalancerRuleCmd extends BaseAsyncCmd {
@Override
public void execute(){
try {
boolean result = _networkService.assignToLoadBalancer(this);
if (result) {
SuccessResponse response = new SuccessResponse(getName());
this.setResponseObject(response);
} else {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to assign load balancer rule");
}
} catch (NetworkRuleConflictException ex) {
throw new ServerApiException(BaseCmd.NETWORK_RULE_CONFLICT_ERROR, ex.getMessage());
if (virtualMachineIds == null && virtualMachineId == null) {
throw new InvalidParameterValueException("Must specify virtual machine id");
}
if (virtualMachineIds == null) {
virtualMachineIds = new ArrayList<Long>();
}
if (virtualMachineId != null) {
virtualMachineIds.add(virtualMachineId);
}
boolean result = _lbService.assignToLoadBalancer(getLoadBalancerId(), virtualMachineIds);
if (result) {
SuccessResponse response = new SuccessResponse(getName());
this.setResponseObject(response);
} else {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to assign load balancer rule");
}
}
}

View File

@ -28,7 +28,7 @@ import com.cloud.api.Parameter;
import com.cloud.api.ServerApiException;
import com.cloud.api.response.FirewallRuleResponse;
import com.cloud.event.EventTypes;
import com.cloud.network.rules.FirewallRule;
import com.cloud.network.rules.PortForwardingRule;
import com.cloud.user.Account;
@Implementation(description="Creates an ip forwarding rule", responseObject=FirewallRuleResponse.class)
@ -72,7 +72,7 @@ public class CreateIpForwardingRuleCmd extends BaseAsyncCreateCmd {
@Override
public void execute(){
FirewallRule result = _networkService.createIpForwardingRuleOnDomr(this.getId());
PortForwardingRule result = _rulesService.createIpForwardingRuleOnDomr(this.getId());
if (result != null) {
FirewallRuleResponse fwResponse = _responseGenerator.createFirewallRuleResponse(result);
fwResponse.setResponseName(getName());
@ -85,7 +85,7 @@ public class CreateIpForwardingRuleCmd extends BaseAsyncCreateCmd {
@Override
public void callCreate(){
FirewallRule rule = _networkService.createIpForwardingRuleInDb(ipAddress,virtualMachineId);
PortForwardingRule rule = _rulesService.createIpForwardingRuleInDb(ipAddress,virtualMachineId);
if (rule != null){
this.setId(rule.getId());
} else {

View File

@ -18,6 +18,8 @@
package com.cloud.api.commands;
import java.util.List;
import org.apache.log4j.Logger;
import com.cloud.api.ApiConstants;
@ -26,10 +28,13 @@ import com.cloud.api.Implementation;
import com.cloud.api.Parameter;
import com.cloud.api.ServerApiException;
import com.cloud.api.response.LoadBalancerResponse;
import com.cloud.network.LoadBalancer;
import com.cloud.exception.NetworkRuleConflictException;
import com.cloud.network.rules.LoadBalancer;
import com.cloud.utils.net.Ip;
import com.cloud.utils.net.NetUtils;
@Implementation(description="Creates a load balancer rule", responseObject=LoadBalancerResponse.class)
public class CreateLoadBalancerRuleCmd extends BaseCmd {
public class CreateLoadBalancerRuleCmd extends BaseCmd implements LoadBalancer {
public static final Logger s_logger = Logger.getLogger(CreateLoadBalancerRuleCmd.class.getName());
private static final String s_name = "createloadbalancerruleresponse";
@ -61,10 +66,12 @@ public class CreateLoadBalancerRuleCmd extends BaseCmd {
/////////////////// Accessors ///////////////////////
/////////////////////////////////////////////////////
@Override
public String getAlgorithm() {
return algorithm;
}
@Override
public String getDescription() {
return description;
}
@ -96,14 +103,86 @@ public class CreateLoadBalancerRuleCmd extends BaseCmd {
}
@Override
public void execute(){
LoadBalancer result = _networkService.createLoadBalancerRule(this);
if (result != null) {
LoadBalancerResponse response = _responseGenerator.createLoadBalancerResponse(result);
response.setResponseName(getName());
this.setResponseObject(response);
} else {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create load balancer rule");
public void execute() {
LoadBalancer result = null;
try {
result = _lbService.createLoadBalancerRule(this);
} catch (NetworkRuleConflictException e) {
throw new ServerApiException(BaseCmd.NETWORK_RULE_CONFLICT_ERROR, e.getMessage());
}
LoadBalancerResponse response = _responseGenerator.createLoadBalancerResponse(result);
response.setResponseName(getName());
this.setResponseObject(response);
}
@Override
public long getId() {
throw new UnsupportedOperationException("not supported");
}
@Override
public String getXid() {
// FIXME: Should fix this.
return null;
}
@Override
public Ip getSourceIpAddress() {
return new Ip(publicIp);
}
@Override
public int getSourcePortStart() {
return Integer.parseInt(publicPort);
}
@Override
public int getSourcePortEnd() {
return Integer.parseInt(publicPort);
}
@Override
public String getProtocol() {
return NetUtils.TCP_PROTO;
}
@Override
public Purpose getPurpose() {
return Purpose.LoadBalancing;
}
@Override
public State getState() {
throw new UnsupportedOperationException("not supported");
}
@Override
public long getNetworkId() {
return -1;
}
@Override
public long getAccountId() {
throw new UnsupportedOperationException("not supported");
}
@Override
public long getDomainId() {
throw new UnsupportedOperationException("not supported");
}
@Override
public int getDefaultPortStart() {
return Integer.parseInt(privatePort);
}
@Override
public int getDefaultPortEnd() {
return Integer.parseInt(privatePort);
}
@Override
public List<? extends Destination> getDestinations() {
throw new UnsupportedOperationException("not supported");
}
}

View File

@ -27,10 +27,13 @@ import com.cloud.api.Parameter;
import com.cloud.api.ServerApiException;
import com.cloud.api.response.FirewallRuleResponse;
import com.cloud.exception.NetworkRuleConflictException;
import com.cloud.network.rules.FirewallRule;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.network.rules.PortForwardingRule;
import com.cloud.user.UserContext;
import com.cloud.utils.net.Ip;
@Implementation(description="Creates a port forwarding rule", responseObject=FirewallRuleResponse.class)
public class CreatePortForwardingRuleCmd extends BaseCmd {
public class CreatePortForwardingRuleCmd extends BaseCmd implements PortForwardingRule {
public static final Logger s_logger = Logger.getLogger(CreatePortForwardingRuleCmd.class.getName());
private static final String s_name = "createportforwardingruleresponse";
@ -67,6 +70,7 @@ public class CreatePortForwardingRuleCmd extends BaseCmd {
return privatePort;
}
@Override
public String getProtocol() {
return protocol;
}
@ -90,19 +94,93 @@ public class CreatePortForwardingRuleCmd extends BaseCmd {
}
@Override
public void execute(){
public void execute() throws ResourceUnavailableException {
try {
FirewallRule result = _networkService.createPortForwardingRule(this);
if (result != null) {
FirewallRuleResponse fwResponse = _responseGenerator.createFirewallRuleResponse(result);
fwResponse.setResponseName(getName());
this.setResponseObject(fwResponse);
} else {
UserContext callerContext = UserContext.current();
PortForwardingRule result = _rulesService.createPortForwardingRule(this, virtualMachineId, callerContext.getAccount());
if (result == null) {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "An existing rule for ipAddress / port / protocol of " + ipAddress + " / " + publicPort + " / " + protocol + " exits.");
}
boolean success = false;
try {
success = _rulesService.applyPortForwardingRules(result.getSourceIpAddress(), callerContext.getAccount());
} finally {
if (!success) {
_rulesService.revokePortForwardingRule(result.getId(), true, callerContext.getAccount());
}
}
FirewallRuleResponse fwResponse = _responseGenerator.createFirewallRuleResponse(result);
fwResponse.setResponseName(getName());
setResponseObject(fwResponse);
} catch (NetworkRuleConflictException ex) {
throw new ServerApiException(BaseCmd.NETWORK_RULE_CONFLICT_ERROR, ex.getMessage());
}
}
@Override
public long getId() {
throw new UnsupportedOperationException("database id can only provided by VO objects");
}
@Override
public String getXid() {
// FIXME: We should allow for end user to specify Xid.
return null;
}
@Override
public Ip getSourceIpAddress() {
return new Ip(ipAddress);
}
@Override
public int getSourcePortStart() {
return Integer.parseInt(publicPort);
}
@Override
public int getSourcePortEnd() {
return Integer.parseInt(publicPort);
}
@Override
public Purpose getPurpose() {
return Purpose.PortForwarding;
}
@Override
public State getState() {
throw new UnsupportedOperationException("Should never call me to find the state");
}
@Override
public long getNetworkId() {
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public long getAccountId() {
throw new UnsupportedOperationException("Get the account id from network");
}
@Override
public long getDomainId() {
throw new UnsupportedOperationException("Get the domain id from network");
}
@Override
public Ip getDestinationIpAddress() {
throw new UnsupportedOperationException("Not implemented yet");
}
@Override
public int getDestinationPortStart() {
return Integer.parseInt(privatePort);
}
@Override
public int getDestinationPortEnd() {
return Integer.parseInt(privatePort);
}
}

View File

@ -63,7 +63,7 @@ public class DeleteIpForwardingRuleCmd extends BaseAsyncCmd {
@Override
public void execute(){
boolean result = false;
result = _networkService.deleteIpForwardingRule(id);
result = _rulesService.deleteIpForwardingRule(id);
if (result) {
SuccessResponse response = new SuccessResponse(getName());
this.setResponseObject(response);

View File

@ -27,7 +27,7 @@ import com.cloud.api.Parameter;
import com.cloud.api.ServerApiException;
import com.cloud.api.response.SuccessResponse;
import com.cloud.event.EventTypes;
import com.cloud.network.LoadBalancer;
import com.cloud.network.rules.LoadBalancer;
import com.cloud.user.Account;
@Implementation(description="Deletes a load balancer rule.", responseObject=SuccessResponse.class)
@ -81,7 +81,7 @@ public class DeleteLoadBalancerRuleCmd extends BaseAsyncCmd {
@Override
public void execute(){
boolean result = _networkService.deleteLoadBalancerRule(this);
boolean result = _lbService.deleteLoadBalancerRule(id, true);
if (result) {
SuccessResponse response = new SuccessResponse(getName());
this.setResponseObject(response);

View File

@ -25,6 +25,9 @@ import com.cloud.api.Implementation;
import com.cloud.api.Parameter;
import com.cloud.api.ServerApiException;
import com.cloud.api.response.SuccessResponse;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.network.rules.PortForwardingRule;
import com.cloud.user.UserContext;
@Implementation(description="Deletes a port forwarding rule", responseObject=SuccessResponse.class)
public class DeletePortForwardingRuleCmd extends BaseCmd {
@ -57,9 +60,9 @@ public class DeletePortForwardingRuleCmd extends BaseCmd {
}
@Override
public void execute(){
boolean result = _networkService.deletePortForwardingRule(id,false);
if (result) {
public void execute() throws ResourceUnavailableException {
PortForwardingRule result = _rulesService.revokePortForwardingRule(id, true, UserContext.current().getAccount());
if (result != null) {
SuccessResponse response = new SuccessResponse(getName());
this.setResponseObject(response);
} else {

View File

@ -30,7 +30,7 @@ import com.cloud.api.BaseCmd.CommandType;
import com.cloud.api.response.FirewallRuleResponse;
import com.cloud.api.response.IpForwardingRuleResponse;
import com.cloud.api.response.ListResponse;
import com.cloud.network.rules.FirewallRule;
import com.cloud.network.rules.PortForwardingRule;
@Implementation(description="List the ip forwarding rules", responseObject=FirewallRuleResponse.class)
public class ListIpForwardingRulesCmd extends BaseListCmd {
@ -82,10 +82,10 @@ public class ListIpForwardingRulesCmd extends BaseListCmd {
@Override
public void execute(){
List<? extends FirewallRule> result = _mgr.searchForIpForwardingRules(this);
List<? extends PortForwardingRule> result = _rulesService.searchForIpForwardingRules(this);
ListResponse<IpForwardingRuleResponse> response = new ListResponse<IpForwardingRuleResponse>();
List<IpForwardingRuleResponse> ipForwardingResponses = new ArrayList<IpForwardingRuleResponse>();
for (FirewallRule rule : result) {
for (PortForwardingRule rule : result) {
IpForwardingRuleResponse resp = _responseGenerator.createIpForwardingRuleResponse(rule);
if (resp != null) {
ipForwardingResponses.add(resp);

View File

@ -69,7 +69,7 @@ public class ListLoadBalancerRuleInstancesCmd extends BaseListCmd {
@Override
public void execute(){
List<? extends UserVm> result = _mgr.listLoadBalancerInstances(this);
List<? extends UserVm> result = _lbService.listLoadBalancerInstances(this);
ListResponse<UserVmResponse> response = new ListResponse<UserVmResponse>();
List<UserVmResponse> vmResponses = new ArrayList<UserVmResponse>();
for (UserVm instance : result) {

View File

@ -29,7 +29,7 @@ import com.cloud.api.Implementation;
import com.cloud.api.Parameter;
import com.cloud.api.response.ListResponse;
import com.cloud.api.response.LoadBalancerResponse;
import com.cloud.network.LoadBalancer;
import com.cloud.network.rules.LoadBalancer;
@Implementation(description="Lists load balancer rules.", responseObject=LoadBalancerResponse.class)
public class ListLoadBalancerRulesCmd extends BaseListCmd {
@ -98,7 +98,7 @@ public class ListLoadBalancerRulesCmd extends BaseListCmd {
@Override
public void execute(){
List<? extends LoadBalancer> loadBalancers = _mgr.searchForLoadBalancers(this);
List<? extends LoadBalancer> loadBalancers = _lbService.searchForLoadBalancers(this);
ListResponse<LoadBalancerResponse> response = new ListResponse<LoadBalancerResponse>();
List<LoadBalancerResponse> lbResponses = new ArrayList<LoadBalancerResponse>();
for (LoadBalancer loadBalancer : loadBalancers) {

View File

@ -28,7 +28,7 @@ import com.cloud.api.Implementation;
import com.cloud.api.Parameter;
import com.cloud.api.response.FirewallRuleResponse;
import com.cloud.api.response.ListResponse;
import com.cloud.network.rules.FirewallRule;
import com.cloud.network.rules.PortForwardingRule;
@Implementation(description="Lists all port forwarding rules for an IP address.", responseObject=FirewallRuleResponse.class)
public class ListPortForwardingRulesCmd extends BaseListCmd {
@ -62,11 +62,11 @@ public class ListPortForwardingRulesCmd extends BaseListCmd {
@Override
public void execute(){
List<? extends FirewallRule> result = _networkService.listPortForwardingRules(this);
List<? extends PortForwardingRule> result = _rulesService.listPortForwardingRules(this);
ListResponse<FirewallRuleResponse> response = new ListResponse<FirewallRuleResponse>();
List<FirewallRuleResponse> fwResponses = new ArrayList<FirewallRuleResponse>();
for (FirewallRule fwRule : result) {
for (PortForwardingRule fwRule : result) {
FirewallRuleResponse ruleData = _responseGenerator.createFirewallRuleResponse(fwRule);
ruleData.setObjectName("portforwardingrule");
fwResponses.add(ruleData);

View File

@ -30,7 +30,8 @@ import com.cloud.api.Parameter;
import com.cloud.api.ServerApiException;
import com.cloud.api.response.SuccessResponse;
import com.cloud.event.EventTypes;
import com.cloud.network.LoadBalancer;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.network.rules.LoadBalancer;
import com.cloud.user.Account;
import com.cloud.utils.StringUtils;
@ -105,7 +106,18 @@ public class RemoveFromLoadBalancerRuleCmd extends BaseAsyncCmd {
@Override
public void execute(){
boolean result = _networkService.removeFromLoadBalancer(this);
if (virtualMachineIds == null && virtualMachineId == null) {
throw new InvalidParameterValueException("Must specify virtual machine id");
}
if (virtualMachineIds == null) {
virtualMachineIds = new ArrayList<Long>();
}
if (virtualMachineId != null) {
virtualMachineIds.add(virtualMachineId);
}
boolean result = _lbService.removeFromLoadBalancer(id, virtualMachineIds);
if (result) {
SuccessResponse response = new SuccessResponse(getName());
this.setResponseObject(response);

View File

@ -27,7 +27,7 @@ import com.cloud.api.Parameter;
import com.cloud.api.ServerApiException;
import com.cloud.api.response.LoadBalancerResponse;
import com.cloud.event.EventTypes;
import com.cloud.network.LoadBalancer;
import com.cloud.network.rules.LoadBalancer;
import com.cloud.user.Account;
@Implementation(description="Updates load balancer", responseObject=LoadBalancerResponse.class)
@ -108,7 +108,7 @@ public class UpdateLoadBalancerRuleCmd extends BaseAsyncCmd {
@Override
public void execute(){
LoadBalancer result = _networkService.updateLoadBalancerRule(this);
LoadBalancer result = _lbService.updateLoadBalancerRule(this);
if (result != null){
LoadBalancerResponse response = _responseGenerator.createLoadBalancerResponse(result);
response.setResponseName(getName());

View File

@ -4,14 +4,11 @@ import org.apache.log4j.Logger;
import com.cloud.api.ApiConstants;
import com.cloud.api.BaseAsyncCmd;
import com.cloud.api.BaseCmd;
import com.cloud.api.Implementation;
import com.cloud.api.Parameter;
import com.cloud.api.ServerApiException;
import com.cloud.api.response.FirewallRuleResponse;
import com.cloud.event.EventTypes;
import com.cloud.network.IpAddress;
import com.cloud.network.rules.FirewallRule;
import com.cloud.user.Account;
@Implementation(responseObject=FirewallRuleResponse.class, description="Updates a port forwarding rule. Only the private port and the virtual machine can be updated.")
@ -101,13 +98,13 @@ public class UpdatePortForwardingRuleCmd extends BaseAsyncCmd {
@Override
public void execute(){
FirewallRule result = _mgr.updatePortForwardingRule(this);
if (result != null) {
FirewallRuleResponse response = _responseGenerator.createFirewallRuleResponse(result);
response.setResponseName(getName());
this.setResponseObject(response);
} else {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update port forwarding rule");
}
//FIXME: PortForwardingRule result = _mgr.updatePortForwardingRule(this);
// if (result != null) {
// FirewallRuleResponse response = _responseGenerator.createFirewallRuleResponse(result);
// response.setResponseName(getName());
// this.setResponseObject(response);
// } else {
// throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update port forwarding rule");
// }
}
}

View File

@ -20,30 +20,21 @@ package com.cloud.network;
import java.util.List;
import com.cloud.api.commands.AddVpnUserCmd;
import com.cloud.api.commands.AssignToLoadBalancerRuleCmd;
import com.cloud.api.commands.AssociateIPAddrCmd;
import com.cloud.api.commands.CreateLoadBalancerRuleCmd;
import com.cloud.api.commands.CreateNetworkCmd;
import com.cloud.api.commands.CreatePortForwardingRuleCmd;
import com.cloud.api.commands.CreateRemoteAccessVpnCmd;
import com.cloud.api.commands.DeleteLoadBalancerRuleCmd;
import com.cloud.api.commands.DeleteNetworkCmd;
import com.cloud.api.commands.DeleteRemoteAccessVpnCmd;
import com.cloud.api.commands.DisassociateIPAddrCmd;
import com.cloud.api.commands.ListNetworksCmd;
import com.cloud.api.commands.ListPortForwardingRulesCmd;
import com.cloud.api.commands.RemoveFromLoadBalancerRuleCmd;
import com.cloud.api.commands.RemoveVpnUserCmd;
import com.cloud.api.commands.UpdateLoadBalancerRuleCmd;
import com.cloud.exception.AccountLimitException;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientAddressCapacityException;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.NetworkRuleConflictException;
import com.cloud.exception.PermissionDeniedException;
import com.cloud.exception.ResourceAllocationException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.network.rules.FirewallRule;
import com.cloud.offering.NetworkOffering;
@ -56,15 +47,6 @@ public interface NetworkService {
* @throws ResourceAllocationException, InsufficientCapacityException
*/
IpAddress associateIP(AssociateIPAddrCmd cmd) throws ResourceAllocationException, InsufficientAddressCapacityException, ConcurrentOperationException;
/**
* Assign a virtual machine, or list of virtual machines, to a load balancer.
*/
boolean assignToLoadBalancer(AssignToLoadBalancerRuleCmd cmd) throws NetworkRuleConflictException;
public boolean removeFromLoadBalancer(RemoveFromLoadBalancerRuleCmd cmd);
public boolean deleteLoadBalancerRule(DeleteLoadBalancerRuleCmd cmd);
public LoadBalancer updateLoadBalancerRule(UpdateLoadBalancerRuleCmd cmd);
public boolean disassociateIpAddress(DisassociateIPAddrCmd cmd);
/**
@ -98,34 +80,6 @@ public interface NetworkService {
boolean removeVpnUser(RemoveVpnUserCmd cmd) throws ConcurrentOperationException;
/**
* Create a port forwarding rule from the given ipAddress/port to the given virtual machine/port.
* @param cmd the command specifying the ip address, public port, protocol, private port, and virtual machine id.
* @return the newly created FirewallRuleVO if successful, null otherwise.
*/
public FirewallRule createPortForwardingRule(CreatePortForwardingRuleCmd cmd) throws NetworkRuleConflictException;
/**
* List port forwarding rules assigned to an ip address
* @param cmd the command object holding the criteria for listing port forwarding rules (the ipAddress)
* @return list of port forwarding rules on the given address, empty list if no rules exist
*/
public List<? extends FirewallRule> listPortForwardingRules(ListPortForwardingRulesCmd cmd);
/**
* Create a load balancer rule from the given ipAddress/port to the given private port
* @param cmd the command specifying the ip address, public port, protocol, private port, and algorithm
* @return the newly created LoadBalancerVO if successful, null otherwise
*/
public LoadBalancer createLoadBalancerRule(CreateLoadBalancerRuleCmd cmd);
FirewallRule createIpForwardingRuleInDb(String ipAddr, long virtualMachineId);
FirewallRule createIpForwardingRuleOnDomr(long ruleId);
boolean deleteIpForwardingRule(Long id);
boolean deletePortForwardingRule(Long id, boolean sysContext);
Network createNetwork(CreateNetworkCmd cmd) throws InvalidParameterValueException, PermissionDeniedException;
List<? extends Network> searchForNetworks(ListNetworksCmd cmd) throws InvalidParameterValueException, PermissionDeniedException;
boolean deleteNetwork(DeleteNetworkCmd cmd) throws InvalidParameterValueException, PermissionDeniedException;

View File

@ -3,12 +3,15 @@
*/
package com.cloud.network.element;
import java.util.List;
import com.cloud.deploy.DeployDestination;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.InsufficientNetworkCapacityException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.network.Network;
import com.cloud.network.rules.FirewallRule;
import com.cloud.offering.NetworkOffering;
import com.cloud.utils.component.Adapter;
import com.cloud.vm.NicProfile;
@ -26,15 +29,13 @@ public interface NetworkElement extends Adapter {
* @param offering network offering that originated the network configuration.
* @return true if network configuration is now usable; false if not; null if not handled by this element.
*/
boolean implement(Network config, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException;
boolean implement(Network network, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException;
boolean prepare(Network config, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientNetworkCapacityException;
boolean prepare(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientNetworkCapacityException;
boolean release(Network config, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException;
boolean release(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException;
boolean shutdown(Network config, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException;
boolean shutdown(Network network, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException;
boolean addRule();
boolean revokeRule();
boolean applyRules(Network network, List<? extends FirewallRule> rules) throws ResourceUnavailableException;
}

View File

@ -0,0 +1,65 @@
/**
* Copyright (C) 2010 Cloud.com, Inc. All rights reserved.
*
* This software is licensed under the GNU General Public License v3 or later.
*
* It is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.cloud.network.lb;
import java.util.List;
import com.cloud.api.commands.ListLoadBalancerRuleInstancesCmd;
import com.cloud.api.commands.ListLoadBalancerRulesCmd;
import com.cloud.api.commands.UpdateLoadBalancerRuleCmd;
import com.cloud.exception.NetworkRuleConflictException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.network.rules.LoadBalancer;
import com.cloud.uservm.UserVm;
public interface LoadBalancingRulesService {
/**
* Create a load balancer rule from the given ipAddress/port to the given private port
* @param cmd the command specifying the ip address, public port, protocol, private port, and algorithm
* @return the newly created LoadBalancerVO if successful, null otherwise
*/
LoadBalancer createLoadBalancerRule(LoadBalancer lb) throws NetworkRuleConflictException;
LoadBalancer updateLoadBalancerRule(UpdateLoadBalancerRuleCmd cmd);
boolean deleteLoadBalancerRule(long lbRuleId, boolean apply);
/**
* Assign a virtual machine, or list of virtual machines, to a load balancer.
*/
boolean assignToLoadBalancer(long lbRuleId, List<Long> vmIds);
boolean removeFromLoadBalancer(long lbRuleId, List<Long> vmIds);
boolean applyLoadBalancerConfig(long id) throws ResourceUnavailableException;
/**
* List instances that have either been applied to a load balancer or are eligible to be assigned to a load balancer.
* @param cmd
* @return list of vm instances that have been or can be applied to a load balancer
*/
List<? extends UserVm> listLoadBalancerInstances(ListLoadBalancerRuleInstancesCmd cmd);
/**
* List load balancer rules based on the given criteria
* @param cmd the command that specifies the criteria to use for listing load balancers. Load balancers can be listed
* by id, name, public ip, and vm instance id
* @return list of load balancers that match the criteria
*/
List<? extends LoadBalancer> searchForLoadBalancers(ListLoadBalancerRulesCmd cmd);
}

View File

@ -17,10 +17,22 @@
*/
package com.cloud.network.rules;
/**
* Specifies the port forwarding for firewall rule.
*/
public interface FirewallRule {
import com.cloud.acl.ControlledEntity;
import com.cloud.utils.net.Ip;
public interface FirewallRule extends ControlledEntity {
enum Purpose {
PortForwarding,
LoadBalancing,
Vpn,
}
enum State {
Staged, // Rule been created but has never got through network rule conflict detection. Rules in this state can not be sent to network elements.
Add, // Add means the rule has been created and has gone through network rule conflict detection.
Revoke // Revoke means this rule has been revoked. If this rule has been sent to the network elements, the rule will be deleted from database.
}
/**
* @return database id.
*/
@ -34,22 +46,26 @@ public interface FirewallRule {
/**
* @return public ip address.
*/
String getPublicIpAddress();
Ip getSourceIpAddress();
/**
* @return public port.
* @return first port of the source port range.
*/
String getPublicPort();
int getSourcePortStart();
/**
* @return private ip address.
* @return last port of the source prot range. If this is null, that means only one port is mapped.
*/
String getPrivateIpAddress();
int getSourcePortEnd();
/**
* @return private port.
* @return protocol to open these ports for.
*/
String getPrivatePort();
String getProtocol();
Purpose getPurpose();
State getState();
long getNetworkId();
}

View File

@ -15,30 +15,30 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.cloud.network;
package com.cloud.network.rules;
public interface LoadBalancer {
long getId();
import java.util.List;
/**
* Definition for a LoadBalancer
*/
public interface LoadBalancer extends FirewallRule {
String getName();
void setName(String name);
String getDescription();
void setDescription(String description);
long getAccountId();
String getIpAddress();
String getPublicPort();
String getPrivatePort();
void setPrivatePort(String privatePort);
int getDefaultPortStart();
int getDefaultPortEnd();
String getAlgorithm();
void setAlgorithm(String algorithm);
Long getDomainId();
List<? extends Destination> getDestinations();
String getAccountName();
public interface Destination {
String getIpAddress();
int getDestinationPortStart();
int getDestinationPortEnd();
}
}

View File

@ -0,0 +1,40 @@
/**
* Copyright (C) 2010 Cloud.com, Inc. All rights reserved.
*
* This software is licensed under the GNU General Public License v3 or later.
*
* It is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.cloud.network.rules;
import com.cloud.utils.net.Ip;
/**
* Specifies the port forwarding for firewall rule.
*/
public interface PortForwardingRule extends FirewallRule {
/**
* @return destination ip address.
*/
Ip getDestinationIpAddress();
/**
* @return start of destination port.
*/
int getDestinationPortStart();
/**
* @return end of destination port range
*/
int getDestinationPortEnd();
}

View File

@ -0,0 +1,68 @@
/**
* Copyright (C) 2010 Cloud.com, Inc. All rights reserved.
*
* This software is licensed under the GNU General Public License v3 or later.
*
* It is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.cloud.network.rules;
import java.util.List;
import com.cloud.api.commands.ListIpForwardingRulesCmd;
import com.cloud.api.commands.ListPortForwardingRulesCmd;
import com.cloud.exception.NetworkRuleConflictException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.user.Account;
import com.cloud.utils.net.Ip;
public interface RulesService {
List<? extends PortForwardingRule> searchForIpForwardingRules(ListIpForwardingRulesCmd cmd);
/**
* List port forwarding rules assigned to an ip address
* @param cmd the command object holding the criteria for listing port forwarding rules (the ipAddress)
* @return list of port forwarding rules on the given address, empty list if no rules exist
*/
public List<? extends PortForwardingRule> listPortForwardingRules(ListPortForwardingRulesCmd cmd);
PortForwardingRule createIpForwardingRuleInDb(String ipAddr, long virtualMachineId);
PortForwardingRule createIpForwardingRuleOnDomr(long ruleId);
boolean deleteIpForwardingRule(Long id);
boolean deletePortForwardingRule(Long id, boolean sysContext);
boolean applyFirewallRules(Ip ip, Account caller) throws ResourceUnavailableException;
boolean applyNatRules(Ip ip, Account caller) throws ResourceUnavailableException;
boolean applyPortForwardingRules(Ip ip, Account caller) throws ResourceUnavailableException;
/**
* Creates a port forwarding rule between two ip addresses or between
* an ip address and a virtual machine.
* @param rule rule to be created.
* @param vmId vm to be linked to. If specified the destination ip address is ignored.
* @param caller caller
* @return PortForwardingRule if created.
* @throws NetworkRuleConflictException if conflicts in the network rules are detected.
*/
PortForwardingRule createPortForwardingRule(PortForwardingRule rule, Long vmId, Account caller) throws NetworkRuleConflictException;
/**
* Revokes a port forwarding rule
* @param ruleId the id of the rule to revoke.
* @param caller
* @return
*/
PortForwardingRule revokePortForwardingRule(long ruleId, boolean apply, Account caller);
}

View File

@ -45,10 +45,7 @@ import com.cloud.api.commands.ListGuestOsCategoriesCmd;
import com.cloud.api.commands.ListGuestOsCmd;
import com.cloud.api.commands.ListHostsCmd;
import com.cloud.api.commands.ListHypervisorsCmd;
import com.cloud.api.commands.ListIpForwardingRulesCmd;
import com.cloud.api.commands.ListIsosCmd;
import com.cloud.api.commands.ListLoadBalancerRuleInstancesCmd;
import com.cloud.api.commands.ListLoadBalancerRulesCmd;
import com.cloud.api.commands.ListPodsByCmd;
import com.cloud.api.commands.ListPreallocatedLunsCmd;
import com.cloud.api.commands.ListPublicIpAddressesCmd;
@ -75,7 +72,6 @@ import com.cloud.api.commands.StopSystemVmCmd;
import com.cloud.api.commands.UpdateDomainCmd;
import com.cloud.api.commands.UpdateIsoCmd;
import com.cloud.api.commands.UpdateIsoPermissionsCmd;
import com.cloud.api.commands.UpdatePortForwardingRuleCmd;
import com.cloud.api.commands.UpdateTemplateCmd;
import com.cloud.api.commands.UpdateTemplatePermissionsCmd;
import com.cloud.api.commands.UpdateVMGroupCmd;
@ -99,11 +95,9 @@ import com.cloud.exception.ResourceUnavailableException;
import com.cloud.exception.StorageUnavailableException;
import com.cloud.host.Host;
import com.cloud.network.IpAddress;
import com.cloud.network.LoadBalancer;
import com.cloud.network.RemoteAccessVpn;
import com.cloud.network.VpnUser;
import com.cloud.network.router.VirtualRouter;
import com.cloud.network.rules.FirewallRule;
import com.cloud.offering.DiskOffering;
import com.cloud.offering.ServiceOffering;
import com.cloud.org.Cluster;
@ -222,13 +216,6 @@ public interface ManagementService {
*/
List<? extends UserVm> searchForUserVMs(ListVMsCmd cmd);
/**
* Update an existing port forwarding rule on the given public IP / public port for the given protocol
* @param cmd - the UpdatePortForwardingRuleCmd command that wraps publicIp, privateIp, publicPort, privatePort, protocol of the rule to update
* @return the new firewall rule if updated, null if no rule on public IP / public port of that protocol could be found
*/
FirewallRule updatePortForwardingRule(UpdatePortForwardingRuleCmd cmd);
/**
* Obtains a list of events by the specified search criteria.
* Can search by: "username", "type", "level", "startDate", "endDate"
@ -372,21 +359,6 @@ public interface ManagementService {
*/
List<? extends DiskOffering> searchForDiskOfferings(ListDiskOfferingsCmd cmd);
/**
* List instances that have either been applied to a load balancer or are eligible to be assigned to a load balancer.
* @param cmd
* @return list of vm instances that have been or can be applied to a load balancer
*/
List<? extends UserVm> listLoadBalancerInstances(ListLoadBalancerRuleInstancesCmd cmd);
/**
* List load balancer rules based on the given criteria
* @param cmd the command that specifies the criteria to use for listing load balancers. Load balancers can be listed
* by id, name, public ip, and vm instance id
* @return list of load balancers that match the criteria
*/
List<? extends LoadBalancer> searchForLoadBalancers(ListLoadBalancerRulesCmd cmd);
/**
* List storage pools that match the given criteria
* @param cmd the command that wraps the search criteria (zone, pod, name, IP address, path, and cluster id)
@ -449,8 +421,6 @@ public interface ManagementService {
public List<? extends VpnUser> searchForVpnUsers(ListVpnUsersCmd cmd);
List<? extends FirewallRule> searchForIpForwardingRules(ListIpForwardingRulesCmd cmd);
String getVersion();
/**

View File

@ -1,109 +0,0 @@
/**
* Copyright (C) 2010 Cloud.com, Inc. All rights reserved.
*
* This software is licensed under the GNU General Public License v3 or later.
*
* It is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.cloud.agent.api.routing;
import com.cloud.network.FirewallRuleVO;
public class SetFirewallRuleCommand extends RoutingCommand {
FirewallRuleVO rule;
String routerName;
String routerIpAddress;
String oldPrivateIP = null;
String oldPrivatePort = null;
boolean create = false;
protected SetFirewallRuleCommand() {
}
public SetFirewallRuleCommand(String routerName, String routerIpAddress, FirewallRuleVO rule1, String oldPrivateIP, String oldPrivatePort) {
this.routerName = routerName;
this.routerIpAddress = routerIpAddress;
this.rule = new FirewallRuleVO(rule1);
this.oldPrivateIP = oldPrivateIP;
this.oldPrivatePort = oldPrivatePort;
}
public SetFirewallRuleCommand(String routerName, String routerIpAddress,FirewallRuleVO rule2, boolean create) {
this.routerName = routerName;
this.routerIpAddress = routerIpAddress;
this.rule = new FirewallRuleVO(rule2);
this.create = create;
}
@Override
public boolean executeInSequence() {
return false;
}
public FirewallRuleVO getRule() {
return rule;
}
public String getPrivateIpAddress() {
return rule.getPrivateIpAddress();
}
public String getPublicIpAddress() {
return rule.getPublicIpAddress();
}
public String getVlanNetmask() {
return rule.getVlanNetmask();
}
public String getPublicPort() {
return rule.getPublicPort();
}
public String getPrivatePort() {
return rule.getPrivatePort();
}
public String getRouterName() {
return routerName;
}
public String getRouterIpAddress() {
return routerIpAddress;
}
public boolean isEnable() {
return rule.isEnabled();
}
public String getProtocol() {
return rule.getProtocol();
}
public String getOldPrivateIP() {
return this.oldPrivateIP;
}
public String getOldPrivatePort() {
return this.oldPrivatePort;
}
// public boolean isNat(){
// return this.nat;
// }
public boolean isCreate() {
return create;
}
}

View File

@ -30,16 +30,14 @@ import java.net.InetSocketAddress;
import java.net.URL;
import java.net.URLConnection;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import javax.ejb.Local;
import javax.naming.ConfigurationException;
import org.apache.log4j.Logger;
import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.Command;
@ -50,11 +48,9 @@ import com.cloud.agent.api.routing.DhcpEntryCommand;
import com.cloud.agent.api.routing.IPAssocCommand;
import com.cloud.agent.api.routing.LoadBalancerCfgCommand;
import com.cloud.agent.api.routing.SavePasswordCommand;
import com.cloud.agent.api.routing.SetFirewallRuleCommand;
import com.cloud.agent.api.routing.VmDataCommand;
import com.cloud.utils.NumbersUtil;
import com.cloud.utils.component.Manager;
import com.cloud.utils.net.NetUtils;
import com.cloud.utils.script.OutputInterpreter;
import com.cloud.utils.script.Script;
@ -90,9 +86,10 @@ public class VirtualRoutingResource implements Manager {
public Answer executeRequest(final Command cmd) {
try {
if (cmd instanceof SetFirewallRuleCommand) {
return execute((SetFirewallRuleCommand)cmd);
}else if (cmd instanceof LoadBalancerCfgCommand) {
// if (cmd instanceof SetFirewallRuleCommand) {
// return execute((SetFirewallRuleCommand)cmd);
// }else
if (cmd instanceof LoadBalancerCfgCommand) {
return execute((LoadBalancerCfgCommand)cmd);
} else if (cmd instanceof IPAssocCommand) {
return execute((IPAssocCommand)cmd);
@ -216,7 +213,9 @@ public class VirtualRoutingResource implements Manager {
private String setLoadBalancerConfig(final String cfgFile,
final String[] addRules, final String[] removeRules, String routerIp) {
if (routerIp == null) routerIp = "none";
if (routerIp == null) {
routerIp = "none";
}
final Script command = new Script(_loadbPath, _timeout, s_logger);
@ -293,8 +292,9 @@ public class VirtualRoutingResource implements Manager {
final StringBuilder sb2 = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null)
sb2.append(line + "\n");
while ((line = reader.readLine()) != null) {
sb2.append(line + "\n");
}
result = sb2.toString();
} catch (final IOException e) {
success = false;
@ -377,8 +377,12 @@ public class VirtualRoutingResource implements Manager {
return null;
}
if (oldPrivateIP == null) oldPrivateIP = "";
if (oldPrivatePort == null) oldPrivatePort = "";
if (oldPrivateIP == null) {
oldPrivateIP = "";
}
if (oldPrivatePort == null) {
oldPrivatePort = "";
}
final Script command = new Script(_firewallPath, _timeout, s_logger);
@ -424,8 +428,9 @@ public class VirtualRoutingResource implements Manager {
String result = cmd.execute();
if (result != null) {
return false;
} else
return true;
} else {
return true;
}
}
private void stopDnsmasq(String dnsmasqName) {
@ -446,55 +451,56 @@ public class VirtualRoutingResource implements Manager {
}
protected Answer execute(final SetFirewallRuleCommand cmd) {
String args;
if(cmd.getProtocol().toLowerCase().equals(NetUtils.NAT_PROTO)){
//1:1 NAT needs instanceip;publicip;domrip;op
if(cmd.isCreate())
args = "-A";
else
args = "-D";
args += " -l " + cmd.getPublicIpAddress();
args += " -i " + cmd.getRouterIpAddress();
args += " -r " + cmd.getPrivateIpAddress();
args += " -G " + cmd.getProtocol();
}else{
if (cmd.isEnable()) {
args = "-A";
} else {
args = "-D";
}
args += " -P " + cmd.getProtocol().toLowerCase();
args += " -l " + cmd.getPublicIpAddress();
args += " -p " + cmd.getPublicPort();
args += " -n " + cmd.getRouterName();
args += " -i " + cmd.getRouterIpAddress();
args += " -r " + cmd.getPrivateIpAddress();
args += " -d " + cmd.getPrivatePort();
args += " -N " + cmd.getVlanNetmask();
String oldPrivateIP = cmd.getOldPrivateIP();
String oldPrivatePort = cmd.getOldPrivatePort();
if (oldPrivateIP != null) {
args += " -w " + oldPrivateIP;
}
if (oldPrivatePort != null) {
args += " -x " + oldPrivatePort;
}
}
final Script command = new Script(_firewallPath, _timeout, s_logger);
String [] argsArray = args.split(" ");
for (String param : argsArray) {
command.add(param);
}
String result = command.execute();
return new Answer(cmd, result == null, result);
}
// protected Answer execute(final SetFirewallRuleCommand cmd) {
// String args;
// if(cmd.getProtocol().toLowerCase().equals(NetUtils.NAT_PROTO)){
// //1:1 NAT needs instanceip;publicip;domrip;op
// if(cmd.isCreate()) {
// args = "-A";
// } else {
// args = "-D";
// }
//
// args += " -l " + cmd.getPublicIpAddress();
// args += " -i " + cmd.getRouterIpAddress();
// args += " -r " + cmd.getPrivateIpAddress();
// args += " -G " + cmd.getProtocol();
// }else{
// if (cmd.isEnable()) {
// args = "-A";
// } else {
// args = "-D";
// }
//
// args += " -P " + cmd.getProtocol().toLowerCase();
// args += " -l " + cmd.getPublicIpAddress();
// args += " -p " + cmd.getPublicPort();
// args += " -n " + cmd.getRouterName();
// args += " -i " + cmd.getRouterIpAddress();
// args += " -r " + cmd.getPrivateIpAddress();
// args += " -d " + cmd.getPrivatePort();
// args += " -N " + cmd.getVlanNetmask();
//
// String oldPrivateIP = cmd.getOldPrivateIP();
// String oldPrivatePort = cmd.getOldPrivatePort();
//
// if (oldPrivateIP != null) {
// args += " -w " + oldPrivateIP;
// }
//
// if (oldPrivatePort != null) {
// args += " -x " + oldPrivatePort;
// }
// }
//
// final Script command = new Script(_firewallPath, _timeout, s_logger);
// String [] argsArray = args.split(" ");
// for (String param : argsArray) {
// command.add(param);
// }
// String result = command.execute();
// return new Answer(cmd, result == null, result);
// }
protected String getDefaultScriptsDir() {
return "scripts/network/domr/dom0";
@ -510,13 +516,15 @@ public class VirtualRoutingResource implements Manager {
_scriptsDir = (String)params.get("domr.scripts.dir");
if (_scriptsDir == null) {
if(s_logger.isInfoEnabled())
s_logger.info("VirtualRoutingResource _scriptDir can't be initialized from domr.scripts.dir param, use default" );
if(s_logger.isInfoEnabled()) {
s_logger.info("VirtualRoutingResource _scriptDir can't be initialized from domr.scripts.dir param, use default" );
}
_scriptsDir = getDefaultScriptsDir();
}
if(s_logger.isInfoEnabled())
s_logger.info("VirtualRoutingResource _scriptDir to use: " + _scriptsDir);
if(s_logger.isInfoEnabled()) {
s_logger.info("VirtualRoutingResource _scriptDir to use: " + _scriptsDir);
}
String value = (String)params.get("scripts.timeout");
_timeout = NumbersUtil.parseInt(value, 120) * 1000;

View File

@ -133,7 +133,8 @@ import com.cloud.agent.api.routing.IPAssocCommand;
import com.cloud.agent.api.routing.LoadBalancerCfgCommand;
import com.cloud.agent.api.routing.RemoteAccessVpnCfgCommand;
import com.cloud.agent.api.routing.SavePasswordCommand;
import com.cloud.agent.api.routing.SetFirewallRuleCommand;
import com.cloud.agent.api.routing.SetPortForwardingRulesAnswer;
import com.cloud.agent.api.routing.SetPortForwardingRulesCommand;
import com.cloud.agent.api.routing.VmDataCommand;
import com.cloud.agent.api.routing.VpnUsersCfgCommand;
import com.cloud.agent.api.storage.CopyVolumeAnswer;
@ -142,11 +143,12 @@ import com.cloud.agent.api.storage.CreateAnswer;
import com.cloud.agent.api.storage.CreateCommand;
import com.cloud.agent.api.storage.CreatePrivateTemplateAnswer;
import com.cloud.agent.api.storage.DestroyCommand;
import com.cloud.agent.api.storage.PrimaryStorageDownloadCommand;
import com.cloud.agent.api.storage.PrimaryStorageDownloadAnswer;
import com.cloud.agent.api.storage.PrimaryStorageDownloadCommand;
import com.cloud.agent.api.storage.ShareAnswer;
import com.cloud.agent.api.storage.ShareCommand;
import com.cloud.agent.api.to.NicTO;
import com.cloud.agent.api.to.PortForwardingRuleTO;
import com.cloud.agent.api.to.StorageFilerTO;
import com.cloud.agent.api.to.VirtualMachineTO;
import com.cloud.agent.api.to.VirtualMachineTO.Monitor;
@ -463,8 +465,9 @@ public abstract class CitrixResourceBase implements StoragePoolResource, ServerR
continue;
}
if (vdir.VBDs == null)
if (vdir.VBDs == null) {
continue;
}
for (VBD vbd : vdir.VBDs) {
try {
@ -530,8 +533,8 @@ public abstract class CitrixResourceBase implements StoragePoolResource, ServerR
public Answer executeRequest(Command cmd) {
if (cmd instanceof CreateCommand) {
return execute((CreateCommand) cmd);
} else if (cmd instanceof SetFirewallRuleCommand) {
return execute((SetFirewallRuleCommand) cmd);
} else if (cmd instanceof SetPortForwardingRulesCommand) {
return execute((SetPortForwardingRulesCommand) cmd);
} else if (cmd instanceof LoadBalancerCfgCommand) {
return execute((LoadBalancerCfgCommand) cmd);
} else if (cmd instanceof IPAssocCommand) {
@ -1038,8 +1041,9 @@ public abstract class CitrixResourceBase implements StoragePoolResource, ServerR
String args = "-h " + computingHostIp;
String result = callHostPlugin("vmops", "pingtest", "args", args);
if (result == null || result.isEmpty())
if (result == null || result.isEmpty()) {
return false;
}
return true;
}
@ -1050,8 +1054,9 @@ public abstract class CitrixResourceBase implements StoragePoolResource, ServerR
private boolean doPingTest(final String domRIp, final String vmIp) {
String args = "-i " + domRIp + " -p " + vmIp;
String result = callHostPlugin("vmops", "pingtest", "args", args);
if (result == null || result.isEmpty())
if (result == null || result.isEmpty()) {
return false;
}
return true;
}
@ -1145,53 +1150,51 @@ public abstract class CitrixResourceBase implements StoragePoolResource, ServerR
}
}
protected Answer execute(final SetFirewallRuleCommand cmd) {
protected SetPortForwardingRulesAnswer execute(SetPortForwardingRulesCommand cmd) {
String args;
String routerIp = cmd.getAccessDetail("router.ip");
String routerName = cmd.getAccessDetail("router.name");
if(cmd.getProtocol().toLowerCase().equals(NetUtils.NAT_PROTO)){
//1:1 NAT needs instanceip;publicip;domrip;op
if(cmd.isCreate())
args = "-A";
else
args = "-D";
args += " -l " + cmd.getPublicIpAddress();
args += " -i " + cmd.getRouterIpAddress();
args += " -r " + cmd.getPrivateIpAddress();
args += " -G " + cmd.getProtocol();
}else{
if (cmd.isEnable()) {
args = "-A";
String[] results = new String[cmd.getRules().length];
int i = 0;
for (PortForwardingRuleTO rule : cmd.getRules()) {
if (rule.getProtocol().toLowerCase().equals(NetUtils.NAT_PROTO)){
//1:1 NAT needs instanceip;publicip;domrip;op
args = rule.revoked() ? "-D" : "-A";
args += " -l " + rule.getSrcIp();
args += " -i " + routerIp;
args += " -r " + rule.getDstIp();
args += " -G " + rule.getProtocol();
} else {
args = "-D";
args = rule.revoked() ? "-D" : "-A";
args += " -P " + rule.getProtocol().toLowerCase();
args += " -l " + rule.getSrcIp();
args += " -p " + rule.getSrcPortRange()[0];
args += " -n " + routerName;
args += " -i " + routerIp;
args += " -r " + rule.getDstIp();
args += " -d " + rule.getDstPortRange()[0];
args += " -N " + rule.getVlanNetmask();
// String oldPrivateIP = rule.getOldPrivateIP();
// String oldPrivatePort = rule.getOldPrivatePort();
//
// if (oldPrivateIP != null) {
// args += " -w " + oldPrivateIP;
// }
//
// if (oldPrivatePort != null) {
// args += " -x " + oldPrivatePort;
// }
}
args += " -P " + cmd.getProtocol().toLowerCase();
args += " -l " + cmd.getPublicIpAddress();
args += " -p " + cmd.getPublicPort();
args += " -n " + cmd.getRouterName();
args += " -i " + cmd.getRouterIpAddress();
args += " -r " + cmd.getPrivateIpAddress();
args += " -d " + cmd.getPrivatePort();
args += " -N " + cmd.getVlanNetmask();
String oldPrivateIP = cmd.getOldPrivateIP();
String oldPrivatePort = cmd.getOldPrivatePort();
if (oldPrivateIP != null) {
args += " -w " + oldPrivateIP;
}
if (oldPrivatePort != null) {
args += " -x " + oldPrivatePort;
}
String result = callHostPlugin("vmops", "setFirewallRule", "args", args);
results[i++] = (result == null || result.isEmpty()) ? "Failed" : null;
}
String result = callHostPlugin("vmops", "setFirewallRule", "args", args);
if (result == null || result.isEmpty()) {
return new Answer(cmd, false, "SetFirewallRule failed");
}
return new Answer(cmd);
return new SetPortForwardingRulesAnswer(cmd, results);
}
protected Answer execute(final LoadBalancerCfgCommand cmd) {
@ -1623,8 +1626,9 @@ public abstract class CitrixResourceBase implements StoragePoolResource, ServerR
}
HashMap<String, VmStatsEntry> vmStatsUUIDMap = getVmStats(cmd, vmUUIDs, cmd.getHostGuid());
if( vmStatsUUIDMap == null )
if( vmStatsUUIDMap == null ) {
return new GetVmStatsAnswer(cmd, vmStatsNameMap);
}
for (String vmUUID : vmStatsUUIDMap.keySet()) {
vmStatsNameMap.put(vmNames.get(vmUUIDs.indexOf(vmUUID)), vmStatsUUIDMap.get(vmUUID));
@ -1720,10 +1724,12 @@ public abstract class CitrixResourceBase implements StoragePoolResource, ServerR
String stats = "";
try {
if (flag == 1)
if (flag == 1) {
stats = getHostStatsRawXML();
if (flag == 2)
}
if (flag == 2) {
stats = getVmStatsRawXML();
}
} catch (Exception e1) {
s_logger.warn("Error whilst collecting raw stats from plugin:" + e1);
return null;
@ -1733,8 +1739,9 @@ public abstract class CitrixResourceBase implements StoragePoolResource, ServerR
// s_logger.debug("Length of raw xml is:"+stats.length());
//stats are null when the host plugin call fails (host down state)
if(stats == null)
return null;
if(stats == null) {
return null;
}
StringReader statsReader = new StringReader(stats);
InputSource statsSource = new InputSource(statsReader);
@ -2073,8 +2080,9 @@ public abstract class CitrixResourceBase implements StoragePoolResource, ServerR
int index = tmplturl.lastIndexOf("/");
String mountpoint = tmplturl.substring(0, index);
String tmpltname = null;
if (index < tmplturl.length() - 1)
if (index < tmplturl.length() - 1) {
tmpltname = tmplturl.substring(index + 1).replace(".vhd", "");
}
try {
Connection conn = getConnection();
String pUuid = cmd.getPoolUuid();
@ -2293,8 +2301,9 @@ public abstract class CitrixResourceBase implements StoragePoolResource, ServerR
}
VMGuestMetrics vmmetric = vm.getGuestMetrics(conn);
if (isRefNull(vmmetric))
if (isRefNull(vmmetric)) {
continue;
}
Map<String, String> PVversion = vmmetric.getPVDriversVersion(conn);
if (PVversion != null && PVversion.containsKey("major")) {
@ -2937,7 +2946,9 @@ public abstract class CitrixResourceBase implements StoragePoolResource, ServerR
vifr.device = devNum;
vifr.MAC = mac;
vifr.network = network;
if ( rate == 0 ) rate = 200;
if ( rate == 0 ) {
rate = 200;
}
vifr.qosAlgorithmType = "ratelimit";
vifr.qosAlgorithmParams = new HashMap<String, String>();
// convert mbs to kilobyte per second
@ -2972,12 +2983,15 @@ public abstract class CitrixResourceBase implements StoragePoolResource, ServerR
// stop vm which is running on this host or is in halted state
for (VM vm : vms) {
VM.Record vmr = vm.getRecord(conn);
if (vmr.powerState != VmPowerState.RUNNING)
if (vmr.powerState != VmPowerState.RUNNING) {
continue;
if (isRefNull(vmr.residentOn))
}
if (isRefNull(vmr.residentOn)) {
continue;
if (vmr.residentOn.getUuid(conn).equals(_host.uuid))
}
if (vmr.residentOn.getUuid(conn).equals(_host.uuid)) {
continue;
}
vms.remove(vm);
}
@ -3143,8 +3157,9 @@ public abstract class CitrixResourceBase implements StoragePoolResource, ServerR
if (s_logger.isDebugEnabled()) {
s_logger.debug("Trying to connect to " + ipAddress);
}
if (pingdomr(ipAddress, Integer.toString(port)))
if (pingdomr(ipAddress, Integer.toString(port))) {
return null;
}
try {
Thread.sleep(_sleep);
} catch (final InterruptedException e) {
@ -3288,8 +3303,9 @@ public abstract class CitrixResourceBase implements StoragePoolResource, ServerR
String pvargs = vm.getPVArgs(conn);
pvargs = pvargs + bootArgs;
if (s_logger.isInfoEnabled())
if (s_logger.isInfoEnabled()) {
s_logger.info("PV args for system vm are " + pvargs);
}
vm.setPVArgs(conn, pvargs);
/* destroy console */
@ -3313,8 +3329,9 @@ public abstract class CitrixResourceBase implements StoragePoolResource, ServerR
}
}
if (s_logger.isInfoEnabled())
if (s_logger.isInfoEnabled()) {
s_logger.info("Ping system vm command port, " + privateIp + ":" + cmdPort);
}
state = State.Running;
String result = connect(vmName, privateIp, cmdPort);
@ -3323,8 +3340,9 @@ public abstract class CitrixResourceBase implements StoragePoolResource, ServerR
s_logger.warn(msg);
throw new CloudRuntimeException(msg);
} else {
if (s_logger.isInfoEnabled())
if (s_logger.isInfoEnabled()) {
s_logger.info("Ping system vm command port succeeded for vm " + vmName);
}
}
return null;
@ -3402,8 +3420,9 @@ public abstract class CitrixResourceBase implements StoragePoolResource, ServerR
try {
Connection conn = getConnection();
Set<String> allowedVBDDevices = vm.getAllowedVBDDevices(conn);
if (allowedVBDDevices.size() == 0)
if (allowedVBDDevices.size() == 0) {
throw new CloudRuntimeException("Could not find an available slot in VM with name: " + vm.getNameLabel(conn) + " to attach a new disk.");
}
return allowedVBDDevices.iterator().next();
} catch (XmlRpcException e) {
String msg = "Catch XmlRpcException due to: " + e.getMessage();
@ -3457,8 +3476,9 @@ public abstract class CitrixResourceBase implements StoragePoolResource, ServerR
protected boolean setIptables() {
String result = callHostPlugin("vmops", "setIptables");
if (result == null || result.isEmpty())
if (result == null || result.isEmpty()) {
return false;
}
return true;
}
@ -3813,8 +3833,9 @@ public abstract class CitrixResourceBase implements StoragePoolResource, ServerR
Connection conn = getConnection();
String lvmuuid = lvmsr.getUuid(conn);
long cap = lvmsr.getPhysicalSize(conn);
if (cap < 0)
if (cap < 0) {
return null;
}
long avail = cap - lvmsr.getPhysicalUtilisation(conn);
lvmsr.setNameLabel(conn, lvmuuid);
String name = "VMOps local storage pool in host : " + _host.uuid;
@ -4585,8 +4606,9 @@ public abstract class CitrixResourceBase implements StoragePoolResource, ServerR
_guestNetworkName = (String)params.get("guest.network.device");
_linkLocalPrivateNetworkName = (String) params.get("private.linkLocal.device");
if (_linkLocalPrivateNetworkName == null)
if (_linkLocalPrivateNetworkName == null) {
_linkLocalPrivateNetworkName = "cloud_link_local_network";
}
_storageNetworkName1 = (String) params.get("storage.network.device1");
if (_storageNetworkName1 == null) {
@ -4853,28 +4875,34 @@ public abstract class CitrixResourceBase implements StoragePoolResource, ServerR
Set<SR> srs = SR.getByNameLabel(conn, pool.getUuid());
for (SR sr : srs) {
if (!SRType.LVMOISCSI.equals(sr.getType(conn)))
if (!SRType.LVMOISCSI.equals(sr.getType(conn))) {
continue;
}
Set<PBD> pbds = sr.getPBDs(conn);
if (pbds.isEmpty())
if (pbds.isEmpty()) {
continue;
}
PBD pbd = pbds.iterator().next();
Map<String, String> dc = pbd.getDeviceConfig(conn);
if (dc == null)
if (dc == null) {
continue;
}
if (dc.get("target") == null)
if (dc.get("target") == null) {
continue;
}
if (dc.get("targetIQN") == null)
if (dc.get("targetIQN") == null) {
continue;
}
if (dc.get("lunid") == null)
if (dc.get("lunid") == null) {
continue;
}
if (target.equals(dc.get("target")) && targetiqn.equals(dc.get("targetIQN")) && lunid.equals(dc.get("lunid"))) {
if (checkSR(sr)) {
@ -4950,25 +4978,30 @@ public abstract class CitrixResourceBase implements StoragePoolResource, ServerR
serverpath = serverpath.replace("//", "/");
Set<SR> srs = SR.getAll(conn);
for (SR sr : srs) {
if (!SRType.NFS.equals(sr.getType(conn)))
if (!SRType.NFS.equals(sr.getType(conn))) {
continue;
}
Set<PBD> pbds = sr.getPBDs(conn);
if (pbds.isEmpty())
if (pbds.isEmpty()) {
continue;
}
PBD pbd = pbds.iterator().next();
Map<String, String> dc = pbd.getDeviceConfig(conn);
if (dc == null)
if (dc == null) {
continue;
}
if (dc.get("server") == null)
if (dc.get("server") == null) {
continue;
}
if (dc.get("serverpath") == null)
if (dc.get("serverpath") == null) {
continue;
}
if (server.equals(dc.get("server")) && serverpath.equals(dc.get("serverpath"))) {
if (checkSR(sr)) {
@ -5170,10 +5203,11 @@ public abstract class CitrixResourceBase implements StoragePoolResource, ServerR
VM vm = getVM(conn, vmName);
/* For HVM guest, if no pv driver installed, no attach/detach */
boolean isHVM;
if (vm.getPVBootloader(conn).equalsIgnoreCase(""))
if (vm.getPVBootloader(conn).equalsIgnoreCase("")) {
isHVM = true;
else
} else {
isHVM = false;
}
VMGuestMetrics vgm = vm.getGuestMetrics(conn);
boolean pvDrvInstalled = false;
if (!isRefNull(vgm) && vgm.getPVDriversUpToDate(conn)) {
@ -5813,12 +5847,14 @@ public abstract class CitrixResourceBase implements StoragePoolResource, ServerR
}
// If there are no VMs, throw an exception
if (vms.size() == 0)
if (vms.size() == 0) {
throw new CloudRuntimeException("VM with name: " + vmName + " does not exist.");
}
// If there is more than one VM, print a warning
if (vms.size() > 1)
if (vms.size() > 1) {
s_logger.warn("Found " + vms.size() + " VMs with name: " + vmName);
}
// Return the first VM in the set
return vms.iterator().next();
@ -5892,12 +5928,13 @@ public abstract class CitrixResourceBase implements StoragePoolResource, ServerR
throw new CloudRuntimeException("SR check failed for storage pool: " + pool.getUuid() + "on host:" + _host.uuid);
} else {
if (pool.getType() == StoragePoolType.NetworkFilesystem)
return getNfsSR(pool);
else if (pool.getType() == StoragePoolType.IscsiLUN)
return getIscsiSR(pool);
else
throw new CloudRuntimeException("The pool type: " + pool.getType().name() + " is not supported.");
if (pool.getType() == StoragePoolType.NetworkFilesystem) {
return getNfsSR(pool);
} else if (pool.getType() == StoragePoolType.IscsiLUN) {
return getIscsiSR(pool);
} else {
throw new CloudRuntimeException("The pool type: " + pool.getType().name() + " is not supported.");
}
}
}
@ -5930,8 +5967,9 @@ public abstract class CitrixResourceBase implements StoragePoolResource, ServerR
final StringBuilder sb2 = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null)
while ((line = reader.readLine()) != null) {
sb2.append(line + "\n");
}
result = sb2.toString();
} catch (final IOException e) {
success = false;

View File

@ -1,186 +0,0 @@
/**
* Copyright (C) 2010 Cloud.com, Inc. All rights reserved.
*
* This software is licensed under the GNU General Public License v3 or later.
*
* It is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.cloud.network;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
import com.cloud.network.rules.FirewallRule;
/**
* A bean representing a IP Forwarding
*
* @author Will Chan
*
*/
@Entity
@Table(name=("ip_forwarding"))
public class FirewallRuleVO implements FirewallRule {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
private long id;
@Column(name="group_id")
private Long groupId;
@Column(name="public_ip_address")
private String publicIpAddress = null;
@Column(name="public_port")
private String publicPort = null;
@Column(name="private_ip_address")
private String privateIpAddress = null;
@Column(name="private_port")
private String privatePort = null;
@Column(name="enabled")
private boolean enabled = false;
@Column(name="protocol")
private String protocol = "TCP";
@Column(name="forwarding")
private boolean forwarding = true;
@Column(name="algorithm")
private String algorithm = null;
@Transient
private String vlanNetmask;
public FirewallRuleVO() {
}
public FirewallRuleVO(Long groupId, String publicIpAddress, String publicPort, String privateIpAddress, String privatePort, boolean enabled, String protocol,
boolean forwarding, String algorithm) {
this.groupId = groupId;
this.publicIpAddress = publicIpAddress;
this.publicPort = publicPort;
this.privateIpAddress = privateIpAddress;
this.privatePort = privatePort;
this.enabled = enabled;
this.protocol = protocol;
this.forwarding = forwarding;
}
public FirewallRuleVO(FirewallRuleVO fwRule) {
this(fwRule.getGroupId(), fwRule.getPublicIpAddress(),
fwRule.getPublicPort(), fwRule.getPrivateIpAddress(),
fwRule.getPrivatePort(), fwRule.isEnabled(), fwRule.getProtocol(),
fwRule.isForwarding(), fwRule.getAlgorithm());
id = fwRule.id;
}
@Override
public long getId() {
return id;
}
@Override
public String getXid() {
return Long.toHexString(id);
}
public Long getGroupId() {
return groupId;
}
public void setGroupId(Long groupId) {
this.groupId = groupId;
}
@Override
public String getPublicIpAddress() {
return publicIpAddress;
}
public void setPublicIpAddress(String address) {
this.publicIpAddress = address;
}
@Override
public String getPublicPort() {
return publicPort;
}
public void setPublicPort(String port) {
this.publicPort = port;
}
@Override
public String getPrivateIpAddress() {
return privateIpAddress;
}
public void setPrivateIpAddress(String privateIpAddress) {
this.privateIpAddress = privateIpAddress;
}
@Override
public String getPrivatePort() {
return privatePort;
}
public void setPrivatePort(String privatePort) {
this.privatePort = privatePort;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
@Override
public String getProtocol() {
return this.protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol.toLowerCase();
}
public boolean isForwarding() {
return forwarding;
}
public void setForwarding(boolean forwarding) {
this.forwarding = forwarding;
}
public String getAlgorithm() {
return algorithm;
}
public void setAlgorithm(String algorithm) {
this.algorithm = algorithm;
}
public void setVlanNetmask(String vlanNetmask) {
this.vlanNetmask = vlanNetmask;
}
public String getVlanNetmask() {
return vlanNetmask;
}
}

View File

@ -19,6 +19,8 @@ package com.cloud.network;
import java.util.List;
import com.cloud.agent.api.to.PortForwardingRuleTO;
/**
* @author chiradeep
@ -28,6 +30,6 @@ public interface LoadBalancerConfigurator {
public final static int ADD = 0;
public final static int REMOVE = 1;
public String [] generateConfiguration(List<FirewallRuleVO> fwRules);
public String [][] generateFwRules(List<FirewallRuleVO> fwRules);
public String [] generateConfiguration(List<PortForwardingRuleTO> fwRules);
public String [][] generateFwRules(List<PortForwardingRuleTO> fwRules);
}

View File

@ -484,7 +484,7 @@ public class ApiDBUtils {
}
public static Network getNetwork(long id) {
return _networkMgr.getNetworkConfiguration(id);
return _networkMgr.getNetwork(id);
}
public static void synchronizeCommand(Object job, String syncObjType, long syncObjId) {

View File

@ -74,7 +74,6 @@ import com.cloud.api.response.VpnUsersResponse;
import com.cloud.api.response.ZoneResponse;
import com.cloud.async.AsyncJob;
import com.cloud.async.AsyncJobResult;
import com.cloud.async.AsyncJobVO;
import com.cloud.async.executor.IngressRuleResultObject;
import com.cloud.async.executor.NetworkGroupResultObject;
import com.cloud.capacity.Capacity;
@ -97,12 +96,12 @@ import com.cloud.host.Host;
import com.cloud.host.HostStats;
import com.cloud.host.HostVO;
import com.cloud.network.IpAddress;
import com.cloud.network.LoadBalancer;
import com.cloud.network.Network;
import com.cloud.network.RemoteAccessVpn;
import com.cloud.network.VpnUser;
import com.cloud.network.router.VirtualRouter;
import com.cloud.network.rules.FirewallRule;
import com.cloud.network.rules.LoadBalancer;
import com.cloud.network.rules.PortForwardingRule;
import com.cloud.network.security.IngressRule;
import com.cloud.network.security.NetworkGroup;
import com.cloud.network.security.NetworkGroupRules;
@ -807,9 +806,9 @@ public class ApiResponseHelper implements ResponseGenerator {
lbResponse.setId(loadBalancer.getId());
lbResponse.setName(loadBalancer.getName());
lbResponse.setDescription(loadBalancer.getDescription());
lbResponse.setPublicIp(loadBalancer.getIpAddress());
lbResponse.setPublicPort(loadBalancer.getPublicPort());
lbResponse.setPrivatePort(loadBalancer.getPrivatePort());
lbResponse.setPublicIp(loadBalancer.getSourceIpAddress().toString());
lbResponse.setPublicPort(Integer.toString(loadBalancer.getSourcePortStart()));
lbResponse.setPrivatePort(Integer.toString(loadBalancer.getDefaultPortStart()));
lbResponse.setAlgorithm(loadBalancer.getAlgorithm());
Account accountTemp = ApiDBUtils.findAccountById(loadBalancer.getAccountId());
@ -1050,15 +1049,15 @@ public class ApiResponseHelper implements ResponseGenerator {
}
@Override
public FirewallRuleResponse createFirewallRuleResponse(FirewallRule fwRule) {
public FirewallRuleResponse createFirewallRuleResponse(PortForwardingRule fwRule) {
FirewallRuleResponse response = new FirewallRuleResponse();
response.setId(fwRule.getId());
response.setPrivatePort(fwRule.getPrivatePort());
response.setPrivatePort(Integer.toString(fwRule.getDestinationPortStart()));
response.setProtocol(fwRule.getProtocol());
response.setPublicPort(fwRule.getPublicPort());
response.setPublicIpAddress(fwRule.getPublicIpAddress());
if (fwRule.getPublicIpAddress() != null && fwRule.getPrivateIpAddress() != null) {
UserVm vm = ApiDBUtils.findUserVmByPublicIpAndGuestIp(fwRule.getPublicIpAddress(), fwRule.getPrivateIpAddress());
response.setPublicPort(Integer.toString(fwRule.getSourcePortStart()));
response.setPublicIpAddress(fwRule.getSourceIpAddress().toString());
if (fwRule.getSourceIpAddress() != null && fwRule.getDestinationIpAddress() != null) {
UserVm vm = ApiDBUtils.findUserVmByPublicIpAndGuestIp(fwRule.getSourceIpAddress().toString(), fwRule.getDestinationIpAddress().toString());
if(vm != null){
response.setVirtualMachineId(vm.getId());
response.setVirtualMachineName(vm.getHostName());
@ -1070,13 +1069,13 @@ public class ApiResponseHelper implements ResponseGenerator {
}
@Override
public IpForwardingRuleResponse createIpForwardingRuleResponse(FirewallRule fwRule) {
public IpForwardingRuleResponse createIpForwardingRuleResponse(PortForwardingRule fwRule) {
IpForwardingRuleResponse response = new IpForwardingRuleResponse();
response.setId(fwRule.getId());
response.setProtocol(fwRule.getProtocol());
response.setPublicIpAddress(fwRule.getPublicIpAddress());
if (fwRule.getPublicIpAddress() != null && fwRule.getPrivateIpAddress() != null) {
UserVm vm = ApiDBUtils.findUserVmByPublicIpAndGuestIp(fwRule.getPublicIpAddress(), fwRule.getPrivateIpAddress());
response.setPublicIpAddress(fwRule.getSourceIpAddress().addr());
if (fwRule.getSourceIpAddress() != null && fwRule.getDestinationIpAddress() != null) {
UserVm vm = ApiDBUtils.findUserVmByPublicIpAndGuestIp(fwRule.getSourceIpAddress().addr(), fwRule.getDestinationIpAddress().addr());
if(vm != null){//vm might be destroyed
response.setVirtualMachineId(vm.getId());
response.setVirtualMachineName(vm.getHostName());

View File

@ -1,79 +0,0 @@
package com.cloud.async.executor;
import org.apache.log4j.Logger;
import com.cloud.api.BaseCmd;
import com.cloud.async.AsyncJobManager;
import com.cloud.async.AsyncJobResult;
import com.cloud.async.AsyncJobVO;
import com.cloud.async.BaseAsyncJobExecutor;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.network.LoadBalancerVO;
import com.cloud.serializer.GsonHelper;
import com.cloud.server.ManagementServer;
import com.cloud.user.Account;
import com.google.gson.Gson;
public class UpdateLoadBalancerRuleExecutor extends BaseAsyncJobExecutor {
public static final Logger s_logger = Logger.getLogger(UpdateLoadBalancerRuleExecutor.class.getName());
@Override
public boolean execute() {
/*
if (getSyncSource() == null) {
Gson gson = GsonHelper.getBuilder().create();
AsyncJobManager asyncMgr = getAsyncJobMgr();
AsyncJobVO job = getJob();
UpdateLoadBalancerParam param = gson.fromJson(job.getCmdInfo(), UpdateLoadBalancerParam.class);
asyncMgr.syncAsyncJobExecution(job.getId(), "LoadBalancer", param.getLoadBalancerId()); // in reality I need to synchronize on both the load balancer and domR
// always true if it does not have sync-source
return true;
} else {
Gson gson = GsonHelper.getBuilder().create();
AsyncJobManager asyncMgr = getAsyncJobMgr();
AsyncJobVO job = getJob();
UpdateLoadBalancerParam param = gson.fromJson(job.getCmdInfo(), UpdateLoadBalancerParam.class);
ManagementServer ms = asyncMgr.getExecutorContext().getManagementServer();
LoadBalancerVO loadBalancer = ms.findLoadBalancerById(param.getLoadBalancerId());
try {
loadBalancer = ms.updateLoadBalancerRule(loadBalancer, param.getName(), param.getDescription());
loadBalancer = ms.updateLoadBalancerRule(param.getUserId(), loadBalancer, param.getPrivatePort(), param.getAlgorithm());
getAsyncJobMgr().completeAsyncJob(job.getId(), AsyncJobResult.STATUS_SUCCEEDED, 0, composeResultObject(ms, loadBalancer));
} catch (InvalidParameterValueException ex) {
getAsyncJobMgr().completeAsyncJob(job.getId(), AsyncJobResult.STATUS_FAILED, BaseCmd.PARAM_ERROR, ex.getMessage());
} catch (Exception ex) {
s_logger.error("Unhandled exception updating load balancer rule", ex);
getAsyncJobMgr().completeAsyncJob(job.getId(), AsyncJobResult.STATUS_FAILED, BaseCmd.INTERNAL_ERROR, "Internal error updating load balancer rule " + loadBalancer.getName());
}
return true;
}
*/
return true;
}
private UpdateLoadBalancerRuleResultObject composeResultObject(ManagementServer ms, LoadBalancerVO loadBalancer) {
UpdateLoadBalancerRuleResultObject resultObject = new UpdateLoadBalancerRuleResultObject();
resultObject.setId(loadBalancer.getId());
resultObject.setName(loadBalancer.getName());
resultObject.setDescription(loadBalancer.getDescription());
resultObject.setPublicIp(loadBalancer.getIpAddress());
resultObject.setPublicPort(loadBalancer.getPublicPort());
resultObject.setPrivatePort(loadBalancer.getPrivatePort());
resultObject.setAlgorithm(loadBalancer.getAlgorithm());
Account accountTemp = ms.findAccountById(loadBalancer.getAccountId());
if (accountTemp != null) {
resultObject.setAccountName(accountTemp.getAccountName());
resultObject.setDomainId(accountTemp.getDomainId());
// resultObject.setDomainName(ms.findDomainIdById(accountTemp.getDomainId()).getName());
}
return resultObject;
}
}

View File

@ -1,93 +0,0 @@
package com.cloud.async.executor;
import java.util.List;
import org.apache.log4j.Logger;
import com.cloud.api.BaseCmd;
import com.cloud.async.AsyncJobManager;
import com.cloud.async.AsyncJobResult;
import com.cloud.async.AsyncJobVO;
import com.cloud.async.BaseAsyncJobExecutor;
import com.cloud.network.FirewallRuleVO;
import com.cloud.network.IPAddressVO;
import com.cloud.serializer.GsonHelper;
import com.cloud.server.Criteria;
import com.cloud.server.ManagementServer;
import com.cloud.vm.DomainRouterVO;
import com.cloud.vm.UserVmVO;
import com.google.gson.Gson;
public class UpdatePortForwardingRuleExecutor extends BaseAsyncJobExecutor {
public static final Logger s_logger = Logger.getLogger(UpdatePortForwardingRuleExecutor.class.getName());
@Override
public boolean execute() {
/*
if (getSyncSource() == null) {
Gson gson = GsonHelper.getBuilder().create();
AsyncJobManager asyncMgr = getAsyncJobMgr();
AsyncJobVO job = getJob();
CreateOrUpdateRuleParam param = gson.fromJson(job.getCmdInfo(), CreateOrUpdateRuleParam.class);
ManagementServer ms = asyncMgr.getExecutorContext().getManagementServer();
IPAddressVO ipAddr = ms.findIPAddressById(param.getAddress());
DomainRouterVO router = ms.findDomainRouterBy(ipAddr.getAccountId(), ipAddr.getDataCenterId());
asyncMgr.syncAsyncJobExecution(job, "Router", router.getId()); // synchronize on the router
// always true if it does not have sync-source
return true;
} else {
Gson gson = GsonHelper.getBuilder().create();
AsyncJobManager asyncMgr = getAsyncJobMgr();
AsyncJobVO job = getJob();
CreateOrUpdateRuleParam param = gson.fromJson(job.getCmdInfo(), CreateOrUpdateRuleParam.class);
ManagementServer ms = asyncMgr.getExecutorContext().getManagementServer();
try {
FirewallRuleVO fwRule = ms.updatePortForwardingRule(param.getUserId(), param.getAddress(), param.getPrivateIpAddress(), param.getPort(), param.getPrivatePort(), param.getProtocol());
if (fwRule != null) {
getAsyncJobMgr().completeAsyncJob(job.getId(), AsyncJobResult.STATUS_SUCCEEDED, 0, composeResultObject(ms, fwRule));
} else {
getAsyncJobMgr().completeAsyncJob(job.getId(), AsyncJobResult.STATUS_FAILED, BaseCmd.INTERNAL_ERROR, "Internal error updating forwarding rule for address " + param.getAddress());
}
} catch (Exception ex) {
s_logger.error("Unhandled exception updating port forwarding rule", ex);
getAsyncJobMgr().completeAsyncJob(job.getId(), AsyncJobResult.STATUS_FAILED, BaseCmd.INTERNAL_ERROR, "Internal error updating forwarding rule for address " + param.getAddress());
}
return true;
}
*/
return true;
}
private UpdatePortForwardingRuleResultObject composeResultObject(ManagementServer ms, FirewallRuleVO firewallRule) {
UpdatePortForwardingRuleResultObject resultObject = new UpdatePortForwardingRuleResultObject();
IPAddressVO ipAddressVO = ms.findIPAddressById(firewallRule.getPublicIpAddress());
Criteria c = new Criteria();
c.addCriteria(Criteria.ACCOUNTID, new Object[] {ipAddressVO.getAccountId()});
c.addCriteria(Criteria.DATACENTERID, ipAddressVO.getDataCenterId());
c.addCriteria(Criteria.IPADDRESS, firewallRule.getPrivateIpAddress());
List<UserVmVO> userVMs = ms.searchForUserVMs(c);
if ((userVMs != null) && (userVMs.size() > 0)) {
UserVmVO userVM = userVMs.get(0);
resultObject.setVirtualMachineId(userVM.getId());
resultObject.setVirtualMachineName(userVM.getHostName());
resultObject.setVirtualMachineDisplayName(userVM.getDisplayName());
}
resultObject.setId(firewallRule.getId());
resultObject.setPublicIp(firewallRule.getPublicIpAddress());
resultObject.setPrivateIp(firewallRule.getPrivateIpAddress());
resultObject.setPublicPort(firewallRule.getPublicPort());
resultObject.setPrivatePort(firewallRule.getPrivatePort());
resultObject.setProtocol(firewallRule.getProtocol());
return resultObject;
}
}

View File

@ -41,6 +41,7 @@ import com.cloud.configuration.dao.ConfigurationDaoImpl;
import com.cloud.configuration.dao.ResourceCountDaoImpl;
import com.cloud.configuration.dao.ResourceLimitDaoImpl;
import com.cloud.consoleproxy.AgentBasedStandaloneConsoleProxyManager;
import com.cloud.dao.EntityManager;
import com.cloud.dao.EntityManagerImpl;
import com.cloud.dc.dao.AccountVlanMapDaoImpl;
import com.cloud.dc.dao.ClusterDaoImpl;
@ -60,6 +61,7 @@ import com.cloud.maid.dao.StackMaidDaoImpl;
import com.cloud.maint.UpgradeManagerImpl;
import com.cloud.maint.dao.AgentUpgradeDaoImpl;
import com.cloud.network.NetworkManagerImpl;
import com.cloud.network.dao.FirewallRulesDao;
import com.cloud.network.dao.FirewallRulesDaoImpl;
import com.cloud.network.dao.IPAddressDaoImpl;
import com.cloud.network.dao.LoadBalancerDaoImpl;
@ -68,6 +70,7 @@ import com.cloud.network.dao.NetworkDaoImpl;
import com.cloud.network.dao.NetworkRuleConfigDaoImpl;
import com.cloud.network.dao.RemoteAccessVpnDaoImpl;
import com.cloud.network.dao.VpnUserDaoImpl;
import com.cloud.network.lb.LoadBalancingRulesManagerImpl;
import com.cloud.network.router.DomainRouterManagerImpl;
import com.cloud.network.security.NetworkGroupManagerImpl;
import com.cloud.network.security.dao.IngressRuleDaoImpl;
@ -126,7 +129,7 @@ import com.cloud.vm.dao.VMInstanceDaoImpl;
public class DefaultComponentLibrary implements ComponentLibrary {
protected final Map<String, ComponentInfo<GenericDao<?, ? extends Serializable>>> _daos = new LinkedHashMap<String, ComponentInfo<GenericDao<?, ?>>>();
protected final Map<String, ComponentInfo<GenericDao<?, ? extends Serializable>>> _daos = new LinkedHashMap<String, ComponentInfo<GenericDao<?, ? extends Serializable>>>();
protected ComponentInfo<? extends GenericDao<?, ? extends Serializable>> addDao(String name, Class<? extends GenericDao<?, ? extends Serializable>> clazz) {
return addDao(name, clazz, new ArrayList<Pair<String, Object>>(), true);
@ -223,6 +226,7 @@ public class DefaultComponentLibrary implements ComponentLibrary {
addDao("RemoteAccessVpnDao", RemoteAccessVpnDaoImpl.class);
addDao("VpnUserDao", VpnUserDaoImpl.class);
addDao("ItWorkDao", ItWorkDaoImpl.class);
addDao("FirewallRulesDao", FirewallRulesDao.class);
}
Map<String, ComponentInfo<Manager>> _managers = new HashMap<String, ComponentInfo<Manager>>();
@ -274,6 +278,7 @@ public class DefaultComponentLibrary implements ComponentLibrary {
addManager("VmManager", MauriceMoss.class);
addManager("DomainRouterManager", DomainRouterManagerImpl.class);
addManager("EntityManager", EntityManagerImpl.class);
addManager("LoadBalancingRulesManager", LoadBalancingRulesManagerImpl.class);
}
protected <T> List<ComponentInfo<Adapter>> addAdapterChain(Class<T> interphace, List<Pair<String, Class<? extends T>>> adapters) {
@ -311,4 +316,11 @@ public class DefaultComponentLibrary implements ComponentLibrary {
}
return _adapters;
}
@Override
public synchronized Map<Class<?>, Class<?>> getFactories() {
HashMap<Class<?>, Class<?>> factories = new HashMap<Class<?>, Class<?>>();
factories.put(EntityManager.class, EntityManagerImpl.class);
return factories;
}
}

View File

@ -24,6 +24,8 @@ import java.util.Map;
import javax.ejb.Local;
import javax.naming.ConfigurationException;
import net.sf.ehcache.Cache;
import com.cloud.utils.component.Manager;
import com.cloud.utils.db.GenericDao;
import com.cloud.utils.db.GenericDaoBase;
@ -35,7 +37,8 @@ import com.cloud.utils.db.SearchCriteria;
@SuppressWarnings("unchecked")
public class EntityManagerImpl implements EntityManager, Manager {
String _name;
Cache _cache;
@Override
public <T, K extends Serializable> T findById(Class<T> entityType, K id) {
GenericDao<? extends T, K> dao = (GenericDao<? extends T, K>)GenericDaoBase.getDao(entityType);
@ -74,9 +77,25 @@ public class EntityManagerImpl implements EntityManager, Manager {
@Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
_name = name;
/*
String threadId = Long.toString(Thread.currentThread().getId());
CacheManager cm = CacheManager.create();
_cache = cm.getCache(threadId);
if (_cache == null) {
int maxElements = NumbersUtil.parseInt((String)params.get("cache.size"), 100);
int live = NumbersUtil.parseInt((String)params.get("cache.time.to.live"), 300);
int idle = NumbersUtil.parseInt((String)params.get("cache.time.to.idle"), 300);
_cache = new Cache(threadId, maxElements, false, live == -1, live == -1 ? Integer.MAX_VALUE : live, idle);
cm.addCache(_cache);
}*/
return true;
}
}
@Override
public boolean start() {

View File

@ -25,6 +25,7 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import com.cloud.agent.api.to.PortForwardingRuleTO;
import com.cloud.utils.net.NetUtils;
@ -64,17 +65,17 @@ public class HAProxyConfigurator implements LoadBalancerConfigurator {
};
@Override
public String[] generateConfiguration(List<FirewallRuleVO> fwRules) {
public String[] generateConfiguration(List<PortForwardingRuleTO> fwRules) {
//Group the rules by publicip:publicport
Map<String, List<FirewallRuleVO>> pools = new HashMap<String, List<FirewallRuleVO>>();
Map<String, List<PortForwardingRuleTO>> pools = new HashMap<String, List<PortForwardingRuleTO>>();
for(FirewallRuleVO rule:fwRules) {
for(PortForwardingRuleTO rule:fwRules) {
StringBuilder sb = new StringBuilder();
String poolName = sb.append(rule.getPublicIpAddress().replace(".", "_")).append('-').append(rule.getPublicPort()).toString();
if (rule.isEnabled() && !rule.isForwarding()) {
List<FirewallRuleVO> fwList = pools.get(poolName);
String poolName = sb.append(rule.getSrcIp().replace(".", "_")).append('-').append(rule.getSrcPortRange()[0]).toString();
if (!rule.revoked()) {
List<PortForwardingRuleTO> fwList = pools.get(poolName);
if (fwList == null) {
fwList = new ArrayList<FirewallRuleVO>();
fwList = new ArrayList<PortForwardingRuleTO>();
pools.put(poolName, fwList);
}
fwList.add(rule);
@ -95,7 +96,7 @@ public class HAProxyConfigurator implements LoadBalancerConfigurator {
}
result.add(getBlankLine());
for (Map.Entry<String, List<FirewallRuleVO>> e : pools.entrySet()){
for (Map.Entry<String, List<PortForwardingRuleTO>> e : pools.entrySet()){
List<String> poolRules = getRulesForPool(e.getKey(), e.getValue());
result.addAll(poolRules);
}
@ -103,11 +104,11 @@ public class HAProxyConfigurator implements LoadBalancerConfigurator {
return result.toArray(new String[result.size()]);
}
private List<String> getRulesForPool(String poolName, List<FirewallRuleVO> fwRules) {
FirewallRuleVO firstRule = fwRules.get(0);
String publicIP = firstRule.getPublicIpAddress();
String publicPort = firstRule.getPublicPort();
String algorithm = firstRule.getAlgorithm();
private List<String> getRulesForPool(String poolName, List<PortForwardingRuleTO> fwRules) {
PortForwardingRuleTO firstRule = fwRules.get(0);
String publicIP = firstRule.getSrcIp();
String publicPort = Integer.toString(firstRule.getSrcPortRange()[0]);
// FIXEME: String algorithm = firstRule.getAlgorithm();
List<String> result = new ArrayList<String>();
//add line like this: "listen 65_37_141_30-80 65.37.141.30:80"
@ -116,7 +117,7 @@ public class HAProxyConfigurator implements LoadBalancerConfigurator {
.append(publicIP).append(":").append(publicPort);
result.add(sb.toString());
sb = new StringBuilder();
sb.append("\t").append("balance ").append(algorithm);
//FIXME sb.append("\t").append("balance ").append(algorithm);
result.add(sb.toString());
if (publicPort.equals(NetUtils.HTTP_PORT)) {
sb = new StringBuilder();
@ -127,14 +128,15 @@ public class HAProxyConfigurator implements LoadBalancerConfigurator {
result.add(sb.toString());
}
int i=0;
for (FirewallRuleVO rule: fwRules) {
for (PortForwardingRuleTO rule: fwRules) {
//add line like this: "server 65_37_141_30-80_3 10.1.1.4:80 check"
if (!rule.isEnabled())
continue;
if (rule.revoked()) {
continue;
}
sb = new StringBuilder();
sb.append("\t").append("server ").append(poolName)
.append("_").append(Integer.toString(i++)).append(" ")
.append(rule.getPrivateIpAddress()).append(":").append(rule.getPrivatePort())
.append(rule.getDstIp()).append(":").append(rule.getDstPortRange()[0])
.append(" check");
result.add(sb.toString());
}
@ -147,24 +149,22 @@ public class HAProxyConfigurator implements LoadBalancerConfigurator {
}
@Override
public String[][] generateFwRules(List<FirewallRuleVO> fwRules) {
public String[][] generateFwRules(List<PortForwardingRuleTO> fwRules) {
String [][] result = new String [2][];
Set<String> toAdd = new HashSet<String>();
Set<String> toRemove = new HashSet<String>();
for (int i = 0; i < fwRules.size(); i++) {
FirewallRuleVO rule = fwRules.get(i);
if (rule.isForwarding())
continue;
PortForwardingRuleTO rule = fwRules.get(i);
String vlanNetmask = rule.getVlanNetmask();
StringBuilder sb = new StringBuilder();
sb.append(rule.getPublicIpAddress()).append(":");
sb.append(rule.getPublicPort()).append(":");
sb.append(rule.getSrcIp()).append(":");
sb.append(rule.getSrcPortRange()[0]).append(":");
sb.append(vlanNetmask);
String lbRuleEntry = sb.toString();
if (rule.isEnabled()) {
if (!rule.revoked()) {
toAdd.add(lbRuleEntry);
} else {
toRemove.add(lbRuleEntry);
@ -176,5 +176,4 @@ public class HAProxyConfigurator implements LoadBalancerConfigurator {
return result;
}
}

View File

@ -141,6 +141,10 @@ public class IPAddressVO implements IpAddress {
@Override
public void setOneToOneNat(boolean oneToOneNat) {
this.oneToOneNat = oneToOneNat;
}
@Override
public String toString() {
return new StringBuilder("Ip[").append(address).append("-").append(dataCenterId).append("]").toString();
}
}

View File

@ -18,12 +18,12 @@
package com.cloud.network;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name=("load_balancer_vm_map"))
@ -31,7 +31,7 @@ public class LoadBalancerVMMapVO {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
private Long id;
private long id;
@Column(name="load_balancer_id")
private long loadBalancerId;
@ -55,7 +55,7 @@ public class LoadBalancerVMMapVO {
this.pending = pending;
}
public Long getId() {
public long getId() {
return id;
}

View File

@ -18,127 +18,80 @@
package com.cloud.network;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.SecondaryTable;
import javax.persistence.Table;
import com.cloud.network.rules.FirewallRuleVO;
import com.cloud.network.rules.LoadBalancer;
import com.cloud.utils.net.Ip;
import com.cloud.utils.net.NetUtils;
@Entity
@Table(name=("load_balancer"))
@SecondaryTable(name="account",
pkJoinColumns={@PrimaryKeyJoinColumn(name="account_id", referencedColumnName="id")})
public class LoadBalancerVO implements LoadBalancer {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
private long id;
public class LoadBalancerVO extends FirewallRuleVO implements LoadBalancer {
@Column(name="name")
private String name;
@Column(name="description")
private String description;
@Column(name="account_id")
private long accountId;
@Column(name="domain_id", table="account", insertable=false, updatable=false)
private long domainId;
@Column(name="account_name", table="account", insertable=false, updatable=false)
private String accountName = null;
@Column(name="ip_address")
private String ipAddress;
@Column(name="public_port")
private String publicPort;
@Column(name="private_port")
private String privatePort;
@Column(name="algorithm")
private String algorithm;
public LoadBalancerVO() { }
public LoadBalancerVO(String name, String description, long accountId, String ipAddress, String publicPort, String privatePort, String algorithm) {
this.name = name;
this.description = description;
this.accountId = accountId;
this.ipAddress = ipAddress;
this.publicPort = publicPort;
this.privatePort = privatePort;
this.algorithm = algorithm;
private String algorithm;
@Column(name="dest_port_start")
private int defaultPortStart;
@Column(name="dest_port_end")
private int defaultPortEnd;
public LoadBalancerVO() {
}
@Override
public long getId() {
return id;
}
public LoadBalancerVO(String xId, String name, String description, Ip srcIp, int srcPort, int dstPort, String algorithm, long networkId, long accountId, long domainId) {
super(xId, srcIp, srcPort, NetUtils.TCP_PROTO, networkId, accountId, domainId, Purpose.LoadBalancing);
this.name = name;
this.description = description;
this.algorithm = algorithm;
this.defaultPortStart = dstPort;
this.defaultPortEnd = dstPort;
}
@Override
public String getName() {
return name;
}
@Override
public void setName(String name) {
this.name = name;
}
@Override
public String getDescription() {
return description;
}
@Override
public void setDescription(String description) {
this.description = description;
}
@Override
public long getAccountId() {
return accountId;
}
@Override
public String getIpAddress() {
return ipAddress;
}
@Override
public String getPublicPort() {
return publicPort;
}
@Override
public String getPrivatePort() {
return privatePort;
}
@Override
public void setPrivatePort(String privatePort) {
this.privatePort = privatePort;
}
@Override
public String getAlgorithm() {
return algorithm;
}
@Override
public void setAlgorithm(String algorithm) {
this.algorithm = algorithm;
public int getDefaultPortStart() {
return defaultPortStart;
}
@Override
public Long getDomainId() {
return domainId;
}
public int getDefaultPortEnd() {
return defaultPortEnd;
}
@Override
public String getAccountName() {
return accountName;
public List<? extends Destination> getDestinations() {
// TODO Auto-generated method stub
return null;
}
}

View File

@ -34,11 +34,13 @@ import com.cloud.exception.ResourceAllocationException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.network.router.VirtualRouter;
import com.cloud.network.rules.FirewallRule;
import com.cloud.offerings.NetworkOfferingVO;
import com.cloud.service.ServiceOfferingVO;
import com.cloud.user.Account;
import com.cloud.user.AccountVO;
import com.cloud.utils.Pair;
import com.cloud.utils.net.Ip;
import com.cloud.vm.DomainRouterVO;
import com.cloud.vm.Nic;
import com.cloud.vm.NicProfile;
@ -140,28 +142,6 @@ public interface NetworkManager extends NetworkService {
*/
public String assignSourceNatIpAddress(Account account, DataCenterVO dc, String domain, ServiceOfferingVO so, long startEventId, HypervisorType hyperType) throws ResourceAllocationException;
/**
* @param fwRules list of rules to be updated
* @param router router where the rules have to be updated
* @return list of rules successfully updated
*/
public List<FirewallRuleVO> updatePortForwardingRules(List<FirewallRuleVO> fwRules, DomainRouterVO router, Long hostId);
/**
* @param fwRules list of rules to be updated
* @param router router where the rules have to be updated
* @return success
*/
public boolean updateLoadBalancerRules(List<FirewallRuleVO> fwRules, DomainRouterVO router, Long hostId);
/**
* @param publicIpAddress public ip address associated with the fwRules
* @param fwRules list of rules to be updated
* @param router router where the rules have to be updated
* @return list of rules successfully updated
*/
public List<FirewallRuleVO> updateFirewallRules(String publicIpAddress, List<FirewallRuleVO> fwRules, DomainRouterVO router);
/**
* Associates or disassociates a list of public IP address for a router.
* @param router router object to send the association to
@ -181,8 +161,6 @@ public interface NetworkManager extends NetworkService {
*/
boolean associateIP(DomainRouterVO router, String ipAddress, boolean add, long vmId) throws ResourceAllocationException;
boolean updateFirewallRule(FirewallRuleVO fwRule, String oldPrivateIP, String oldPrivatePort);
/**
* Add a DHCP entry on the domr dhcp server
@ -240,7 +218,8 @@ public interface NetworkManager extends NetworkService {
List<NetworkVO> setupNetworkConfiguration(Account owner, ServiceOfferingVO offering, DeploymentPlan plan);
String assignSourceNatIpAddress(Account account, DataCenter dc) throws InsufficientAddressCapacityException;
Network getNetworkConfiguration(long id);
Network getNetwork(long id);
String getNextAvailableMacAddressInNetwork(long networkConfigurationId) throws InsufficientAddressCapacityException;
boolean applyRules(Ip ip, List<? extends FirewallRule> rules, boolean continueOnError) throws ResourceUnavailableException;
}

File diff suppressed because it is too large Load Diff

View File

@ -32,13 +32,13 @@ import com.cloud.deploy.DeploymentPlan;
import com.cloud.exception.InsufficientAddressCapacityException;
import com.cloud.exception.InsufficientVirtualNetworkCapcityException;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.network.Network;
import com.cloud.network.Network.State;
import com.cloud.network.NetworkManager;
import com.cloud.network.NetworkVO;
import com.cloud.network.Networks.BroadcastDomainType;
import com.cloud.network.Networks.Mode;
import com.cloud.network.Networks.TrafficType;
import com.cloud.network.Network;
import com.cloud.network.Network.State;
import com.cloud.network.NetworkVO;
import com.cloud.network.NetworkManager;
import com.cloud.offering.NetworkOffering;
import com.cloud.offering.NetworkOffering.GuestIpType;
import com.cloud.resource.Resource.ReservationStrategy;
@ -229,7 +229,6 @@ public class GuestNetworkGuru extends AdapterBase implements NetworkGuru {
@Override
public boolean trash(Network config, NetworkOffering offering, Account owner) {
// TODO Auto-generated method stub
return true;
}
}

View File

@ -18,40 +18,47 @@
package com.cloud.network.dao;
import java.util.List;
import com.cloud.network.FirewallRuleVO;
import java.util.List;
import com.cloud.network.rules.FirewallRuleVO;
import com.cloud.utils.db.GenericDao;
import com.cloud.utils.net.Ip;
/*
* Data Access Object for user_ip_address and ip_forwarding tables
*/
public interface FirewallRulesDao extends GenericDao<FirewallRuleVO, Long> {
public List<FirewallRuleVO> listIPForwarding(String publicIPAddress, boolean forwarding);
public List<FirewallRuleVO> listIPForwarding(String publicIPAddress, String port, boolean forwarding);
public List<FirewallRuleVO> listIPForwarding(long userId);
public List<FirewallRuleVO> listIPForwarding(long userId, long dcId);
public void deleteIPForwardingByPublicIpAddress(String ipAddress);
public List<FirewallRuleVO> listIPForwarding(String publicIPAddress);
public List<FirewallRuleVO> listIPForwardingForUpdate(String publicIPAddress);
public void disableIPForwarding(String publicIPAddress);
public List<FirewallRuleVO> listIPForwardingForUpdate(String publicIp, boolean fwding);
public List<FirewallRuleVO> listIPForwardingForUpdate(String publicIp, String publicPort, String proto);
public List<FirewallRuleVO> listIPForwardingByPortAndProto(String publicIp, String publicPort, String proto);
public List<FirewallRuleVO> listLoadBalanceRulesForUpdate(String publicIp, String publicPort, String algo);
public List<FirewallRuleVO> listIpForwardingRulesForLoadBalancers(String publicIp);
public List<FirewallRuleVO> listRulesExcludingPubIpPort(String publicIpAddress, long securityGroupId);
public List<FirewallRuleVO> listBySecurityGroupId(long securityGroupId);
public List<FirewallRuleVO> listByLoadBalancerId(long loadBalancerId);
public List<FirewallRuleVO> listForwardingByPubAndPrivIp(boolean forwarding, String publicIPAddress, String privateIp);
public FirewallRuleVO findByGroupAndPrivateIp(long groupId, String privateIp, boolean forwarding);
public List<FirewallRuleVO> listByPrivateIp(String privateIp);
public boolean isPublicIpOneToOneNATted(String publicIp);
void deleteIPForwardingByPublicIpAndPort(String ipAddress, String port);
public List<FirewallRuleVO> listIPForwardingForLB(long userId, long dcId);
public List<FirewallRuleVO> findRuleByPublicIp(String publicIp);
public interface FirewallRulesDao extends GenericDao<FirewallRuleVO, Long> {
List<FirewallRuleVO> listByIpAndNotRevoked(Ip ip);
boolean setStateToAdd(FirewallRuleVO rule);
boolean revoke(FirewallRuleVO rule);
// public List<PortForwardingRuleVO> listIPForwarding(String publicIPAddress, boolean forwarding);
// public List<PortForwardingRuleVO> listIPForwarding(String publicIPAddress, String port, boolean forwarding);
//
// public List<PortForwardingRuleVO> listIPForwarding(long userId);
// public List<PortForwardingRuleVO> listIPForwarding(long userId, long dcId);
// public void deleteIPForwardingByPublicIpAddress(String ipAddress);
// public List<PortForwardingRuleVO> listIPForwarding(String publicIPAddress);
// public List<PortForwardingRuleVO> listIPForwardingForUpdate(String publicIPAddress);
// public void disableIPForwarding(String publicIPAddress);
// public List<PortForwardingRuleVO> listIPForwardingForUpdate(String publicIp, boolean fwding);
// public List<PortForwardingRuleVO> listIPForwardingForUpdate(String publicIp, String publicPort, String proto);
// public List<PortForwardingRuleVO> listIPForwardingByPortAndProto(String publicIp, String publicPort, String proto);
//
// public List<PortForwardingRuleVO> listLoadBalanceRulesForUpdate(String publicIp, String publicPort, String algo);
// public List<PortForwardingRuleVO> listIpForwardingRulesForLoadBalancers(String publicIp);
//
//
// public List<PortForwardingRuleVO> listRulesExcludingPubIpPort(String publicIpAddress, long securityGroupId);
// public List<PortForwardingRuleVO> listBySecurityGroupId(long securityGroupId);
// public List<PortForwardingRuleVO> listByLoadBalancerId(long loadBalancerId);
// public List<PortForwardingRuleVO> listForwardingByPubAndPrivIp(boolean forwarding, String publicIPAddress, String privateIp);
// public PortForwardingRuleVO findByGroupAndPrivateIp(long groupId, String privateIp, boolean forwarding);
// public List<PortForwardingRuleVO> findByPublicIpPrivateIpForNatRule(String publicIp,String privateIp);
// public List<PortForwardingRuleVO> listByPrivateIp(String privateIp);
// public boolean isPublicIpOneToOneNATted(String publicIp);
// void deleteIPForwardingByPublicIpAndPort(String ipAddress, String port);
// public List<PortForwardingRuleVO> listIPForwardingForLB(long userId, long dcId);
}

View File

@ -18,407 +18,458 @@
package com.cloud.network.dao;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.ejb.Local;
import javax.naming.ConfigurationException;
import org.apache.log4j.Logger;
import com.cloud.network.FirewallRuleVO;
import com.cloud.network.rules.FirewallRule.State;
import com.cloud.network.rules.FirewallRuleVO;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.db.SearchCriteria.Op;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.net.NetUtils;
import com.cloud.utils.net.Ip;
@Local(value = { FirewallRulesDao.class })
@Local(value = { FirewallRulesDao.class }) @DB(txn=false)
public class FirewallRulesDaoImpl extends GenericDaoBase<FirewallRuleVO, Long> implements FirewallRulesDao {
private static final Logger s_logger = Logger.getLogger(FirewallRulesDaoImpl.class);
public static String SELECT_IP_FORWARDINGS_BY_USERID_SQL = null;
public static String SELECT_IP_FORWARDINGS_BY_USERID_AND_DCID_SQL = null;
public static String SELECT_LB_FORWARDINGS_BY_USERID_AND_DCID_SQL = null;
public static final String DELETE_IP_FORWARDING_BY_IPADDRESS_SQL = "DELETE FROM ip_forwarding WHERE public_ip_address = ?";
public static final String DELETE_IP_FORWARDING_BY_IP_PORT_SQL = "DELETE FROM ip_forwarding WHERE public_ip_address = ? and public_port = ?";
public static final String DISABLE_IP_FORWARDING_BY_IPADDRESS_SQL = "UPDATE ip_forwarding set enabled=0 WHERE public_ip_address = ?";
protected SearchBuilder<FirewallRuleVO> FWByIPSearch;
protected SearchBuilder<FirewallRuleVO> FWByIPAndForwardingSearch;
protected SearchBuilder<FirewallRuleVO> FWByIPPortAndForwardingSearch;
protected SearchBuilder<FirewallRuleVO> FWByIPPortProtoSearch;
protected SearchBuilder<FirewallRuleVO> FWByIPPortAlgoSearch;
protected SearchBuilder<FirewallRuleVO> FWByPrivateIPSearch;
protected SearchBuilder<FirewallRuleVO> RulesExcludingPubIpPort;
protected SearchBuilder<FirewallRuleVO> FWByGroupId;
protected SearchBuilder<FirewallRuleVO> FWByIpForLB;
protected SearchBuilder<FirewallRuleVO> FWByGroupAndPrivateIp;
protected SearchBuilder<FirewallRuleVO> FWByPublicIpSearch;
protected SearchBuilder<FirewallRuleVO> OneToOneNATSearch;
protected FirewallRulesDaoImpl() {
}
@Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
if (!super.configure(name, params)) {
return false;
}
SELECT_IP_FORWARDINGS_BY_USERID_SQL = buildSelectByUserIdSql();
if (s_logger.isDebugEnabled()) {
s_logger.debug(SELECT_IP_FORWARDINGS_BY_USERID_SQL);
}
SELECT_IP_FORWARDINGS_BY_USERID_AND_DCID_SQL = buildSelectByUserIdAndDatacenterIdSql();
if (s_logger.isDebugEnabled()) {
s_logger.debug(SELECT_IP_FORWARDINGS_BY_USERID_AND_DCID_SQL);
}
SELECT_LB_FORWARDINGS_BY_USERID_AND_DCID_SQL = buildSelectByUserIdAndDatacenterIdForLBSql();
if (s_logger.isDebugEnabled()) {
s_logger.debug(SELECT_LB_FORWARDINGS_BY_USERID_AND_DCID_SQL);
}
FWByIPSearch = createSearchBuilder();
FWByIPSearch.and("publicIpAddress", FWByIPSearch.entity().getPublicIpAddress(), SearchCriteria.Op.EQ);
FWByIPSearch.done();
FWByIPAndForwardingSearch = createSearchBuilder();
FWByIPAndForwardingSearch.and("publicIpAddress", FWByIPAndForwardingSearch.entity().getPublicIpAddress(), SearchCriteria.Op.EQ);
FWByIPAndForwardingSearch.and("forwarding", FWByIPAndForwardingSearch.entity().isForwarding(), SearchCriteria.Op.EQ);
FWByIPAndForwardingSearch.done();
FWByIPPortAndForwardingSearch = createSearchBuilder();
FWByIPPortAndForwardingSearch.and("publicIpAddress", FWByIPPortAndForwardingSearch.entity().getPublicIpAddress(), SearchCriteria.Op.EQ);
FWByIPPortAndForwardingSearch.and("publicPort", FWByIPPortAndForwardingSearch.entity().getPublicPort(), SearchCriteria.Op.EQ);
FWByIPPortAndForwardingSearch.and("forwarding", FWByIPPortAndForwardingSearch.entity().isForwarding(), SearchCriteria.Op.EQ);
FWByIPPortAndForwardingSearch.done();
FWByIPPortProtoSearch = createSearchBuilder();
FWByIPPortProtoSearch.and("publicIpAddress", FWByIPPortProtoSearch.entity().getPublicIpAddress(), SearchCriteria.Op.EQ);
FWByIPPortProtoSearch.and("publicPort", FWByIPPortProtoSearch.entity().getPublicPort(), SearchCriteria.Op.EQ);
FWByIPPortProtoSearch.and("protocol", FWByIPPortProtoSearch.entity().getProtocol(), SearchCriteria.Op.EQ);
FWByIPPortProtoSearch.done();
FWByIPPortAlgoSearch = createSearchBuilder();
FWByIPPortAlgoSearch.and("publicIpAddress", FWByIPPortAlgoSearch.entity().getPublicIpAddress(), SearchCriteria.Op.EQ);
FWByIPPortAlgoSearch.and("publicPort", FWByIPPortAlgoSearch.entity().getPublicPort(), SearchCriteria.Op.EQ);
FWByIPPortAlgoSearch.and("algorithm", FWByIPPortAlgoSearch.entity().getAlgorithm(), SearchCriteria.Op.EQ);
FWByIPPortAlgoSearch.done();
FWByPrivateIPSearch = createSearchBuilder();
FWByPrivateIPSearch.and("privateIpAddress", FWByPrivateIPSearch.entity().getPrivateIpAddress(), SearchCriteria.Op.EQ);
FWByPrivateIPSearch.done();
RulesExcludingPubIpPort = createSearchBuilder();
RulesExcludingPubIpPort.and("publicIpAddress", RulesExcludingPubIpPort.entity().getPrivateIpAddress(), SearchCriteria.Op.EQ);
RulesExcludingPubIpPort.and("groupId", RulesExcludingPubIpPort.entity().getGroupId(), SearchCriteria.Op.NEQ);
RulesExcludingPubIpPort.and("forwarding", RulesExcludingPubIpPort.entity().isForwarding(), SearchCriteria.Op.EQ);
RulesExcludingPubIpPort.done();
FWByGroupId = createSearchBuilder();
FWByGroupId.and("groupId", FWByGroupId.entity().getGroupId(), SearchCriteria.Op.EQ);
FWByGroupId.and("forwarding", FWByGroupId.entity().isForwarding(), SearchCriteria.Op.EQ);
FWByGroupId.done();
FWByGroupAndPrivateIp = createSearchBuilder();
FWByGroupAndPrivateIp.and("groupId", FWByGroupAndPrivateIp.entity().getGroupId(), SearchCriteria.Op.EQ);
FWByGroupAndPrivateIp.and("privateIpAddress", FWByGroupAndPrivateIp.entity().getPrivateIpAddress(), SearchCriteria.Op.EQ);
FWByGroupAndPrivateIp.and("forwarding", FWByGroupAndPrivateIp.entity().isForwarding(), SearchCriteria.Op.EQ);
FWByGroupAndPrivateIp.done();
FWByPublicIpSearch = createSearchBuilder();
FWByPublicIpSearch.and("publicIpAddress", FWByPublicIpSearch.entity().getPublicIpAddress(), SearchCriteria.Op.EQ);
FWByPublicIpSearch.done();
OneToOneNATSearch = createSearchBuilder();
OneToOneNATSearch.and("publicIpAddress", OneToOneNATSearch.entity().getPublicIpAddress(), SearchCriteria.Op.EQ);
OneToOneNATSearch.and("protocol", OneToOneNATSearch.entity().getProtocol(), SearchCriteria.Op.EQ);
OneToOneNATSearch.done();
FWByIpForLB = createSearchBuilder();
FWByIpForLB.and("publicIpAddress", FWByIpForLB.entity().getPublicIpAddress(), SearchCriteria.Op.EQ);
FWByIpForLB.and("groupId", FWByIpForLB.entity().getGroupId(), SearchCriteria.Op.NNULL);
FWByIpForLB.and("forwarding", FWByIpForLB.entity().isForwarding(), SearchCriteria.Op.EQ);
FWByIpForLB.done();
return true;
}
protected String buildSelectByUserIdSql() {
StringBuilder sql = createPartialSelectSql(null, true);
sql.insert(sql.length() - 6, ", user_ip_address ");
sql.append("ip_forwarding.public_ip_address = user_ip_address.public_ip_address AND user_ip_address.account_id = ?");
return sql.toString();
}
protected String buildSelectByUserIdAndDatacenterIdSql() {
return "SELECT i.id, i.group_id, i.public_ip_address, i.public_port, i.private_ip_address, i.private_port, i.enabled, i.protocol, i.forwarding, i.algorithm FROM ip_forwarding i, user_ip_address u WHERE i.public_ip_address=u.public_ip_address AND u.account_id=? AND u.data_center_id=?";
}
protected String buildSelectByUserIdAndDatacenterIdForLBSql() {
return "SELECT i.id, i.group_id, i.public_ip_address, i.public_port, i.private_ip_address, i.private_port, i.enabled, i.protocol, i.forwarding, i.algorithm FROM ip_forwarding i, user_ip_address u WHERE i.public_ip_address=u.public_ip_address AND u.account_id=? AND u.data_center_id=? AND i.group_id is not NULL";
}
public List<FirewallRuleVO> listIPForwarding(String publicIPAddress, boolean forwarding) {
SearchCriteria<FirewallRuleVO> sc = FWByIPAndForwardingSearch.create();
sc.setParameters("publicIpAddress", publicIPAddress);
sc.setParameters("forwarding", forwarding);
return listBy(sc);
}
@Override
public List<FirewallRuleVO> listIPForwarding(long userId) {
Transaction txn = Transaction.currentTxn();
List<FirewallRuleVO> forwardings = new ArrayList<FirewallRuleVO>();
PreparedStatement pstmt = null;
try {
pstmt = txn.prepareAutoCloseStatement(SELECT_IP_FORWARDINGS_BY_USERID_SQL);
pstmt.setLong(1, userId);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
forwardings.add(toEntityBean(rs, false));
}
} catch (Exception e) {
s_logger.warn(e);
}
return forwardings;
}
public List<FirewallRuleVO> listIPForwarding(long userId, long dcId) {
Transaction txn = Transaction.currentTxn();
List<FirewallRuleVO> forwardings = new ArrayList<FirewallRuleVO>();
PreparedStatement pstmt = null;
try {
pstmt = txn.prepareAutoCloseStatement(SELECT_IP_FORWARDINGS_BY_USERID_AND_DCID_SQL);
pstmt.setLong(1, userId);
pstmt.setLong(2, dcId);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
forwardings.add(toEntityBean(rs, false));
}
} catch (Exception e) {
s_logger.warn(e);
}
return forwardings;
}
@Override
public void deleteIPForwardingByPublicIpAddress(String ipAddress) {
Transaction txn = Transaction.currentTxn();
PreparedStatement pstmt = null;
try {
pstmt = txn.prepareAutoCloseStatement(DELETE_IP_FORWARDING_BY_IPADDRESS_SQL);
pstmt.setString(1, ipAddress);
pstmt.executeUpdate();
} catch (Exception e) {
s_logger.warn(e);
}
}
protected final SearchBuilder<FirewallRuleVO> AllFieldsSearch;
protected final SearchBuilder<FirewallRuleVO> IpNotRevokedSearch;
protected FirewallRulesDaoImpl() {
super();
AllFieldsSearch = createSearchBuilder();
AllFieldsSearch.and("ip", AllFieldsSearch.entity().getSourceIpAddress(), Op.EQ);
AllFieldsSearch.and("protocol", AllFieldsSearch.entity().getProtocol(), Op.EQ);
AllFieldsSearch.and("state", AllFieldsSearch.entity().getState(), Op.EQ);
AllFieldsSearch.and("purpose", AllFieldsSearch.entity().getPurpose(), Op.EQ);
AllFieldsSearch.and("account", AllFieldsSearch.entity().getAccountId(), Op.EQ);
AllFieldsSearch.and("domain", AllFieldsSearch.entity().getDomainId(), Op.EQ);
AllFieldsSearch.and("id", AllFieldsSearch.entity().getId(), Op.EQ);
AllFieldsSearch.done();
IpNotRevokedSearch = createSearchBuilder();
IpNotRevokedSearch.and("ip", IpNotRevokedSearch.entity().getSourceIpAddress(), Op.EQ);
IpNotRevokedSearch.and("state", IpNotRevokedSearch.entity().getSourceIpAddress(), Op.NEQ);
IpNotRevokedSearch.done();
}
@Override
public void deleteIPForwardingByPublicIpAndPort(String ipAddress, String port) {
Transaction txn = Transaction.currentTxn();
PreparedStatement pstmt = null;
try {
pstmt = txn.prepareAutoCloseStatement(DELETE_IP_FORWARDING_BY_IP_PORT_SQL);
pstmt.setString(1, ipAddress);
pstmt.setString(2, port);
pstmt.executeUpdate();
} catch (Exception e) {
s_logger.warn(e);
}
}
@Override
public List<FirewallRuleVO> listIPForwarding(String publicIPAddress) {
SearchCriteria<FirewallRuleVO> sc = FWByIPSearch.create();
sc.setParameters("publicIpAddress", publicIPAddress);
return listBy(sc);
}
@Override
public List<FirewallRuleVO> listIPForwardingForUpdate(String publicIPAddress) {
SearchCriteria<FirewallRuleVO> sc = FWByIPSearch.create();
sc.setParameters("publicIpAddress", publicIPAddress);
return listBy(sc, null);
}
@Override
public List<FirewallRuleVO> listIPForwardingForUpdate(String publicIp, boolean fwding) {
SearchCriteria<FirewallRuleVO> sc = FWByIPAndForwardingSearch.create();
sc.setParameters("publicIpAddress", publicIp);
sc.setParameters("forwarding", fwding);
return search(sc, null);
}
@Override
public List<FirewallRuleVO> listIPForwardingForUpdate(String publicIp,
String publicPort, String proto) {
SearchCriteria<FirewallRuleVO> sc = FWByIPPortProtoSearch.create();
sc.setParameters("publicIpAddress", publicIp);
sc.setParameters("publicPort", publicPort);
sc.setParameters("protocol", proto);
return search(sc, null);
}
@Override
public List<FirewallRuleVO> listLoadBalanceRulesForUpdate(String publicIp,
String publicPort, String algo) {
SearchCriteria<FirewallRuleVO> sc = FWByIPPortAlgoSearch.create();
sc.setParameters("publicIpAddress", publicIp);
sc.setParameters("publicPort", publicPort);
sc.setParameters("algorithm", algo);
return listBy(sc, null);
}
@Override
public List<FirewallRuleVO> listIPForwarding(String publicIPAddress,
String port, boolean forwarding) {
SearchCriteria<FirewallRuleVO> sc = FWByIPPortAndForwardingSearch.create();
sc.setParameters("publicIpAddress", publicIPAddress);
sc.setParameters("publicPort", port);
sc.setParameters("forwarding", forwarding);
return listBy(sc);
}
@Override
public void disableIPForwarding(String publicIPAddress) {
Transaction txn = Transaction.currentTxn();
PreparedStatement pstmt = null;
try {
txn.start();
pstmt = txn.prepareAutoCloseStatement(DISABLE_IP_FORWARDING_BY_IPADDRESS_SQL);
pstmt.setString(1, publicIPAddress);
pstmt.executeUpdate();
txn.commit();
} catch (Exception e) {
txn.rollback();
throw new CloudRuntimeException("DB Exception ", e);
}
}
@Override
public List<FirewallRuleVO> listRulesExcludingPubIpPort(String publicIpAddress, long securityGroupId) {
SearchCriteria<FirewallRuleVO> sc = RulesExcludingPubIpPort.create();
sc.setParameters("publicIpAddress", publicIpAddress);
sc.setParameters("groupId", securityGroupId);
sc.setParameters("forwarding", false);
return listBy(sc);
}
@Override
public List<FirewallRuleVO> listBySecurityGroupId(long securityGroupId) {
SearchCriteria<FirewallRuleVO> sc = FWByGroupId.create();
sc.setParameters("groupId", securityGroupId);
sc.setParameters("forwarding", Boolean.TRUE);
return listBy(sc);
}
@Override
public List<FirewallRuleVO> listForwardingByPubAndPrivIp(boolean forwarding, String publicIPAddress, String privateIp) {
SearchCriteria<FirewallRuleVO> sc = FWByIPAndForwardingSearch.create();
sc.setParameters("publicIpAddress", publicIPAddress);
sc.setParameters("forwarding", forwarding);
sc.addAnd("privateIpAddress", SearchCriteria.Op.EQ, privateIp);
return listBy(sc);
}
@Override
public List<FirewallRuleVO> listByLoadBalancerId(long loadBalancerId) {
SearchCriteria<FirewallRuleVO> sc = FWByGroupId.create();
sc.setParameters("groupId", loadBalancerId);
sc.setParameters("forwarding", Boolean.FALSE);
return listBy(sc);
}
@Override
public FirewallRuleVO findByGroupAndPrivateIp(long groupId, String privateIp, boolean forwarding) {
SearchCriteria<FirewallRuleVO> sc = FWByGroupAndPrivateIp.create();
sc.setParameters("groupId", groupId);
sc.setParameters("privateIpAddress", privateIp);
sc.setParameters("forwarding", forwarding);
return findOneBy(sc);
}
@Override
public List<FirewallRuleVO> findRuleByPublicIp(String publicIp){
SearchCriteria<FirewallRuleVO> sc = FWByPublicIpSearch.create();
sc.setParameters("publicIpAddress", publicIp);
return listBy(sc);
}
@Override
public List<FirewallRuleVO> listByPrivateIp(String privateIp) {
SearchCriteria<FirewallRuleVO> sc = FWByPrivateIPSearch.create();
sc.setParameters("privateIpAddress", privateIp);
public List<FirewallRuleVO> listByIpAndNotRevoked(Ip ip) {
SearchCriteria<FirewallRuleVO> sc = IpNotRevokedSearch.create();
sc.setParameters("ip", ip);
sc.setParameters("state", State.Revoke);
return listBy(sc);
}
@Override
public List<FirewallRuleVO> listIPForwardingByPortAndProto(String publicIp,
String publicPort, String proto) {
SearchCriteria<FirewallRuleVO> sc = FWByIPPortProtoSearch.create();
sc.setParameters("publicIpAddress", publicIp);
sc.setParameters("publicPort", publicPort);
sc.setParameters("protocol", proto);
return search(sc, null);
}
@Override
public boolean isPublicIpOneToOneNATted(String publicIp) {
SearchCriteria<FirewallRuleVO> sc = OneToOneNATSearch.create();
sc.setParameters("publicIpAddress", publicIp);
sc.setParameters("protocol", NetUtils.NAT_PROTO);
List<FirewallRuleVO> rules = search(sc, null);
if (rules.size() != 1)
return false;
return rules.get(1).getProtocol().equalsIgnoreCase(NetUtils.NAT_PROTO);
}
@Override
public List<FirewallRuleVO> listIpForwardingRulesForLoadBalancers(
String publicIp) {
SearchCriteria<FirewallRuleVO> sc = FWByIpForLB.create();
sc.setParameters("publicIpAddress", publicIp);
sc.setParameters("forwarding", false);
return search(sc, null);
}
@Override
public List<FirewallRuleVO> listIPForwardingForLB(long userId, long dcId) {
Transaction txn = Transaction.currentTxn();
List<FirewallRuleVO> forwardings = new ArrayList<FirewallRuleVO>();
PreparedStatement pstmt = null;
try {
pstmt = txn.prepareAutoCloseStatement(SELECT_LB_FORWARDINGS_BY_USERID_AND_DCID_SQL);
pstmt.setLong(1, userId);
pstmt.setLong(2, dcId);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
forwardings.add(toEntityBean(rs, false));
}
} catch (Exception e) {
s_logger.warn(e);
}
return forwardings;
}
}
@Override
public boolean setStateToAdd(FirewallRuleVO rule) {
SearchCriteria<FirewallRuleVO> sc = AllFieldsSearch.create();
sc.setParameters("id", rule.getId());
sc.setParameters("state", State.Staged);
rule.setState(State.Add);
return update(rule, sc) > 0;
}
@Override
public boolean revoke(FirewallRuleVO rule) {
rule.setState(State.Revoke);
return update(rule.getId(), rule);
}
// public static String SELECT_IP_FORWARDINGS_BY_USERID_SQL = null;
// public static String SELECT_IP_FORWARDINGS_BY_USERID_AND_DCID_SQL = null;
// public static String SELECT_LB_FORWARDINGS_BY_USERID_AND_DCID_SQL = null;
//
//
// public static final String DELETE_IP_FORWARDING_BY_IPADDRESS_SQL = "DELETE FROM ip_forwarding WHERE public_ip_address = ?";
// public static final String DELETE_IP_FORWARDING_BY_IP_PORT_SQL = "DELETE FROM ip_forwarding WHERE public_ip_address = ? and public_port = ?";
//
// public static final String DISABLE_IP_FORWARDING_BY_IPADDRESS_SQL = "UPDATE ip_forwarding set enabled=0 WHERE public_ip_address = ?";
//
//
// protected SearchBuilder<PortForwardingRuleVO> FWByIPAndForwardingSearch;
// protected SearchBuilder<PortForwardingRuleVO> FWByIPPortAndForwardingSearch;
// protected SearchBuilder<PortForwardingRuleVO> FWByIPPortProtoSearch;
// protected SearchBuilder<PortForwardingRuleVO> FWByIPPortAlgoSearch;
// protected SearchBuilder<PortForwardingRuleVO> FWByPrivateIPSearch;
// protected SearchBuilder<PortForwardingRuleVO> RulesExcludingPubIpPort;
// protected SearchBuilder<PortForwardingRuleVO> FWByGroupId;
// protected SearchBuilder<PortForwardingRuleVO> FWByIpForLB;
//
// protected SearchBuilder<PortForwardingRuleVO> FWByGroupAndPrivateIp;
// protected SearchBuilder<PortForwardingRuleVO> FWByPrivateIpPrivatePortPublicIpPublicPortSearch;
// protected SearchBuilder<PortForwardingRuleVO> OneToOneNATSearch;
//
//
// protected FirewallRulesDaoImpl() {
// }
//
// @Override
// public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
// if (!super.configure(name, params)) {
// return false;
// }
//
// SELECT_IP_FORWARDINGS_BY_USERID_SQL = buildSelectByUserIdSql();
// if (s_logger.isDebugEnabled()) {
// s_logger.debug(SELECT_IP_FORWARDINGS_BY_USERID_SQL);
// }
//
// SELECT_IP_FORWARDINGS_BY_USERID_AND_DCID_SQL = buildSelectByUserIdAndDatacenterIdSql();
// if (s_logger.isDebugEnabled()) {
// s_logger.debug(SELECT_IP_FORWARDINGS_BY_USERID_AND_DCID_SQL);
// }
//
// SELECT_LB_FORWARDINGS_BY_USERID_AND_DCID_SQL = buildSelectByUserIdAndDatacenterIdForLBSql();
// if (s_logger.isDebugEnabled()) {
// s_logger.debug(SELECT_LB_FORWARDINGS_BY_USERID_AND_DCID_SQL);
// }
//
//
// FWByIPSearch = createSearchBuilder();
// FWByIPSearch.and("publicIpAddress", FWByIPSearch.entity().getSourceIpAddress(), SearchCriteria.Op.EQ);
// FWByIPSearch.done();
//
// FWByIPAndForwardingSearch = createSearchBuilder();
// FWByIPAndForwardingSearch.and("publicIpAddress", FWByIPAndForwardingSearch.entity().getSourceIpAddress(), SearchCriteria.Op.EQ);
// FWByIPAndForwardingSearch.and("forwarding", FWByIPAndForwardingSearch.entity().isForwarding(), SearchCriteria.Op.EQ);
// FWByIPAndForwardingSearch.done();
//
// FWByIPPortAndForwardingSearch = createSearchBuilder();
// FWByIPPortAndForwardingSearch.and("publicIpAddress", FWByIPPortAndForwardingSearch.entity().getSourceIpAddress(), SearchCriteria.Op.EQ);
// FWByIPPortAndForwardingSearch.and("publicPort", FWByIPPortAndForwardingSearch.entity().getSourcePort(), SearchCriteria.Op.EQ);
// FWByIPPortAndForwardingSearch.and("forwarding", FWByIPPortAndForwardingSearch.entity().isForwarding(), SearchCriteria.Op.EQ);
// FWByIPPortAndForwardingSearch.done();
//
// FWByIPPortProtoSearch = createSearchBuilder();
// FWByIPPortProtoSearch.and("publicIpAddress", FWByIPPortProtoSearch.entity().getSourceIpAddress(), SearchCriteria.Op.EQ);
// FWByIPPortProtoSearch.and("publicPort", FWByIPPortProtoSearch.entity().getSourcePort(), SearchCriteria.Op.EQ);
// FWByIPPortProtoSearch.and("protocol", FWByIPPortProtoSearch.entity().getProtocol(), SearchCriteria.Op.EQ);
// FWByIPPortProtoSearch.done();
//
// FWByIPPortAlgoSearch = createSearchBuilder();
// FWByIPPortAlgoSearch.and("publicIpAddress", FWByIPPortAlgoSearch.entity().getSourceIpAddress(), SearchCriteria.Op.EQ);
// FWByIPPortAlgoSearch.and("publicPort", FWByIPPortAlgoSearch.entity().getSourcePort(), SearchCriteria.Op.EQ);
// FWByIPPortAlgoSearch.and("algorithm", FWByIPPortAlgoSearch.entity().getAlgorithm(), SearchCriteria.Op.EQ);
// FWByIPPortAlgoSearch.done();
//
// FWByPrivateIPSearch = createSearchBuilder();
// FWByPrivateIPSearch.and("privateIpAddress", FWByPrivateIPSearch.entity().getDestinationIpAddress(), SearchCriteria.Op.EQ);
// FWByPrivateIPSearch.done();
//
// RulesExcludingPubIpPort = createSearchBuilder();
// RulesExcludingPubIpPort.and("publicIpAddress", RulesExcludingPubIpPort.entity().getDestinationIpAddress(), SearchCriteria.Op.EQ);
// RulesExcludingPubIpPort.and("groupId", RulesExcludingPubIpPort.entity().getGroupId(), SearchCriteria.Op.NEQ);
// RulesExcludingPubIpPort.and("forwarding", RulesExcludingPubIpPort.entity().isForwarding(), SearchCriteria.Op.EQ);
// RulesExcludingPubIpPort.done();
//
// FWByGroupId = createSearchBuilder();
// FWByGroupId.and("groupId", FWByGroupId.entity().getGroupId(), SearchCriteria.Op.EQ);
// FWByGroupId.and("forwarding", FWByGroupId.entity().isForwarding(), SearchCriteria.Op.EQ);
// FWByGroupId.done();
//
// FWByGroupAndPrivateIp = createSearchBuilder();
// FWByGroupAndPrivateIp.and("groupId", FWByGroupAndPrivateIp.entity().getGroupId(), SearchCriteria.Op.EQ);
// FWByGroupAndPrivateIp.and("privateIpAddress", FWByGroupAndPrivateIp.entity().getDestinationIpAddress(), SearchCriteria.Op.EQ);
// FWByGroupAndPrivateIp.and("forwarding", FWByGroupAndPrivateIp.entity().isForwarding(), SearchCriteria.Op.EQ);
// FWByGroupAndPrivateIp.done();
//
// FWByPrivateIpPrivatePortPublicIpPublicPortSearch = createSearchBuilder();
// FWByPrivateIpPrivatePortPublicIpPublicPortSearch.and("publicIpAddress", FWByPrivateIpPrivatePortPublicIpPublicPortSearch.entity().getSourceIpAddress(), SearchCriteria.Op.EQ);
// FWByPrivateIpPrivatePortPublicIpPublicPortSearch.and("privateIpAddress", FWByPrivateIpPrivatePortPublicIpPublicPortSearch.entity().getDestinationIpAddress(), SearchCriteria.Op.EQ);
// FWByPrivateIpPrivatePortPublicIpPublicPortSearch.and("privatePort", FWByPrivateIpPrivatePortPublicIpPublicPortSearch.entity().getDestinationPort(), SearchCriteria.Op.NULL);
// FWByPrivateIpPrivatePortPublicIpPublicPortSearch.and("publicPort", FWByPrivateIpPrivatePortPublicIpPublicPortSearch.entity().getSourcePort(), SearchCriteria.Op.NULL);
// FWByPrivateIpPrivatePortPublicIpPublicPortSearch.done();
//
// OneToOneNATSearch = createSearchBuilder();
// OneToOneNATSearch.and("publicIpAddress", OneToOneNATSearch.entity().getSourceIpAddress(), SearchCriteria.Op.EQ);
// OneToOneNATSearch.and("protocol", OneToOneNATSearch.entity().getProtocol(), SearchCriteria.Op.EQ);
// OneToOneNATSearch.done();
//
// FWByIpForLB = createSearchBuilder();
// FWByIpForLB.and("publicIpAddress", FWByIpForLB.entity().getSourceIpAddress(), SearchCriteria.Op.EQ);
// FWByIpForLB.and("groupId", FWByIpForLB.entity().getGroupId(), SearchCriteria.Op.NNULL);
// FWByIpForLB.and("forwarding", FWByIpForLB.entity().isForwarding(), SearchCriteria.Op.EQ);
// FWByIpForLB.done();
//
// return true;
// }
//
// protected String buildSelectByUserIdSql() {
// StringBuilder sql = createPartialSelectSql(null, true);
// sql.insert(sql.length() - 6, ", user_ip_address ");
// sql.append("ip_forwarding.public_ip_address = user_ip_address.public_ip_address AND user_ip_address.account_id = ?");
//
// return sql.toString();
// }
//
// protected String buildSelectByUserIdAndDatacenterIdSql() {
// return "SELECT i.id, i.group_id, i.public_ip_address, i.public_port, i.private_ip_address, i.private_port, i.enabled, i.protocol, i.forwarding, i.algorithm FROM ip_forwarding i, user_ip_address u WHERE i.public_ip_address=u.public_ip_address AND u.account_id=? AND u.data_center_id=?";
// }
//
// protected String buildSelectByUserIdAndDatacenterIdForLBSql() {
// return "SELECT i.id, i.group_id, i.public_ip_address, i.public_port, i.private_ip_address, i.private_port, i.enabled, i.protocol, i.forwarding, i.algorithm FROM ip_forwarding i, user_ip_address u WHERE i.public_ip_address=u.public_ip_address AND u.account_id=? AND u.data_center_id=? AND i.group_id is not NULL";
// }
//
// public List<PortForwardingRuleVO> listIPForwarding(String publicIPAddress, boolean forwarding) {
// SearchCriteria<PortForwardingRuleVO> sc = FWByIPAndForwardingSearch.create();
// sc.setParameters("publicIpAddress", publicIPAddress);
// sc.setParameters("forwarding", forwarding);
// return listBy(sc);
// }
//
// @Override
// public List<PortForwardingRuleVO> listIPForwarding(long userId) {
// Transaction txn = Transaction.currentTxn();
// List<PortForwardingRuleVO> forwardings = new ArrayList<PortForwardingRuleVO>();
// PreparedStatement pstmt = null;
// try {
// pstmt = txn.prepareAutoCloseStatement(SELECT_IP_FORWARDINGS_BY_USERID_SQL);
// pstmt.setLong(1, userId);
// ResultSet rs = pstmt.executeQuery();
// while (rs.next()) {
// forwardings.add(toEntityBean(rs, false));
// }
// } catch (Exception e) {
// s_logger.warn(e);
// }
// return forwardings;
// }
//
// public List<PortForwardingRuleVO> listIPForwarding(long userId, long dcId) {
// Transaction txn = Transaction.currentTxn();
// List<PortForwardingRuleVO> forwardings = new ArrayList<PortForwardingRuleVO>();
// PreparedStatement pstmt = null;
// try {
// pstmt = txn.prepareAutoCloseStatement(SELECT_IP_FORWARDINGS_BY_USERID_AND_DCID_SQL);
// pstmt.setLong(1, userId);
// pstmt.setLong(2, dcId);
// ResultSet rs = pstmt.executeQuery();
// while (rs.next()) {
// forwardings.add(toEntityBean(rs, false));
// }
// } catch (Exception e) {
// s_logger.warn(e);
// }
// return forwardings;
// }
//
// @Override
// public void deleteIPForwardingByPublicIpAddress(String ipAddress) {
// Transaction txn = Transaction.currentTxn();
// PreparedStatement pstmt = null;
// try {
// pstmt = txn.prepareAutoCloseStatement(DELETE_IP_FORWARDING_BY_IPADDRESS_SQL);
// pstmt.setString(1, ipAddress);
// pstmt.executeUpdate();
// } catch (Exception e) {
// s_logger.warn(e);
// }
// }
//
// @Override
// public void deleteIPForwardingByPublicIpAndPort(String ipAddress, String port) {
// Transaction txn = Transaction.currentTxn();
// PreparedStatement pstmt = null;
// try {
// pstmt = txn.prepareAutoCloseStatement(DELETE_IP_FORWARDING_BY_IP_PORT_SQL);
// pstmt.setString(1, ipAddress);
// pstmt.setString(2, port);
//
// pstmt.executeUpdate();
// } catch (Exception e) {
// s_logger.warn(e);
// }
// }
//
// @Override
// public List<PortForwardingRuleVO> listIPForwarding(String publicIPAddress) {
// SearchCriteria<PortForwardingRuleVO> sc = FWByIPSearch.create();
// sc.setParameters("publicIpAddress", publicIPAddress);
// return listBy(sc);
// }
//
// @Override
// public List<PortForwardingRuleVO> listIPForwardingForUpdate(String publicIPAddress) {
// SearchCriteria<PortForwardingRuleVO> sc = FWByIPSearch.create();
// sc.setParameters("publicIpAddress", publicIPAddress);
// return listBy(sc, null);
// }
//
// @Override
// public List<PortForwardingRuleVO> listIPForwardingForUpdate(String publicIp, boolean fwding) {
// SearchCriteria<PortForwardingRuleVO> sc = FWByIPAndForwardingSearch.create();
// sc.setParameters("publicIpAddress", publicIp);
// sc.setParameters("forwarding", fwding);
// return search(sc, null);
// }
//
// @Override
// public List<PortForwardingRuleVO> listIPForwardingForUpdate(String publicIp,
// String publicPort, String proto) {
// SearchCriteria<PortForwardingRuleVO> sc = FWByIPPortProtoSearch.create();
// sc.setParameters("publicIpAddress", publicIp);
// sc.setParameters("publicPort", publicPort);
// sc.setParameters("protocol", proto);
// return search(sc, null);
// }
//
// @Override
// public List<PortForwardingRuleVO> listLoadBalanceRulesForUpdate(String publicIp,
// String publicPort, String algo) {
// SearchCriteria<PortForwardingRuleVO> sc = FWByIPPortAlgoSearch.create();
// sc.setParameters("publicIpAddress", publicIp);
// sc.setParameters("publicPort", publicPort);
// sc.setParameters("algorithm", algo);
// return listBy(sc, null);
// }
//
// @Override
// public List<PortForwardingRuleVO> listIPForwarding(String publicIPAddress,
// String port, boolean forwarding) {
// SearchCriteria<PortForwardingRuleVO> sc = FWByIPPortAndForwardingSearch.create();
// sc.setParameters("publicIpAddress", publicIPAddress);
// sc.setParameters("publicPort", port);
// sc.setParameters("forwarding", forwarding);
//
// return listBy(sc);
// }
//
// @Override
// public void disableIPForwarding(String publicIPAddress) {
// Transaction txn = Transaction.currentTxn();
// PreparedStatement pstmt = null;
// try {
// txn.start();
// pstmt = txn.prepareAutoCloseStatement(DISABLE_IP_FORWARDING_BY_IPADDRESS_SQL);
// pstmt.setString(1, publicIPAddress);
// pstmt.executeUpdate();
// txn.commit();
// } catch (Exception e) {
// txn.rollback();
// throw new CloudRuntimeException("DB Exception ", e);
// }
// }
//
// @Override
// public List<PortForwardingRuleVO> listRulesExcludingPubIpPort(String publicIpAddress, long securityGroupId) {
// SearchCriteria<PortForwardingRuleVO> sc = RulesExcludingPubIpPort.create();
// sc.setParameters("publicIpAddress", publicIpAddress);
// sc.setParameters("groupId", securityGroupId);
// sc.setParameters("forwarding", false);
// return listBy(sc);
// }
//
// @Override
// public List<PortForwardingRuleVO> listBySecurityGroupId(long securityGroupId) {
// SearchCriteria<PortForwardingRuleVO> sc = FWByGroupId.create();
// sc.setParameters("groupId", securityGroupId);
// sc.setParameters("forwarding", Boolean.TRUE);
// return listBy(sc);
// }
//
// @Override
// public List<PortForwardingRuleVO> listForwardingByPubAndPrivIp(boolean forwarding, String publicIPAddress, String privateIp) {
// SearchCriteria<PortForwardingRuleVO> sc = FWByIPAndForwardingSearch.create();
// sc.setParameters("publicIpAddress", publicIPAddress);
// sc.setParameters("forwarding", forwarding);
// sc.addAnd("privateIpAddress", SearchCriteria.Op.EQ, privateIp);
// return listBy(sc);
// }
//
// @Override
// public List<PortForwardingRuleVO> listByLoadBalancerId(long loadBalancerId) {
// SearchCriteria<PortForwardingRuleVO> sc = FWByGroupId.create();
// sc.setParameters("groupId", loadBalancerId);
// sc.setParameters("forwarding", Boolean.FALSE);
// return listBy(sc);
// }
//
// @Override
// public PortForwardingRuleVO findByGroupAndPrivateIp(long groupId, String privateIp, boolean forwarding) {
// SearchCriteria<PortForwardingRuleVO> sc = FWByGroupAndPrivateIp.create();
// sc.setParameters("groupId", groupId);
// sc.setParameters("privateIpAddress", privateIp);
// sc.setParameters("forwarding", forwarding);
// return findOneBy(sc);
//
// }
//
// @Override
// public List<PortForwardingRuleVO> findByPublicIpPrivateIpForNatRule(String publicIp, String privateIp){
// SearchCriteria<PortForwardingRuleVO> sc = FWByPrivateIpPrivatePortPublicIpPublicPortSearch.create();
// sc.setParameters("publicIpAddress", publicIp);
// sc.setParameters("privateIpAddress", privateIp);
// return listBy(sc);
// }
//
// @Override
// public List<PortForwardingRuleVO> listByPrivateIp(String privateIp) {
// SearchCriteria<PortForwardingRuleVO> sc = FWByPrivateIPSearch.create();
// sc.setParameters("privateIpAddress", privateIp);
// return listBy(sc);
// }
//
// @Override
// public List<PortForwardingRuleVO> listIPForwardingByPortAndProto(String publicIp,
// String publicPort, String proto) {
// SearchCriteria<PortForwardingRuleVO> sc = FWByIPPortProtoSearch.create();
// sc.setParameters("publicIpAddress", publicIp);
// sc.setParameters("publicPort", publicPort);
// sc.setParameters("protocol", proto);
// return search(sc, null);
// }
//
// @Override
// public boolean isPublicIpOneToOneNATted(String publicIp) {
// SearchCriteria<PortForwardingRuleVO> sc = OneToOneNATSearch.create();
// sc.setParameters("publicIpAddress", publicIp);
// sc.setParameters("protocol", NetUtils.NAT_PROTO);
// List<PortForwardingRuleVO> rules = search(sc, null);
// if (rules.size() != 1)
// return false;
// return rules.get(1).getProtocol().equalsIgnoreCase(NetUtils.NAT_PROTO);
// }
//
// @Override
// public List<PortForwardingRuleVO> listIpForwardingRulesForLoadBalancers(
// String publicIp) {
// SearchCriteria<PortForwardingRuleVO> sc = FWByIpForLB.create();
// sc.setParameters("publicIpAddress", publicIp);
// sc.setParameters("forwarding", false);
// return search(sc, null);
// }
//
// @Override
// public List<PortForwardingRuleVO> listIPForwardingForLB(long userId, long dcId) {
// Transaction txn = Transaction.currentTxn();
// List<PortForwardingRuleVO> forwardings = new ArrayList<PortForwardingRuleVO>();
// PreparedStatement pstmt = null;
// try {
// pstmt = txn.prepareAutoCloseStatement(SELECT_LB_FORWARDINGS_BY_USERID_AND_DCID_SQL);
// pstmt.setLong(1, userId);
// pstmt.setLong(2, dcId);
// ResultSet rs = pstmt.executeQuery();
// while (rs.next()) {
// forwardings.add(toEntityBean(rs, false));
// }
// } catch (Exception e) {
// s_logger.warn(e);
// }
// return forwardings;
// }
}

View File

@ -50,12 +50,12 @@ public class LoadBalancerDaoImpl extends GenericDaoBase<LoadBalancerVO, Long> im
protected LoadBalancerDaoImpl() {
ListByIp = createSearchBuilder();
ListByIp.and("ipAddress", ListByIp.entity().getIpAddress(), SearchCriteria.Op.EQ);
ListByIp.and("ipAddress", ListByIp.entity().getSourceIpAddress(), SearchCriteria.Op.EQ);
ListByIp.done();
IpAndPublicPortSearch = createSearchBuilder();
IpAndPublicPortSearch.and("ipAddress", IpAndPublicPortSearch.entity().getIpAddress(), SearchCriteria.Op.EQ);
IpAndPublicPortSearch.and("publicPort", IpAndPublicPortSearch.entity().getPublicPort(), SearchCriteria.Op.EQ);
IpAndPublicPortSearch.and("ipAddress", IpAndPublicPortSearch.entity().getSourceIpAddress(), SearchCriteria.Op.EQ);
IpAndPublicPortSearch.and("publicPort", IpAndPublicPortSearch.entity().getSourcePortStart(), SearchCriteria.Op.EQ);
IpAndPublicPortSearch.done();
AccountAndNameSearch = createSearchBuilder();

View File

@ -18,8 +18,8 @@
package com.cloud.network.dao;
import java.util.List;
import java.util.List;
import com.cloud.network.LoadBalancerVMMapVO;
import com.cloud.utils.db.GenericDao;

View File

@ -17,6 +17,8 @@
*/
package com.cloud.network.element;
import java.util.List;
import javax.ejb.Local;
import org.apache.log4j.Logger;
@ -26,11 +28,12 @@ import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.InsufficientNetworkCapacityException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.network.Networks.TrafficType;
import com.cloud.network.Network;
import com.cloud.network.NetworkManager;
import com.cloud.network.Networks.TrafficType;
import com.cloud.network.dao.NetworkDao;
import com.cloud.network.router.DomainRouterManager;
import com.cloud.network.rules.FirewallRule;
import com.cloud.offering.NetworkOffering;
import com.cloud.offering.NetworkOffering.GuestIpType;
import com.cloud.uservm.UserVm;
@ -114,17 +117,12 @@ public class DomainRouterElement extends AdapterBase implements NetworkElement {
return _routerMgr.stopRouter(router.getId(), 1);
}
@Override
public boolean addRule() {
return false;
}
@Override
public boolean revokeRule() {
return false;
}
protected DomainRouterElement() {
super();
}
@Override
public boolean applyRules(Network config, List<? extends FirewallRule> rules) throws ResourceUnavailableException {
return false;
}
}

View File

@ -15,12 +15,10 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.cloud.agent.api.routing;
package com.cloud.network.lb;
import com.cloud.agent.api.Command;
import com.cloud.utils.net.Ip;
public abstract class RoutingCommand extends Command {
protected RoutingCommand() {
super();
}
public interface LoadBalancingRulesManager extends LoadBalancingRulesService {
boolean removeAllLoadBalanacers(Ip ip);
}

File diff suppressed because it is too large Load Diff

View File

@ -105,7 +105,6 @@ import com.cloud.host.dao.HostDao;
import com.cloud.hypervisor.Hypervisor;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.network.DomainRouterService;
import com.cloud.network.FirewallRuleVO;
import com.cloud.network.IPAddressVO;
import com.cloud.network.Network;
import com.cloud.network.NetworkManager;
@ -123,6 +122,7 @@ import com.cloud.network.dao.NetworkRuleConfigDao;
import com.cloud.network.dao.RemoteAccessVpnDao;
import com.cloud.network.dao.VpnUserDao;
import com.cloud.network.router.VirtualRouter.Role;
import com.cloud.network.rules.PortForwardingRuleVO;
import com.cloud.offering.NetworkOffering;
import com.cloud.offerings.NetworkOfferingVO;
import com.cloud.offerings.dao.NetworkOfferingDao;
@ -272,10 +272,11 @@ public class DomainRouterManagerImpl implements DomainRouterManager, DomainRoute
ModifySshKeysCommand cmd = new ModifySshKeysCommand(pubKey, prvKey);
final Answer answer = _agentMgr.easySend(hostId, cmd);
if (answer != null)
return true;
else
return false;
if (answer != null) {
return true;
} else {
return false;
}
}
@Override
@ -297,8 +298,9 @@ public class DomainRouterManagerImpl implements DomainRouterManager, DomainRoute
if (pod == null) {
throw new ConcurrentOperationException("Unable to acquire lock on pod " + podId );
}
if(s_logger.isDebugEnabled())
s_logger.debug("Lock on pod " + podId + " is acquired");
if(s_logger.isDebugEnabled()) {
s_logger.debug("Lock on pod " + podId + " is acquired");
}
final long id = _routerDao.getNextInSequence(Long.class, "id");
final String[] macAddresses = _dcDao.getNextAvailableMacAddressPair(dc.getId());
@ -407,8 +409,9 @@ public class DomainRouterManagerImpl implements DomainRouterManager, DomainRoute
_routerDao.releaseFromLockTable(id);
}
if (pod != null) {
if(s_logger.isDebugEnabled())
s_logger.debug("Releasing lock on pod " + podId);
if(s_logger.isDebugEnabled()) {
s_logger.debug("Releasing lock on pod " + podId);
}
_podDao.releaseFromLockTable(pod.getId());
}
}
@ -432,8 +435,9 @@ public class DomainRouterManagerImpl implements DomainRouterManager, DomainRoute
throw new ConcurrentOperationException("Unable to acquire account " + accountId);
}
if(s_logger.isDebugEnabled())
s_logger.debug("lock on account " + accountId + " for createRouter is acquired");
if(s_logger.isDebugEnabled()) {
s_logger.debug("lock on account " + accountId + " for createRouter is acquired");
}
final Transaction txn = Transaction.currentTxn();
DomainRouterVO router = null;
@ -574,8 +578,9 @@ public class DomainRouterManagerImpl implements DomainRouterManager, DomainRoute
return null;
} finally {
if (account != null) {
if(s_logger.isDebugEnabled())
s_logger.debug("Releasing lock on account " + account.getId() + " for createRouter");
if(s_logger.isDebugEnabled()) {
s_logger.debug("Releasing lock on account " + account.getId() + " for createRouter");
}
_accountDao.releaseFromLockTable(account.getId());
}
if(!success){
@ -632,8 +637,9 @@ public class DomainRouterManagerImpl implements DomainRouterManager, DomainRoute
return false;
}
} finally {
if (s_logger.isDebugEnabled())
if (s_logger.isDebugEnabled()) {
s_logger.debug("Release lock on router " + routerId + " for stop");
}
_routerDao.releaseFromLockTable(routerId);
}
@ -699,10 +705,11 @@ public class DomainRouterManagerImpl implements DomainRouterManager, DomainRoute
}
router.setServiceOfferingId(serviceOfferingId);
if (_routerDao.update(routerId, router))
return _routerDao.findById(routerId);
else
if (_routerDao.update(routerId, router)) {
return _routerDao.findById(routerId);
} else {
throw new CloudRuntimeException("Unable to upgrade router " + routerId);
}
}
@ -781,8 +788,9 @@ public class DomainRouterManagerImpl implements DomainRouterManager, DomainRoute
AsyncJobExecutor asyncExecutor = BaseAsyncJobExecutor.getCurrentExecutor();
if (asyncExecutor != null) {
AsyncJobVO job = asyncExecutor.getJob();
if (s_logger.isInfoEnabled())
if (s_logger.isInfoEnabled()) {
s_logger.info("Start router " + routerId + ", update async job-" + job.getId());
}
_asyncMgr.updateAsyncJobAttachment(job.getId(), "domain_router", routerId);
}
@ -792,8 +800,9 @@ public class DomainRouterManagerImpl implements DomainRouterManager, DomainRoute
return router;
}
if(s_logger.isDebugEnabled())
s_logger.debug("Lock on router " + routerId + " is acquired");
if(s_logger.isDebugEnabled()) {
s_logger.debug("Lock on router " + routerId + " is acquired");
}
boolean started = false;
String vnet = null;
@ -1024,10 +1033,11 @@ public class DomainRouterManagerImpl implements DomainRouterManager, DomainRoute
router.setPrivateIpAddress(null);
if(_defaultHypervisorType == null || !_defaultHypervisorType.equalsIgnoreCase(Hypervisor.HypervisorType.VmWare.toString()))
_dcDao.releaseLinkLocalIpAddress(privateIpAddress, router.getDataCenterId(), router.getId());
else
_dcDao.releasePrivateIpAddress(privateIpAddress, router.getDataCenterId(), router.getId());
if(_defaultHypervisorType == null || !_defaultHypervisorType.equalsIgnoreCase(Hypervisor.HypervisorType.VmWare.toString())) {
_dcDao.releaseLinkLocalIpAddress(privateIpAddress, router.getDataCenterId(), router.getId());
} else {
_dcDao.releasePrivateIpAddress(privateIpAddress, router.getDataCenterId(), router.getId());
}
_storageMgr.unshare(router, vols, routingHost);
} while (--retry > 0 && (routingHost = (HostVO)_agentMgr.findHost(Host.Type.Routing, dc, pod, sp, offering, template, router, null, avoid)) != null);
@ -1093,8 +1103,9 @@ public class DomainRouterManagerImpl implements DomainRouterManager, DomainRoute
}
if (router != null) {
if(s_logger.isDebugEnabled())
s_logger.debug("Releasing lock on router " + routerId);
if(s_logger.isDebugEnabled()) {
s_logger.debug("Releasing lock on router " + routerId);
}
_routerDao.releaseFromLockTable(routerId);
}
@ -1138,17 +1149,17 @@ public class DomainRouterManagerImpl implements DomainRouterManager, DomainRoute
return false;
}
}
final List<FirewallRuleVO> fwRules = new ArrayList<FirewallRuleVO>();
for (final IPAddressVO ipVO : ipAddrs) {
//We need only firewall rules that are either forwarding or for load balancers
fwRules.addAll(_rulesDao.listIPForwarding(ipVO.getAddress(), true));
fwRules.addAll(_rulesDao.listIpForwardingRulesForLoadBalancers(ipVO.getAddress()));
}
final List<FirewallRuleVO> result = _networkMgr.updateFirewallRules(router
.getPublicIpAddress(), fwRules, router);
if (result.size() != fwRules.size()) {
return false;
}
final List<PortForwardingRuleVO> fwRules = new ArrayList<PortForwardingRuleVO>();
//FIXME: for (final IPAddressVO ipVO : ipAddrs) {
// //We need only firewall rules that are either forwarding or for load balancers
// fwRules.addAll(_rulesDao.listIPForwarding(ipVO.getAddress(), true));
// fwRules.addAll(_rulesDao.listIpForwardingRulesForLoadBalancers(ipVO.getAddress()));
// }
// final List<PortForwardingRuleVO> result = _networkMgr.updateFirewallRules(router
// .getPublicIpAddress(), fwRules, router);
// if (result.size() != fwRules.size()) {
// return false;
// }
}
return resendDhcpEntries(router) && resendVpnServerData(router);
@ -1158,8 +1169,9 @@ public class DomainRouterManagerImpl implements DomainRouterManager, DomainRoute
final List<UserVmVO> vms = _vmDao.listBy(router.getId(), State.Creating, State.Starting, State.Running, State.Stopping, State.Stopped, State.Migrating);
Commands cmds = new Commands(OnError.Continue);
for (UserVmVO vm: vms) {
if (vm.getGuestIpAddress() == null || vm.getGuestMacAddress() == null || vm.getHostName() == null)
continue;
if (vm.getGuestIpAddress() == null || vm.getGuestMacAddress() == null || vm.getHostName() == null) {
continue;
}
DhcpEntryCommand decmd = new DhcpEntryCommand(vm.getGuestMacAddress(), vm.getGuestIpAddress(), router.getPrivateIpAddress(), vm.getHostName());
cmds.addCommand(decmd);
}
@ -1248,8 +1260,9 @@ public class DomainRouterManagerImpl implements DomainRouterManager, DomainRoute
if (asyncExecutor != null) {
AsyncJobVO job = asyncExecutor.getJob();
if (s_logger.isInfoEnabled())
if (s_logger.isInfoEnabled()) {
s_logger.info("Stop router " + routerId + ", update async job-" + job.getId());
}
_asyncMgr.updateAsyncJobAttachment(job.getId(), "domain_router", routerId);
}
@ -1365,8 +1378,9 @@ public class DomainRouterManagerImpl implements DomainRouterManager, DomainRoute
if (asyncExecutor != null) {
AsyncJobVO job = asyncExecutor.getJob();
if (s_logger.isInfoEnabled())
if (s_logger.isInfoEnabled()) {
s_logger.info("Reboot router " + routerId + ", update async job-" + job.getId());
}
_asyncMgr.updateAsyncJobAttachment(job.getId(), "domain_router", routerId);
}
@ -1428,10 +1442,11 @@ public class DomainRouterManagerImpl implements DomainRouterManager, DomainRoute
}
long eventId = EventUtils.saveScheduledEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM, EventTypes.EVENT_ROUTER_REBOOT, "rebooting Router with Id: "+routerId);
if (rebootRouter(routerId, eventId))
return _routerDao.findById(routerId);
else
throw new CloudRuntimeException("Fail to reboot router " + routerId);
if (rebootRouter(routerId, eventId)) {
return _routerDao.findById(routerId);
} else {
throw new CloudRuntimeException("Fail to reboot router " + routerId);
}
}
@Override
@ -1579,10 +1594,11 @@ public class DomainRouterManagerImpl implements DomainRouterManager, DomainRoute
String privateIpAddress = router.getPrivateIpAddress();
if (privateIpAddress != null) {
if(_defaultHypervisorType == null || !_defaultHypervisorType.equalsIgnoreCase(Hypervisor.HypervisorType.VmWare.toString()))
_dcDao.releaseLinkLocalIpAddress(privateIpAddress, router.getDataCenterId(), router.getId());
else
_dcDao.releasePrivateIpAddress(privateIpAddress, router.getDataCenterId(), router.getId());
if(_defaultHypervisorType == null || !_defaultHypervisorType.equalsIgnoreCase(Hypervisor.HypervisorType.VmWare.toString())) {
_dcDao.releaseLinkLocalIpAddress(privateIpAddress, router.getDataCenterId(), router.getId());
} else {
_dcDao.releasePrivateIpAddress(privateIpAddress, router.getDataCenterId(), router.getId());
}
}
router.setPrivateIpAddress(null);
@ -1661,8 +1677,9 @@ public class DomainRouterManagerImpl implements DomainRouterManager, DomainRoute
try {
if(s_logger.isDebugEnabled())
s_logger.debug("Lock on router " + routerId + " for stop is acquired");
if(s_logger.isDebugEnabled()) {
s_logger.debug("Lock on router " + routerId + " for stop is acquired");
}
if (router.getRemoved() != null) {
s_logger.debug("router " + routerId + " is removed");
@ -1730,8 +1747,9 @@ public class DomainRouterManagerImpl implements DomainRouterManager, DomainRoute
processStopOrRebootAnswer(router, answer);
} finally {
if(s_logger.isDebugEnabled())
if(s_logger.isDebugEnabled()) {
s_logger.debug("Release lock on router " + routerId + " for stop");
}
_routerDao.releaseFromLockTable(routerId);
}
return true;
@ -2427,15 +2445,15 @@ public class DomainRouterManagerImpl implements DomainRouterManager, DomainRoute
return false;
}
}
final List<FirewallRuleVO> fwRules = new ArrayList<FirewallRuleVO>();
for (final IPAddressVO ipVO : ipAddrs) {
fwRules.addAll(_rulesDao.listIPForwarding(ipVO.getAddress()));
}
final List<FirewallRuleVO> result = _networkMgr.updateFirewallRules(router
.getPublicIpAddress(), fwRules, router);
if (result.size() != fwRules.size()) {
return false;
}
// FIXME final List<PortForwardingRuleVO> fwRules = new ArrayList<PortForwardingRuleVO>();
// for (final IPAddressVO ipVO : ipAddrs) {
// fwRules.addAll(_rulesDao.listIPForwarding(ipVO.getAddress()));
// }
// final List<PortForwardingRuleVO> result = _networkMgr.updateFirewallRules(router
// .getPublicIpAddress(), fwRules, router);
// if (result.size() != fwRules.size()) {
// return false;
// }
}
return resendDhcpEntries(router) && resendVpnServerData(router);
@ -2445,8 +2463,9 @@ public class DomainRouterManagerImpl implements DomainRouterManager, DomainRoute
final List<UserVmVO> vms = _vmDao.listBy(router.getId(), State.Creating, State.Starting, State.Running, State.Stopping, State.Stopped, State.Migrating);
Commands cmds = new Commands(OnError.Continue);
for (UserVmVO vm: vms) {
if (vm.getGuestIpAddress() == null || vm.getGuestMacAddress() == null || vm.getHostName() == null)
if (vm.getGuestIpAddress() == null || vm.getGuestMacAddress() == null || vm.getHostName() == null) {
continue;
}
DhcpEntryCommand decmd = new DhcpEntryCommand(vm.getGuestMacAddress(), vm.getGuestIpAddress(), router.getPrivateIpAddress(), vm.getHostName());
cmds.addCommand(decmd);
}

View File

@ -0,0 +1,170 @@
/**
* Copyright (C) 2010 Cloud.com, Inc. All rights reserved.
*
* This software is licensed under the GNU General Public License v3 or later.
*
* It is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.cloud.network.rules;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.DiscriminatorType;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.Table;
import com.cloud.utils.db.GenericDao;
import com.cloud.utils.net.Ip;
@Entity
@Table(name="firewall_rules")
@Inheritance(strategy=InheritanceType.JOINED)
@DiscriminatorColumn(name="purpose", discriminatorType=DiscriminatorType.STRING, length=32)
public class FirewallRuleVO implements FirewallRule {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
long id;
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name=GenericDao.XID_COLUMN)
String xId;
@Column(name="domain_id", updatable=false)
long domainId;
@Column(name="account_id", updatable=false)
long accountId;
@Column(name="ip_address", updatable=false)
Ip sourceIpAddress;
@Column(name="port_start", updatable=false)
int sourcePortStart;
@Column(name="port_end", updatable=false)
int sourcePortEnd;
@Column(name="protocol", updatable=false)
String protocol = "TCP";
@Enumerated(value=EnumType.STRING)
@Column(name="purpose")
Purpose purpose;
@Enumerated(value=EnumType.STRING)
@Column(name="state")
State state;
@Column(name=GenericDao.CREATED_COLUMN)
Date created;
@Column(name="network_id")
long networkId;
@Override
public long getAccountId() {
return accountId;
}
@Override
public long getDomainId() {
return domainId;
}
@Override
public long getId() {
return id;
}
@Override
public String getXid() {
return xId;
}
@Override
public Ip getSourceIpAddress() {
return sourceIpAddress;
}
@Override
public int getSourcePortStart() {
return sourcePortStart;
}
@Override
public int getSourcePortEnd() {
return sourcePortEnd;
}
@Override
public String getProtocol() {
return protocol;
}
public void setState(State state) {
this.state = state;
}
@Override
public Purpose getPurpose() {
return purpose;
}
@Override
public State getState() {
return state;
}
public long getNetworkId() {
return networkId;
}
public Date getCreated() {
return created;
}
protected FirewallRuleVO() {
}
public FirewallRuleVO(String xId, Ip srcIp, int portStart, int portEnd, String protocol, long networkId, long accountId, long domainId, Purpose purpose) {
this.xId = xId;
this.accountId = accountId;
this.domainId = domainId;
this.sourceIpAddress = srcIp;
this.sourcePortStart = portStart;
this.sourcePortEnd = portEnd;
this.protocol = protocol;
this.purpose = purpose;
this.networkId = networkId;
this.state = State.Staged;
}
public FirewallRuleVO(String xId, Ip srcIp, int port, String protocol, long networkId, long accountId, long domainId, Purpose purpose) {
this(xId, srcIp, port, port, protocol, networkId, accountId, domainId, purpose);
}
@Override
public String toString() {
return new StringBuilder("Rule[").append(id).append("-").append(purpose).append("-").append(state).append("]").toString();
}
}

View File

@ -0,0 +1,76 @@
/**
* Copyright (C) 2010 Cloud.com, Inc. All rights reserved.
*
* This software is licensed under the GNU General Public License v3 or later.
*
* It is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.cloud.network.rules;
import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import com.cloud.utils.net.Ip;
@Entity
@Table(name=("port_forwarding_rule"))
@DiscriminatorValue(value="PortForwarding")
@PrimaryKeyJoinColumn(name="id")
public class PortForwardingRuleVO extends FirewallRuleVO implements PortForwardingRule {
@Enumerated(value=EnumType.STRING)
@Column(name="dest_ip_address")
private Ip destinationIpAddress = null;
@Column(name="dest_port_start")
private int destinationPortStart;
@Column(name="dest_port_end")
private int destinationPortEnd;
public PortForwardingRuleVO() {
}
public PortForwardingRuleVO(String xId, Ip srcIp, int srcPortStart, int srcPortEnd, Ip dstIp, int dstPortStart, int dstPortEnd, String protocol, long networkId, long accountId, long domainId) {
super(xId, srcIp, srcPortStart, srcPortEnd, protocol, networkId, accountId, domainId, Purpose.PortForwarding);
this.destinationIpAddress = dstIp;
this.destinationPortStart = dstPortStart;
this.destinationPortEnd = dstPortEnd;
}
public PortForwardingRuleVO(String xId, Ip srcIp, int srcPort, Ip dstIp, int dstPort, String protocol, long networkId, long accountId, long domainId) {
this(xId, srcIp, srcPort, srcPort, dstIp, dstPort, dstPort, protocol, networkId, accountId, domainId);
}
@Override
public Ip getDestinationIpAddress() {
return destinationIpAddress;
}
@Override
public int getDestinationPortStart() {
return destinationPortStart;
}
@Override
public int getDestinationPortEnd() {
return destinationPortEnd;
}
}

View File

@ -17,113 +17,41 @@
*/
package com.cloud.network.rules;
import java.util.List;
import com.cloud.api.commands.AddVpnUserCmd;
import com.cloud.api.commands.AssignToLoadBalancerRuleCmd;
import com.cloud.api.commands.CreateLoadBalancerRuleCmd;
import com.cloud.api.commands.CreatePortForwardingRuleCmd;
import com.cloud.api.commands.CreateRemoteAccessVpnCmd;
import com.cloud.api.commands.DeleteLoadBalancerRuleCmd;
import com.cloud.api.commands.DeleteRemoteAccessVpnCmd;
import com.cloud.api.commands.ListPortForwardingRulesCmd;
import com.cloud.api.commands.RemoveFromLoadBalancerRuleCmd;
import com.cloud.api.commands.RemoveVpnUserCmd;
import com.cloud.api.commands.UpdateLoadBalancerRuleCmd;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.NetworkRuleConflictException;
import com.cloud.exception.PermissionDeniedException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.network.FirewallRuleVO;
import com.cloud.network.LoadBalancerVO;
import com.cloud.network.RemoteAccessVpnVO;
import com.cloud.network.VpnUserVO;
import com.cloud.vm.DomainRouterVO;
import com.cloud.network.IpAddress;
import com.cloud.user.Account;
import com.cloud.uservm.UserVm;
import com.cloud.utils.net.Ip;
public interface RulesManager {
/**
* Rules Manager manages the network rules created for different networks.
*/
public interface RulesManager extends RulesService {
PortForwardingRule revokePortForwardingRule(String ruleId, Account caller);
boolean applyPortForwardingRules(Ip ip, boolean continueOnError);
/**
* @param fwRules list of rules to be updated
* @param router router where the rules have to be updated
* @return list of rules successfully updated
*/
List<FirewallRuleVO> updatePortForwardingRules(List<FirewallRuleVO> fwRules, DomainRouterVO router, Long hostId);
/**
* @param fwRules list of rules to be updated
* @param router router where the rules have to be updated
* @return success
*/
boolean updateLoadBalancerRules(List<FirewallRuleVO> fwRules, DomainRouterVO router, Long hostId);
* detectRulesConflict finds conflicts in networking rules. It checks for
* conflicts between the following types of netowrking rules;
* 1. one to one nat ip forwarding
* 2. port forwarding
* 3. load balancing
*
* It is possible for two conflicting rules to be added at the same time
* and conflicts are detected between those two rules. In this case, it
* is possible for both rules to be rolled back when, technically, we should
* only roll back one of the rules. However, the chances of that is low
* and the user can simply re-add one of the rules themselves.
*
* @param newRule the new rule created.
* @param ipAddress ip address that back up the new rule.
* @throws NetworkRuleConflictException
*/
void detectRulesConflict(FirewallRule newRule, IpAddress ipAddress) throws NetworkRuleConflictException;
/**
* @param publicIpAddress ip address associated with the fwRules
* @param fwRules list of rules to be updated
* @param router router where the rules have to be updated
* @return list of rules successfully updated
*/
List<FirewallRuleVO> updateFirewallRules(String publicIpAddress, List<FirewallRuleVO> fwRules, DomainRouterVO router);
/**
* Create a port forwarding rule from the given ipAddress/port to the given virtual machine/port.
* @param cmd the command specifying the ip address, port, protocol, private port, and virtual machine id.
* @return the newly created FirewallRuleVO if successful, null otherwise.
*/
FirewallRuleVO createPortForwardingRule(CreatePortForwardingRuleCmd cmd) throws NetworkRuleConflictException;
/**
* List port forwarding rules assigned to an ip address
* @param cmd the command object holding the criteria for listing port forwarding rules (the ipAddress)
* @return list of port forwarding rules on the given address, empty list if no rules exist
*/
List<FirewallRuleVO> listPortForwardingRules(ListPortForwardingRulesCmd cmd);
/**
* Create a load balancer rule from the given ipAddress/port to the given private port
* @param cmd the command specifying the ip address, port, protocol, private port, and algorithm
* @return the newly created LoadBalancerVO if successful, null otherwise
*/
LoadBalancerVO createLoadBalancerRule(CreateLoadBalancerRuleCmd cmd);
boolean updateFirewallRule(FirewallRuleVO fwRule, String oldPrivateIP, String oldPrivatePort);
/**
* Assign a virtual machine, or list of virtual machines, to a load balancer.
*/
boolean assignToLoadBalancer(AssignToLoadBalancerRuleCmd cmd) throws NetworkRuleConflictException;
boolean removeFromLoadBalancer(RemoveFromLoadBalancerRuleCmd cmd);
boolean deleteLoadBalancerRule(DeleteLoadBalancerRuleCmd cmd);
LoadBalancerVO updateLoadBalancerRule(UpdateLoadBalancerRuleCmd cmd);
RemoteAccessVpnVO createRemoteAccessVpn(CreateRemoteAccessVpnCmd cmd) throws ConcurrentOperationException, InvalidParameterValueException, PermissionDeniedException;
/**
* Start a remote access vpn for the given ip address and client ip range
* @param cmd the command specifying the ip address, ip range
* @return the RemoteAccessVpnVO if successful, null otherwise
* @throws ConcurrentOperationException
* @throws ResourceUnavailableException
*/
RemoteAccessVpnVO startRemoteAccessVpn(CreateRemoteAccessVpnCmd cmd) throws ConcurrentOperationException, ResourceUnavailableException;
/**
* Destroy a previously created remote access VPN
* @param cmd the command specifying the account and zone
* @return success if successful, false otherwise
* @throws ConcurrentOperationException
*/
boolean destroyRemoteAccessVpn(DeleteRemoteAccessVpnCmd cmd) throws ConcurrentOperationException;
VpnUserVO addVpnUser(AddVpnUserCmd cmd) throws ConcurrentOperationException;
boolean removeVpnUser(RemoveVpnUserCmd cmd) throws ConcurrentOperationException;
FirewallRuleVO createIpForwardingRuleInDb(String ipAddr, Long virtualMachineId);
boolean deletePortForwardingRule(Long id, boolean sysContext);
boolean deleteIpForwardingRule(Long id);
void checkIpAndUserVm(IpAddress ipAddress, UserVm userVm, Account caller) throws InvalidParameterValueException, PermissionDeniedException;
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,57 @@
/**
* Copyright (C) 2010 Cloud.com, Inc. All rights reserved.
*
* This software is licensed under the GNU General Public License v3 or later.
*
* It is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.cloud.network.rules.dao;
import java.util.List;
import javax.ejb.Local;
import com.cloud.network.rules.FirewallRule.State;
import com.cloud.network.rules.PortForwardingRuleVO;
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;
import com.cloud.utils.net.Ip;
@Local(value=PortForwardingRulesDao.class)
public class PortForwardingRuleDaoImpl extends GenericDaoBase<PortForwardingRuleVO, Long> implements PortForwardingRulesDao {
protected final SearchBuilder<PortForwardingRuleVO> AllFieldsSearch;
protected final SearchBuilder<PortForwardingRuleVO> ApplicationSearch;
protected PortForwardingRuleDaoImpl() {
super();
AllFieldsSearch = createSearchBuilder();
AllFieldsSearch.and("id", AllFieldsSearch.entity().getId(), Op.EQ);
AllFieldsSearch.done();
ApplicationSearch = createSearchBuilder();
ApplicationSearch.and("ip", ApplicationSearch.entity().getSourceIpAddress(), Op.EQ);
ApplicationSearch.and("state", ApplicationSearch.entity().getState(), Op.NEQ);
}
@Override
public List<PortForwardingRuleVO> listForApplication(Ip ip) {
SearchCriteria<PortForwardingRuleVO> sc = ApplicationSearch.create();
sc.setParameters("ip", ip);
sc.setParameters("state", State.Staged);
return listBy(sc, null);
}
}

View File

@ -0,0 +1,28 @@
/**
* Copyright (C) 2010 Cloud.com, Inc. All rights reserved.
*
* This software is licensed under the GNU General Public License v3 or later.
*
* It is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.cloud.network.rules.dao;
import java.util.List;
import com.cloud.network.rules.PortForwardingRuleVO;
import com.cloud.utils.db.GenericDao;
import com.cloud.utils.net.Ip;
public interface PortForwardingRulesDao extends GenericDao<PortForwardingRuleVO, Long> {
List<PortForwardingRuleVO> listForApplication(Ip ip);
}

View File

@ -34,9 +34,7 @@ import com.cloud.exception.InternalErrorException;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.host.HostVO;
import com.cloud.info.ConsoleProxyInfo;
import com.cloud.network.FirewallRuleVO;
import com.cloud.network.IPAddressVO;
import com.cloud.network.LoadBalancerVO;
import com.cloud.network.security.NetworkGroupVO;
import com.cloud.service.ServiceOfferingVO;
import com.cloud.storage.DiskOfferingVO;
@ -331,13 +329,6 @@ public interface ManagementServer extends ManagementService {
*/
List<UserVmVO> searchForUserVMs(Criteria c);
/**
* Find a firewall rule by rule id
* @param ruleId
* @return
*/
FirewallRuleVO findForwardingRuleById(Long ruleId);
/**
* Find an IP Address VO object by ip address string
* @param ipAddress
@ -533,9 +524,6 @@ public interface ManagementServer extends ManagementService {
AsyncJobVO findAsyncJobById(long jobId);
LoadBalancerVO findLoadBalancer(Long accountId, String name);
LoadBalancerVO findLoadBalancerById(long loadBalancerId);
String[] getApiConfig();
StoragePoolVO findPoolById(Long id);
List<? extends StoragePoolVO> searchForStoragePools(Criteria c);

View File

@ -97,10 +97,7 @@ import com.cloud.api.commands.ListGuestOsCategoriesCmd;
import com.cloud.api.commands.ListGuestOsCmd;
import com.cloud.api.commands.ListHostsCmd;
import com.cloud.api.commands.ListHypervisorsCmd;
import com.cloud.api.commands.ListIpForwardingRulesCmd;
import com.cloud.api.commands.ListIsosCmd;
import com.cloud.api.commands.ListLoadBalancerRuleInstancesCmd;
import com.cloud.api.commands.ListLoadBalancerRulesCmd;
import com.cloud.api.commands.ListPodsByCmd;
import com.cloud.api.commands.ListPreallocatedLunsCmd;
import com.cloud.api.commands.ListPublicIpAddressesCmd;
@ -126,7 +123,6 @@ import com.cloud.api.commands.StopSystemVmCmd;
import com.cloud.api.commands.UpdateDomainCmd;
import com.cloud.api.commands.UpdateIsoCmd;
import com.cloud.api.commands.UpdateIsoPermissionsCmd;
import com.cloud.api.commands.UpdatePortForwardingRuleCmd;
import com.cloud.api.commands.UpdateTemplateCmd;
import com.cloud.api.commands.UpdateTemplateOrIsoCmd;
import com.cloud.api.commands.UpdateTemplateOrIsoPermissionsCmd;
@ -192,17 +188,11 @@ import com.cloud.host.Status;
import com.cloud.host.dao.HostDao;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.info.ConsoleProxyInfo;
import com.cloud.network.FirewallRuleVO;
import com.cloud.network.IPAddressVO;
import com.cloud.network.LoadBalancerVMMapVO;
import com.cloud.network.LoadBalancerVO;
import com.cloud.network.NetworkManager;
import com.cloud.network.RemoteAccessVpnVO;
import com.cloud.network.VpnUserVO;
import com.cloud.network.dao.FirewallRulesDao;
import com.cloud.network.dao.IPAddressDao;
import com.cloud.network.dao.LoadBalancerDao;
import com.cloud.network.dao.LoadBalancerVMMapDao;
import com.cloud.network.dao.RemoteAccessVpnDao;
import com.cloud.network.dao.VpnUserDao;
import com.cloud.network.security.NetworkGroupManager;
@ -305,12 +295,9 @@ public class ManagementServerImpl implements ManagementServer {
private final AccountManager _accountMgr;
private final AgentManager _agentMgr;
private final ConfigurationManager _configMgr;
private final FirewallRulesDao _firewallRulesDao;
private final NetworkGroupDao _networkSecurityGroupDao;
private final LoadBalancerDao _loadBalancerDao;
private final IPAddressDao _publicIpAddressDao;
private final DataCenterIpAddressDao _privateIpAddressDao;
private final LoadBalancerVMMapDao _loadBalancerVMMapDao;
private final DomainRouterDao _routerDao;
private final ConsoleProxyDao _consoleProxyDao;
private final ClusterDao _clusterDao;
@ -413,12 +400,9 @@ public class ManagementServerImpl implements ManagementServer {
_consoleProxyMgr = locator.getManager(ConsoleProxyManager.class);
_secStorageVmMgr = locator.getManager(SecondaryStorageVmManager.class);
_storageMgr = locator.getManager(StorageManager.class);
_firewallRulesDao = locator.getDao(FirewallRulesDao.class);
_networkSecurityGroupDao = locator.getDao(NetworkGroupDao.class);
_loadBalancerDao = locator.getDao(LoadBalancerDao.class);
_publicIpAddressDao = locator.getDao(IPAddressDao.class);
_privateIpAddressDao = locator.getDao(DataCenterIpAddressDao.class);
_loadBalancerVMMapDao = locator.getDao(LoadBalancerVMMapDao.class);
_consoleProxyDao = locator.getDao(ConsoleProxyDao.class);
_secStorageVmDao = locator.getDao(SecondaryStorageVmDao.class);
_userDao = locator.getDao(UserDao.class);
@ -775,24 +759,29 @@ public class ManagementServerImpl implements ManagementServer {
public List<IPAddressVO> listPublicIpAddressesBy(Long accountId, boolean allocatedOnly, Long zoneId, Long vlanDbId) {
SearchCriteria<IPAddressVO> sc = _publicIpAddressDao.createSearchCriteria();
if (accountId != null)
if (accountId != null) {
sc.addAnd("accountId", SearchCriteria.Op.EQ, accountId);
if (zoneId != null)
}
if (zoneId != null) {
sc.addAnd("dataCenterId", SearchCriteria.Op.EQ, zoneId);
if (vlanDbId != null)
}
if (vlanDbId != null) {
sc.addAnd("vlanDbId", SearchCriteria.Op.EQ, vlanDbId);
if (allocatedOnly)
}
if (allocatedOnly) {
sc.addAnd("allocated", SearchCriteria.Op.NNULL);
}
return _publicIpAddressDao.search(sc, null);
}
@Override
public List<DataCenterIpAddressVO> listPrivateIpAddressesBy(Long podId, Long zoneId) {
if (podId != null && zoneId != null)
if (podId != null && zoneId != null) {
return _privateIpAddressDao.listByPodIdDcId(podId.longValue(), zoneId.longValue());
else
} else {
return new ArrayList<DataCenterIpAddressVO>();
}
}
@Override
@ -914,8 +903,9 @@ public class ManagementServerImpl implements ManagementServer {
if (asyncExecutor != null) {
AsyncJobVO job = asyncExecutor.getJob();
if (s_logger.isInfoEnabled())
if (s_logger.isInfoEnabled()) {
s_logger.info("DeployVM acquired a new instance " + vmId + ", update async job-" + job.getId() + " progress status");
}
_asyncMgr.updateAsyncJobAttachment(job.getId(), "vm_instance", vmId);
_asyncMgr.updateAsyncJobStatus(job.getId(), BaseCmd.PROGRESS_INSTANCE_CREATED, vmId);
@ -1299,33 +1289,39 @@ public class ManagementServerImpl implements ManagementServer {
try {
return deployVirtualMachineImpl(userId, accountId, dataCenterId, serviceOfferingId, template, diskOfferingId, domain, password, displayName, group, userData, networkGroups, eventId, (1L*size*1024));//this api expects size in MB
} catch (ResourceAllocationException e) {
if(s_logger.isDebugEnabled())
if(s_logger.isDebugEnabled()) {
s_logger.debug("Unable to deploy VM: " + e.getMessage());
}
EventUtils.saveEvent(userId, accountId, EventVO.LEVEL_ERROR, EventTypes.EVENT_VM_CREATE, "Unable to deploy VM: VM_INSUFFICIENT_CAPACITY", null, eventId);
throw e;
} catch (ExecutionException e) {
if(s_logger.isDebugEnabled())
if(s_logger.isDebugEnabled()) {
s_logger.debug("Unable to deploy VM: " + e.getMessage());
}
EventUtils.saveEvent(userId, accountId, EventVO.LEVEL_ERROR, EventTypes.EVENT_VM_CREATE, "Unable to deploy VM: VM_HOST_LICENSE_EXPIRED", null, eventId);
throw e;
} catch (InvalidParameterValueException e) {
if(s_logger.isDebugEnabled())
if(s_logger.isDebugEnabled()) {
s_logger.debug("Unable to deploy VM: " + e.getMessage());
}
EventUtils.saveEvent(userId, accountId, EventVO.LEVEL_ERROR, EventTypes.EVENT_VM_CREATE, "Unable to deploy VM: VM_INVALID_PARAM_ERROR", null, eventId);
throw e;
} catch (InsufficientStorageCapacityException e) {
if(s_logger.isDebugEnabled())
if(s_logger.isDebugEnabled()) {
s_logger.debug("Unable to deploy VM: " + e.getMessage());
}
EventUtils.saveEvent(userId, accountId, EventVO.LEVEL_ERROR, EventTypes.EVENT_VM_CREATE, "Unable to deploy VM: VM_INSUFFICIENT_CAPACITY", null, eventId);
throw e;
} catch (PermissionDeniedException e) {
if(s_logger.isDebugEnabled())
if(s_logger.isDebugEnabled()) {
s_logger.debug("Unable to deploy VM: " + e.getMessage());
}
EventUtils.saveEvent(userId, accountId, EventVO.LEVEL_ERROR, EventTypes.EVENT_VM_CREATE, "Unable to deploy VM: ACCOUNT_ERROR", null, eventId);
throw e;
} catch (ConcurrentOperationException e) {
if(s_logger.isDebugEnabled())
if(s_logger.isDebugEnabled()) {
s_logger.debug("Unable to deploy VM: " + e.getMessage());
}
EventUtils.saveEvent(userId, accountId, EventVO.LEVEL_ERROR, EventTypes.EVENT_VM_CREATE, "Unable to deploy VM: INTERNAL_ERROR", null, eventId);
throw e;
} catch(Exception e) {
@ -1363,10 +1359,11 @@ public class ManagementServerImpl implements ManagementServer {
{
while(true){
dcs.addAll(_dcDao.findZonesByDomainId(domainRecord.getId()));
if(domainRecord.getParent() != null)
domainRecord = _domainDao.findById(domainRecord.getParent());
else
break;
if(domainRecord.getParent() != null) {
domainRecord = _domainDao.findById(domainRecord.getParent());
} else {
break;
}
}
}
//add all public zones too
@ -1381,10 +1378,11 @@ public class ManagementServerImpl implements ManagementServer {
DomainVO localRecord = domainRecord;
while(true){
dcs.addAll(_dcDao.findZonesByDomainId(localRecord.getId()));
if(localRecord.getParent() != null)
localRecord = _domainDao.findById(localRecord.getParent());
else
break;
if(localRecord.getParent() != null) {
localRecord = _domainDao.findById(localRecord.getParent());
} else {
break;
}
}
}
//this covers till leaf
@ -1419,8 +1417,9 @@ public class ManagementServerImpl implements ManagementServer {
break;
}
}
if (!found)
if (!found) {
iter.remove();
}
}
}
}
@ -1607,20 +1606,24 @@ public class ManagementServerImpl implements ManagementServer {
private boolean isPermissible(Long accountDomainId, Long offeringDomainId){
if(accountDomainId == offeringDomainId)
return true; // account and service offering in same domain
{
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;
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;
if(domainRecord.getParent() != null) {
domainRecord = _domainDao.findById(domainRecord.getParent());
} else {
break;
}
}
}
@ -1762,10 +1765,12 @@ public class ManagementServerImpl implements ManagementServer {
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
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());
@ -1773,8 +1778,9 @@ public class ManagementServerImpl implements ManagementServer {
}
//add all the public offerings to the sol list before returning
if(includePublicOfferings)
sol.addAll(_offeringsDao.findPublicServiceOfferings());
if(includePublicOfferings) {
sol.addAll(_offeringsDao.findPublicServiceOfferings());
}
return sol;
}
@ -2235,8 +2241,9 @@ public class ManagementServerImpl implements ManagementServer {
@Override
public Account findAccountByName(String accountName, Long domainId) {
if (domainId == null)
if (domainId == null) {
domainId = DomainVO.ROOT_DOMAIN;
}
return _accountDao.findAccount(accountName, domainId);
}
@ -2347,8 +2354,9 @@ public class ManagementServerImpl implements ManagementServer {
@Override
public boolean deleteLimit(Long limitId) {
// A limit ID must be passed in
if (limitId == null)
if (limitId == null) {
return false;
}
return _resourceLimitDao.expunge(limitId);
}
@ -2538,140 +2546,7 @@ public class ManagementServerImpl implements ManagementServer {
public VMTemplateVO findTemplateById(long templateId) {
return _templateDao.findById(templateId);
}
@Override
public List<FirewallRuleVO> searchForIpForwardingRules(ListIpForwardingRulesCmd cmd){
//Note::
//The following was decided after discussing with Will
//ListIpForwardingRules with no params lists the rules for that user ; with a listAll() for admin
//ListIpForwardingRules with accountName and domainId lists the rule for that account (provided the executing user has the right perms)
//ListIpForwardingRules with ipAddress lists the rule for that ip address (provided the executing user has the right perms)
String ipAddress = cmd.getPublicIpAddress();
String accountName = cmd.getAccountName();
Long domainId = cmd.getDomainId();
Account account = null;
if((accountName != null && domainId == null) || (accountName == null && domainId != null)){
throw new ServerApiException(BaseCmd.PARAM_ERROR, "Account name and domain id both have to be passed as a tuple");
}
if(accountName != null && domainId != null && ipAddress != null){
throw new ServerApiException(BaseCmd.PARAM_ERROR, "Either Account name and domain id both have to be passed as a tuple; or the ip address has to be passed whilst searching");
}
//account and domainId both provided case
if(accountName != null && domainId != null){
account = _accountDao.findAccount(accountName, domainId);
if(account == null)
throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, "Specified account for domainId:"+domainId+" account name:"+accountName+" doesn't exist");
else{
//get the ctxaccount to see if he has permissions
Account ctxAccount = UserContext.current().getAccount();
if(!isChildDomain(ctxAccount.getDomainId(), account.getDomainId())){
throw new PermissionDeniedException("Unable to list ip forwarding rules for address " + ipAddress + ", permission denied for the executing account: " + ctxAccount.getId()+" to view rules for account: "+account.getId());
}
Filter searchFilter = new Filter(FirewallRuleVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal());
SearchBuilder<FirewallRuleVO> sb = _firewallRulesDao.createSearchBuilder();
SearchBuilder<IPAddressVO> sb1 = _publicIpAddressDao.createSearchBuilder();
sb1.and("accountId", sb1.entity().getAccountId(), SearchCriteria.Op.EQ);
sb1.and("oneToOneNat", sb1.entity().isOneToOneNat(), SearchCriteria.Op.EQ);
sb.join("sb1", sb1, sb.entity().getPublicIpAddress(),sb1.entity().getAddress(), JoinBuilder.JoinType.INNER);
SearchCriteria<FirewallRuleVO> sc = sb.create();
sc.setJoinParameters("sb1","oneToOneNat", new Long(1));
sc.setJoinParameters("sb1", "accountId", account.getId());
return _firewallRulesDao.search(sc, searchFilter);
}
}
if(account == null){
account = UserContext.current().getAccount();//use user context
}
if(account == null || account.getType() == Account.ACCOUNT_TYPE_ADMIN){
return searchIpForwardingRulesInternal(ipAddress, cmd, null, Account.ACCOUNT_TYPE_ADMIN);
}
if((account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN)){
if(ipAddress != null){
IPAddressVO ipAddressVO = _publicIpAddressDao.findById(ipAddress);
if (ipAddressVO == null) {
throw new InvalidParameterValueException("Unable to find IP address " + ipAddress);
}else{
//check permissions
Account addrOwner = _accountDao.findById(ipAddressVO.getAccountId());
if ((addrOwner != null) && !_domainDao.isChildDomain(account.getDomainId(), addrOwner.getDomainId())) {
throw new PermissionDeniedException("Unable to list ip forwarding rule for address " + ipAddress + ", permission denied for account " + account.getId());
}else{
return searchIpForwardingRulesInternal(ipAddress, cmd, null, Account.ACCOUNT_TYPE_DOMAIN_ADMIN);
}
}
}else{
//need to list all rules visible to the domain admin
//join with the ip_address table where account_id = user's account id
return searchIpForwardingRulesInternal(ipAddress, cmd, account.getId(), Account.ACCOUNT_TYPE_DOMAIN_ADMIN);
}
}
if(account.getType() == Account.ACCOUNT_TYPE_NORMAL){
if(ipAddress != null){
IPAddressVO ipAddressVO = _publicIpAddressDao.findById(ipAddress);
if (ipAddressVO == null) {
throw new InvalidParameterValueException("Unable to find IP address " + ipAddress);
}else{
//check permissions
if ((ipAddressVO.getAccountId() == null) || (account.getId() != ipAddressVO.getAccountId().longValue())) {
throw new PermissionDeniedException("Unable to list ip forwarding rule for address " + ipAddress + ", permission denied for account " + account.getId());
}else{
return searchIpForwardingRulesInternal(ipAddress, cmd, null, Account.ACCOUNT_TYPE_NORMAL);
}
}
}else{
//need to list all rules visible to the user
//join with the ip_address table where account_id = user's account id
return searchIpForwardingRulesInternal(ipAddress, cmd, account.getId(), Account.ACCOUNT_TYPE_NORMAL);
}
}
return new ArrayList<FirewallRuleVO>();
}
private List<FirewallRuleVO> searchIpForwardingRulesInternal(String ipAddress, ListIpForwardingRulesCmd cmd, Long accountId, short accountType){
Filter searchFilter = new Filter(FirewallRuleVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal());
if(accountId == null){
SearchCriteria<FirewallRuleVO> sc = _firewallRulesDao.createSearchCriteria();
if (ipAddress != null) {
sc.addAnd("publicIpAddress", SearchCriteria.Op.EQ, ipAddress);
}
//search for rules with protocol = nat
sc.addAnd("protocol", SearchCriteria.Op.EQ, NetUtils.NAT_PROTO);
return _firewallRulesDao.search(sc, searchFilter);
}else{
//accountId and accountType both given
if((accountType == Account.ACCOUNT_TYPE_NORMAL) || (accountType == Account.ACCOUNT_TYPE_DOMAIN_ADMIN)){
SearchBuilder<FirewallRuleVO> sb = _firewallRulesDao.createSearchBuilder();
SearchBuilder<IPAddressVO> sb1 = _publicIpAddressDao.createSearchBuilder();
sb1.and("accountId", sb1.entity().getAccountId(), SearchCriteria.Op.EQ);
sb1.and("oneToOneNat", sb1.entity().isOneToOneNat(), SearchCriteria.Op.EQ);
sb.join("sb1", sb1, sb.entity().getPublicIpAddress(),sb1.entity().getAddress(), JoinBuilder.JoinType.INNER);
SearchCriteria<FirewallRuleVO> sc = sb.create();
sc.setJoinParameters("sb1","oneToOneNat", new Long(1));
sc.setJoinParameters("sb1", "accountId", accountId);
return _firewallRulesDao.search(sc, searchFilter);
}
}
return new ArrayList<FirewallRuleVO>();
}
@Override
public List<UserVmVO> searchForUserVMs(ListVMsCmd cmd) throws InvalidParameterValueException, PermissionDeniedException {
@ -2862,14 +2737,16 @@ public class ManagementServerImpl implements ManagementServer {
if (zone != null) {
sc.setParameters("dataCenterId", zone);
if(state == null)
sc.setParameters("stateNEQ", "Destroyed");
if(state == null) {
sc.setParameters("stateNEQ", "Destroyed");
}
}
if (pod != null) {
sc.setParameters("podId", pod);
if(state == null)
sc.setParameters("stateNEQ", "Destroyed");
if(state == null) {
sc.setParameters("stateNEQ", "Destroyed");
}
}
if (hostId != null) {
@ -2897,95 +2774,6 @@ public class ManagementServerImpl implements ManagementServer {
return _userVmDao.search(sc, searchFilter);
}
@Override
public FirewallRuleVO updatePortForwardingRule(UpdatePortForwardingRuleCmd cmd) throws InvalidParameterValueException, PermissionDeniedException{
String publicIp = cmd.getPublicIp();
String privateIp = cmd.getPrivateIp();
String privatePort = cmd.getPrivatePort();
String publicPort = cmd.getPublicPort();
String protocol = cmd.getProtocol();
Long vmId = cmd.getVirtualMachineId();
Long userId = UserContext.current().getUserId();
Account account = UserContext.current().getAccount();
UserVmVO userVM = null;
if (userId == null) {
userId = Long.valueOf(User.UID_SYSTEM);
}
IPAddressVO ipAddressVO = findIPAddressById(publicIp);
if (ipAddressVO == null) {
throw new InvalidParameterValueException("Unable to find IP address " + publicIp);
}
if (ipAddressVO.getAccountId() == null) {
throw new InvalidParameterValueException("Unable to update port forwarding rule, owner of IP address " + publicIp + " not found.");
}
if (privateIp != null) {
if (!NetUtils.isValidIp(privateIp)) {
throw new InvalidParameterValueException("Invalid private IP address specified: " + privateIp);
}
Criteria c = new Criteria();
c.addCriteria(Criteria.ACCOUNTID, new Object[] {ipAddressVO.getAccountId()});
c.addCriteria(Criteria.DATACENTERID, ipAddressVO.getDataCenterId());
c.addCriteria(Criteria.IPADDRESS, privateIp);
List<UserVmVO> userVMs = searchForUserVMs(c);
if ((userVMs == null) || userVMs.isEmpty()) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, "Invalid private IP address specified: " + privateIp + ", no virtual machine instances running with that address.");
}
userVM = userVMs.get(0);
} else if (vmId != null) {
userVM = findUserVMInstanceById(vmId);
if (userVM == null) {
throw new InvalidParameterValueException("Unable to find virtual machine with id " + vmId);
}
if ((ipAddressVO.getAccountId() == null) || (ipAddressVO.getAccountId().longValue() != userVM.getAccountId())) {
throw new PermissionDeniedException("Unable to update port forwarding rule on IP address " + publicIp + ", permission denied.");
}
if (ipAddressVO.getDataCenterId() != userVM.getDataCenterId()) {
throw new PermissionDeniedException("Unable to update port forwarding rule, IP address " + publicIp + " is not in the same availability zone as virtual machine " + userVM.toString());
}
privateIp = userVM.getGuestIpAddress();
} else {
throw new InvalidParameterValueException("No private IP address (privateip) or virtual machine instance id (virtualmachineid) specified, unable to update port forwarding rule");
}
// if an admin account was passed in, or no account was passed in, make sure we honor the accountName/domainId parameters
if (account != null) {
if (isAdmin(account.getType())) {
if (!_domainDao.isChildDomain(account.getDomainId(), ipAddressVO.getDomainId())) {
throw new PermissionDeniedException("Unable to update port forwarding rule on IP address " + publicIp + ", permission denied.");
}
} else if (account.getId() != ipAddressVO.getAccountId()) {
throw new PermissionDeniedException("Unable to update port forwarding rule on IP address " + publicIp + ", permission denied.");
}
}
List<FirewallRuleVO> fwRules = _firewallRulesDao.listIPForwardingForUpdate(publicIp, publicPort, protocol);
if ((fwRules != null) && (fwRules.size() == 1)) {
FirewallRuleVO fwRule = fwRules.get(0);
String oldPrivateIP = fwRule.getPrivateIpAddress();
String oldPrivatePort = fwRule.getPrivatePort();
fwRule.setPrivateIpAddress(privateIp);
fwRule.setPrivatePort(privatePort);
_firewallRulesDao.update(fwRule.getId(), fwRule);
_networkMgr.updateFirewallRule(fwRule, oldPrivateIP, oldPrivatePort);
return fwRule;
}else{
s_logger.warn("Unable to find the rule to be updated for public ip:public port"+publicIp+":"+publicPort+ "private ip:private port:"+privateIp+":"+privatePort);
throw new InvalidParameterValueException("Unable to find the rule to be updated for public ip:public port"+publicIp+":"+publicPort+ " private ip:private port:"+privateIp+":"+privatePort);
}
}
@Override
public FirewallRuleVO findForwardingRuleById(Long ruleId) {
return _firewallRulesDao.findById(ruleId);
}
@Override
public IPAddressVO findIPAddressById(String ipAddress) {
return _publicIpAddressDao.findById(ipAddress);
@ -3067,8 +2855,9 @@ public class ManagementServerImpl implements ManagementServer {
sc.addAnd("level", SearchCriteria.Op.SC, ssc);
}
if (level != null)
sc.setParameters("levelEQ", level);
if (level != null) {
sc.setParameters("levelEQ", level);
}
if (accountId != null) {
sc.setParameters("accountId", accountId);
@ -3701,8 +3490,9 @@ public class ManagementServerImpl implements ManagementServer {
VMInstanceVO vm = this.findVMInstanceById(vmId);
if (vm != null) {
ConsoleProxyInfo proxy = getConsoleProxy(vm.getDataCenterId(), vmId);
if (proxy != null)
if (proxy != null) {
return proxy.getProxyImageUrl();
}
}
return null;
}
@ -3714,12 +3504,14 @@ public class ManagementServerImpl implements ManagementServer {
return new Pair<String, Integer>(null, -1);
}
if(s_logger.isTraceEnabled())
s_logger.trace("Trying to retrieve VNC port from agent about VM " + vm.getHostName());
if(s_logger.isTraceEnabled()) {
s_logger.trace("Trying to retrieve VNC port from agent about VM " + vm.getHostName());
}
GetVncPortAnswer answer = (GetVncPortAnswer) _agentMgr.easySend(vm.getHostId(), new GetVncPortCommand(vm.getId(), vm.getInstanceName()));
if(answer != null)
if(answer != null) {
return new Pair<String, Integer>(answer.getAddress(), answer.getPort());
}
return new Pair<String, Integer>(null, -1);
}
@ -4387,10 +4179,12 @@ public class ManagementServerImpl implements ManagementServer {
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
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());
@ -4398,8 +4192,9 @@ public class ManagementServerImpl implements ManagementServer {
}
//add all the public offerings to the sol list before returning
if(includePublicOfferings)
dol.addAll(_diskOfferingDao.findPublicDiskOfferings());
if(includePublicOfferings) {
dol.addAll(_diskOfferingDao.findPublicDiskOfferings());
}
return dol;
@ -4500,17 +4295,19 @@ public class ManagementServerImpl implements ManagementServer {
public AsyncJobResult queryAsyncJobResult(long jobId) throws PermissionDeniedException {
AsyncJobVO job = _asyncMgr.getAsyncJob(jobId);
if (job == null) {
if (s_logger.isDebugEnabled())
if (s_logger.isDebugEnabled()) {
s_logger.debug("queryAsyncJobResult error: Permission denied, invalid job id " + jobId);
}
throw new PermissionDeniedException("Permission denied, invalid job id " + jobId);
}
// treat any requests from API server as trusted requests
if (!UserContext.current().isApiServer() && job.getAccountId() != UserContext.current().getAccount().getId()) {
if (s_logger.isDebugEnabled())
if (s_logger.isDebugEnabled()) {
s_logger.debug("Mismatched account id in job and user context, perform further securty check. job id: "
+ jobId + ", job owner account: " + job.getAccountId() + ", accound id in current context: " + UserContext.current().getAccount().getId());
}
Account account = UserContext.current().getAccount();
if (account != null) {
@ -4550,200 +4347,6 @@ public class ManagementServerImpl implements ManagementServer {
return _asyncMgr.getAsyncJob(jobId);
}
@Override
public LoadBalancerVO findLoadBalancer(Long accountId, String name) {
SearchCriteria<LoadBalancerVO> sc = _loadBalancerDao.createSearchCriteria();
sc.addAnd("accountId", SearchCriteria.Op.EQ, accountId);
sc.addAnd("name", SearchCriteria.Op.EQ, name);
List<LoadBalancerVO> loadBalancers = _loadBalancerDao.search(sc, null);
if ((loadBalancers != null) && !loadBalancers.isEmpty()) {
return loadBalancers.get(0);
}
return null;
}
@Override
public LoadBalancerVO findLoadBalancerById(long loadBalancerId) {
return _loadBalancerDao.findById(Long.valueOf(loadBalancerId));
}
@Override
public List<UserVmVO> listLoadBalancerInstances(ListLoadBalancerRuleInstancesCmd cmd) throws PermissionDeniedException {
Account account = UserContext.current().getAccount();
Long loadBalancerId = cmd.getId();
Boolean applied = cmd.isApplied();
if (applied == null) {
applied = Boolean.TRUE;
}
LoadBalancerVO loadBalancer = _loadBalancerDao.findById(loadBalancerId);
if (loadBalancer == null) {
return null;
}
if (account != null) {
long lbAcctId = loadBalancer.getAccountId();
if (isAdmin(account.getType())) {
Account userAccount = _accountDao.findById(lbAcctId);
if (!_domainDao.isChildDomain(account.getDomainId(), userAccount.getDomainId())) {
throw new PermissionDeniedException("Invalid load balancer rule id (" + loadBalancerId + ") given, unable to list load balancer instances.");
}
} else if (account.getId() != lbAcctId) {
throw new PermissionDeniedException("Unable to list load balancer instances, account " + account.getAccountName() + " does not own load balancer rule " + loadBalancer.getName());
}
}
List<UserVmVO> loadBalancerInstances = new ArrayList<UserVmVO>();
List<LoadBalancerVMMapVO> vmLoadBalancerMappings = null;
if (applied) {
// List only the instances that have actually been applied to the load balancer (pending is false).
vmLoadBalancerMappings = _loadBalancerVMMapDao.listByLoadBalancerId(loadBalancerId, false);
} else {
// List all instances applied, even pending ones that are currently being assigned, so that the semantics
// of "what instances can I apply to this load balancer" are maintained.
vmLoadBalancerMappings = _loadBalancerVMMapDao.listByLoadBalancerId(loadBalancerId);
}
List<Long> appliedInstanceIdList = new ArrayList<Long>();
if ((vmLoadBalancerMappings != null) && !vmLoadBalancerMappings.isEmpty()) {
for (LoadBalancerVMMapVO vmLoadBalancerMapping : vmLoadBalancerMappings) {
appliedInstanceIdList.add(vmLoadBalancerMapping.getInstanceId());
}
}
IPAddressVO addr = _publicIpAddressDao.findById(loadBalancer.getIpAddress());
List<UserVmVO> userVms = _userVmDao.listVirtualNetworkInstancesByAcctAndZone(loadBalancer.getAccountId(), addr.getDataCenterId());
for (UserVmVO userVm : userVms) {
// if the VM is destroyed, being expunged, in an error state, or in an unknown state, skip it
switch (userVm.getState()) {
case Destroyed:
case Expunging:
case Error:
case Unknown:
continue;
}
boolean isApplied = appliedInstanceIdList.contains(userVm.getId());
if (!applied && !isApplied) {
loadBalancerInstances.add(userVm);
} else if (applied && isApplied) {
loadBalancerInstances.add(userVm);
}
}
return loadBalancerInstances;
}
@Override
public List<LoadBalancerVO> searchForLoadBalancers(ListLoadBalancerRulesCmd cmd) throws InvalidParameterValueException, PermissionDeniedException {
// do some parameter validation
Account account = UserContext.current().getAccount();
String accountName = cmd.getAccountName();
Long domainId = cmd.getDomainId();
Long accountId = null;
Account ipAddressOwner = null;
String ipAddress = cmd.getPublicIp();
if (ipAddress != null) {
IPAddressVO ipAddressVO = _publicIpAddressDao.findById(ipAddress);
if (ipAddressVO == null) {
throw new InvalidParameterValueException("Unable to list load balancers, IP address " + ipAddress + " not found.");
} else {
Long ipAddrAcctId = ipAddressVO.getAccountId();
if (ipAddrAcctId == null) {
throw new InvalidParameterValueException("Unable to list load balancers, IP address " + ipAddress + " is not associated with an account.");
}
ipAddressOwner = _accountDao.findById(ipAddrAcctId);
}
}
if ((account == null) || isAdmin(account.getType())) {
// validate domainId before proceeding
if (domainId != null) {
if ((account != null) && !_domainDao.isChildDomain(account.getDomainId(), domainId)) {
throw new PermissionDeniedException("Unable to list load balancers for domain id " + domainId + ", permission denied.");
}
if (accountName != null) {
Account userAccount = _accountDao.findActiveAccount(accountName, domainId);
if (userAccount != null) {
accountId = userAccount.getId();
} else {
throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain " + domainId);
}
}
} else if (ipAddressOwner != null) {
if ((account != null) && !_domainDao.isChildDomain(account.getDomainId(), ipAddressOwner.getDomainId())) {
throw new PermissionDeniedException("Unable to list load balancer rules for IP address " + ipAddress + ", permission denied.");
}
} else {
domainId = ((account == null) ? DomainVO.ROOT_DOMAIN : account.getDomainId());
}
} else {
accountId = account.getId();
}
Filter searchFilter = new Filter(LoadBalancerVO.class, "ipAddress", true, cmd.getStartIndex(), cmd.getPageSizeVal());
Object id = cmd.getId();
Object name = cmd.getLoadBalancerRuleName();
Object keyword = cmd.getKeyword();
Object instanceId = cmd.getVirtualMachineId();
SearchBuilder<LoadBalancerVO> sb = _loadBalancerDao.createSearchBuilder();
sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
sb.and("nameEQ", sb.entity().getName(), SearchCriteria.Op.EQ);
sb.and("accountId", sb.entity().getAccountId(), SearchCriteria.Op.EQ);
sb.and("ipAddress", sb.entity().getIpAddress(), SearchCriteria.Op.EQ);
if ((accountId == null) && (domainId != null)) {
// if accountId isn't specified, we can do a domain match for the admin case
SearchBuilder<DomainVO> domainSearch = _domainDao.createSearchBuilder();
domainSearch.and("path", domainSearch.entity().getPath(), SearchCriteria.Op.LIKE);
sb.join("domainSearch", domainSearch, sb.entity().getDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER);
}
if (instanceId != null) {
SearchBuilder<LoadBalancerVMMapVO> lbVMSearch = _loadBalancerVMMapDao.createSearchBuilder();
lbVMSearch.and("instanceId", lbVMSearch.entity().getInstanceId(), SearchCriteria.Op.EQ);
sb.join("lbVMSearch", lbVMSearch, sb.entity().getId(), lbVMSearch.entity().getLoadBalancerId(), JoinBuilder.JoinType.INNER);
}
SearchCriteria<LoadBalancerVO> sc = sb.create();
if (keyword != null) {
SearchCriteria<LoadBalancerVO> ssc = _loadBalancerDao.createSearchCriteria();
ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("description", SearchCriteria.Op.LIKE, "%" + keyword + "%");
sc.addAnd("name", SearchCriteria.Op.SC, ssc);
}
if (name != null) {
sc.setParameters("nameEQ", name);
}
if (id != null) {
sc.setParameters("id", id);
}
if (ipAddress != null) {
sc.setParameters("ipAddress", ipAddress);
}
if (accountId != null) {
sc.setParameters("accountId", accountId);
} else if (domainId != null) {
DomainVO domain = _domainDao.findById(domainId);
sc.setJoinParameters("domainSearch", "path", domain.getPath() + "%");
}
if (instanceId != null) {
sc.setJoinParameters("lbVMSearch", "instanceId", instanceId);
}
return _loadBalancerDao.search(sc, searchFilter);
}
@Override
public String[] getApiConfig() {
return new String[] { "commands.properties" };
@ -4781,8 +4384,9 @@ public class ManagementServerImpl implements ManagementServer {
} catch (Exception e) {
s_logger.error("Exception ", e);
} finally {
if(txn != null)
txn.close();
if(txn != null) {
txn.close();
}
lock.unlock();
}
@ -5058,11 +4662,13 @@ public class ManagementServerImpl implements ManagementServer {
@Override
public VMInstanceVO findSystemVMById(long instanceId) {
VMInstanceVO systemVm = _vmInstanceDao.findByIdTypes(instanceId, VirtualMachine.Type.ConsoleProxy, VirtualMachine.Type.SecondaryStorageVm);
if(systemVm == null)
return null;
if(systemVm == null) {
return null;
}
if(systemVm.getType() == VirtualMachine.Type.ConsoleProxy)
return _consoleProxyDao.findById(instanceId);
if(systemVm.getType() == VirtualMachine.Type.ConsoleProxy) {
return _consoleProxyDao.findById(instanceId);
}
return _secStorageVmDao.findById(instanceId);
}
@ -5199,8 +4805,9 @@ public class ManagementServerImpl implements ManagementServer {
//verify that user exists
User user = findUserById(userId);
if ((user == null) || (user.getRemoved() != null))
throw new InvalidParameterValueException("Unable to find active user by id " + userId);
if ((user == null) || (user.getRemoved() != null)) {
throw new InvalidParameterValueException("Unable to find active user by id " + userId);
}
String cloudIdentifier = _configDao.getValue("cloud.identifier");
if (cloudIdentifier == null) {
@ -5298,10 +4905,11 @@ public class ManagementServerImpl implements ManagementServer {
{
String value = _configs.get("use.local.storage");
if(value!=null && value.equalsIgnoreCase("true"))
return true;
else
return false;
if(value!=null && value.equalsIgnoreCase("true")) {
return true;
} else {
return false;
}
}
@Override
@ -5331,8 +4939,9 @@ public class ManagementServerImpl implements ManagementServer {
Map<String, String> capabilities = new HashMap<String, String>();
String networkGroupsEnabled = _configs.get("direct.attach.network.groups.enabled");
if(networkGroupsEnabled == null)
networkGroupsEnabled = "false";
if(networkGroupsEnabled == null) {
networkGroupsEnabled = "false";
}
capabilities.put("networkGroupsEnabled", networkGroupsEnabled);
capabilities.put("cloudStackVersion", getVersion());
@ -5368,10 +4977,11 @@ public class ManagementServerImpl implements ManagementServer {
if(rootVolume!=null){
Status poolStatus = _poolDao.findById(rootVolume.getPoolId()).getStatus();
if(!poolStatus.equals(Status.Up))
return false;
else
return true;
if(!poolStatus.equals(Status.Up)) {
return false;
} else {
return true;
}
}
return false;
@ -5683,11 +5293,13 @@ public class ManagementServerImpl implements ManagementServer {
throw new ResourceUnavailableException(msg);
}else{
if(cert.getUpdated().equalsIgnoreCase("Y")){
if(s_logger.isDebugEnabled())
s_logger.debug("A custom certificate already exists in the DB, will replace it with the new one being uploaded");
if(s_logger.isDebugEnabled()) {
s_logger.debug("A custom certificate already exists in the DB, will replace it with the new one being uploaded");
}
}else{
if(s_logger.isDebugEnabled())
s_logger.debug("No custom certificate exists in the DB, will upload a new one");
if(s_logger.isDebugEnabled()) {
s_logger.debug("No custom certificate exists in the DB, will upload a new one");
}
}
//validate if the cert follows X509 format, if not, don't persist to db
@ -5702,8 +5314,9 @@ public class ManagementServerImpl implements ManagementServer {
}
certVOId = _certDao.persistCustomCertToDb(certificate,cert,this.getId());//0 implies failure
if(s_logger.isDebugEnabled())
s_logger.debug("Custom certificate persisted to the DB");
if(s_logger.isDebugEnabled()) {
s_logger.debug("Custom certificate persisted to the DB");
}
}
if (certVOId != 0)
@ -5743,8 +5356,9 @@ public class ManagementServerImpl implements ManagementServer {
long eventId = saveScheduledEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM, EventTypes.EVENT_PROXY_REBOOT, "rebooting console proxy with Id: "+cp.getId());
_consoleProxyMgr.rebootProxy(cp.getId(), eventId);
//when cp reboots, the context will be reinit with the new cert
if(s_logger.isDebugEnabled())
s_logger.debug("Successfully updated custom certificate on console proxy vm id:"+cp.getId()+" ,console proxy host id:"+cpHostId);
if(s_logger.isDebugEnabled()) {
s_logger.debug("Successfully updated custom certificate on console proxy vm id:"+cp.getId()+" ,console proxy host id:"+cpHostId);
}
updatedCpIdList.add(cp.getId());
}
} catch (AgentUnavailableException e) {
@ -5768,11 +5382,11 @@ public class ManagementServerImpl implements ManagementServer {
}
}catch (Exception e) {
s_logger.warn("Failed to successfully update the cert across console proxies on management server:"+this.getId());
if(e instanceof ResourceUnavailableException)
throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, e.getMessage());
else if(e instanceof ManagementServerException)
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage());
else if(e instanceof IndexOutOfBoundsException){
if(e instanceof ResourceUnavailableException) {
throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, e.getMessage());
} else if(e instanceof ManagementServerException) {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage());
} else if(e instanceof IndexOutOfBoundsException){
String msg = "Custom certificate record in the db deleted; this should never happen. Please create a new record in the certificate table";
s_logger.error(msg,e);
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, msg);

View File

@ -128,10 +128,8 @@ import com.cloud.host.HostVO;
import com.cloud.host.dao.DetailsDao;
import com.cloud.host.dao.HostDao;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.network.FirewallRuleVO;
import com.cloud.network.IPAddressVO;
import com.cloud.network.IpAddrAllocator;
import com.cloud.network.LoadBalancerVMMapVO;
import com.cloud.network.NetworkManager;
import com.cloud.network.NetworkVO;
import com.cloud.network.Networks.TrafficType;
@ -328,9 +326,10 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM
VMTemplateVO template = _templateDao.findById(vmInstance.getTemplateId());
if (template.getEnablePassword()) {
if (vmInstance.getDomainRouterId() == null)
/*TODO: add it for external dhcp mode*/
if (vmInstance.getDomainRouterId() == null) {
/*TODO: add it for external dhcp mode*/
return true;
}
if (_networkMgr.savePasswordToRouter(vmInstance.getDomainRouterId(), vmInstance.getPrivateIpAddress(), password)) {
// Need to reboot the virtual machine so that the password gets redownloaded from the DomR, and reset on the VM
if (!rebootVirtualMachine(userId, vmId)) {
@ -418,11 +417,13 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM
// If the account is not an admin, check that the volume and the virtual machine are owned by the account that was passed in
if (account != null) {
if (!isAdmin(account.getType())) {
if (account.getId() != volume.getAccountId())
if (account.getId() != volume.getAccountId()) {
throw new PermissionDeniedException("Unable to find volume with ID: " + volumeId + " for account: " + account.getAccountName() + ". Permission denied.");
}
if (account.getId() != vm.getAccountId())
if (account.getId() != vm.getAccountId()) {
throw new PermissionDeniedException("Unable to find VM with ID: " + vmId + " for account: " + account.getAccountName() + ". Permission denied");
}
} else {
if (!_domainDao.isChildDomain(account.getDomainId(), volume.getDomainId()) ||
!_domainDao.isChildDomain(account.getDomainId(), vm.getDomainId())) {
@ -538,8 +539,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM
if(asyncExecutor != null) {
AsyncJobVO job = asyncExecutor.getJob();
if(s_logger.isInfoEnabled())
s_logger.info("Trying to attaching volume " + volumeId +" to vm instance:"+vm.getId()+ ", update async job-" + job.getId() + " progress status");
if(s_logger.isInfoEnabled()) {
s_logger.info("Trying to attaching volume " + volumeId +" to vm instance:"+vm.getId()+ ", update async job-" + job.getId() + " progress status");
}
_asyncMgr.updateAsyncJobAttachment(job.getId(), "volume", volumeId);
_asyncMgr.updateAsyncJobStatus(job.getId(), BaseCmd.PROGRESS_INSTANCE_CREATED, volumeId);
@ -552,8 +554,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM
if(hostId == null) {
hostId = vm.getLastHostId();
HostVO host = _hostDao.findById(hostId);
if(host != null && host.getHypervisorType() == HypervisorType.VmWare)
sendCommand = true;
if(host != null && host.getHypervisorType() == HypervisorType.VmWare) {
sendCommand = true;
}
}
if (sendCommand) {
@ -581,18 +584,20 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM
} else {
_volsDao.attachVolume(volume.getId(), vmId, deviceId);
}
if(!vm.getHostName().equals(vm.getDisplayName()))
event.setDescription("Volume: " +volume.getName()+ " successfully attached to VM: "+vm.getHostName()+"("+vm.getDisplayName()+")");
else
event.setDescription("Volume: " +volume.getName()+ " successfully attached to VM: "+vm.getHostName());
if(!vm.getHostName().equals(vm.getDisplayName())) {
event.setDescription("Volume: " +volume.getName()+ " successfully attached to VM: "+vm.getHostName()+"("+vm.getDisplayName()+")");
} else {
event.setDescription("Volume: " +volume.getName()+ " successfully attached to VM: "+vm.getHostName());
}
event.setLevel(EventVO.LEVEL_INFO);
_eventDao.persist(event);
return _volsDao.findById(volumeId);
} else {
if (answer != null) {
String details = answer.getDetails();
if (details != null && !details.isEmpty())
errorMsg += "; " + details;
if (details != null && !details.isEmpty()) {
errorMsg += "; " + details;
}
}
throw new CloudRuntimeException(errorMsg);
}
@ -634,13 +639,15 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM
}
// Check that the volume ID is valid
if (volume == null)
throw new ServerApiException(BaseCmd.PARAM_ERROR, "Unable to find volume with ID: " + volumeId);
if (volume == null) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, "Unable to find volume with ID: " + volumeId);
}
// If the account is not an admin, check that the volume is owned by the account that was passed in
if (!isAdmin) {
if (account.getId() != volume.getAccountId())
throw new ServerApiException(BaseCmd.PARAM_ERROR, "Unable to find volume with ID: " + volumeId + " for account: " + account.getAccountName());
if (account.getId() != volume.getAccountId()) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, "Unable to find volume with ID: " + volumeId + " for account: " + account.getAccountName());
}
} else if (account != null) {
if (!_domainDao.isChildDomain(account.getDomainId(), volume.getDomainId())) {
throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, "Unable to detach volume with ID: " + volumeId + ", permission denied.");
@ -674,8 +681,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM
if(asyncExecutor != null) {
AsyncJobVO job = asyncExecutor.getJob();
if(s_logger.isInfoEnabled())
s_logger.info("Trying to attaching volume " + volumeId +"to vm instance:"+vm.getId()+ ", update async job-" + job.getId() + " progress status");
if(s_logger.isInfoEnabled()) {
s_logger.info("Trying to attaching volume " + volumeId +"to vm instance:"+vm.getId()+ ", update async job-" + job.getId() + " progress status");
}
_asyncMgr.updateAsyncJobAttachment(job.getId(), "volume", volumeId);
_asyncMgr.updateAsyncJobStatus(job.getId(), BaseCmd.PROGRESS_INSTANCE_CREATED, volumeId);
@ -707,10 +715,11 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM
if (!sendCommand || (answer != null && answer.getResult())) {
// Mark the volume as detached
_volsDao.detachVolume(volume.getId());
if(!vm.getHostName().equals(vm.getDisplayName()))
event.setDescription("Volume: " +volume.getName()+ " successfully detached from VM: "+vm.getHostName()+"("+vm.getDisplayName()+")");
else
event.setDescription("Volume: " +volume.getName()+ " successfully detached from VM: "+vm.getHostName());
if(!vm.getHostName().equals(vm.getDisplayName())) {
event.setDescription("Volume: " +volume.getName()+ " successfully detached from VM: "+vm.getHostName()+"("+vm.getDisplayName()+")");
} else {
event.setDescription("Volume: " +volume.getName()+ " successfully detached from VM: "+vm.getHostName());
}
event.setLevel(EventVO.LEVEL_INFO);
_eventDao.persist(event);
@ -719,8 +728,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM
if (answer != null) {
String details = answer.getDetails();
if (details != null && !details.isEmpty())
errorMsg += "; " + details;
if (details != null && !details.isEmpty()) {
errorMsg += "; " + details;
}
}
throw new CloudRuntimeException(errorMsg);
@ -781,13 +791,14 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM
// TODO following implementation only do asynchronized operation at API level
try {
UserVmVO vm = start(param.getUserId(), param.getVmId(), null, param.getIsoPath(), param.getEventId());
if(vm != null)
executor.getAsyncJobMgr().completeAsyncJob(executor.getJob().getId(),
if(vm != null) {
executor.getAsyncJobMgr().completeAsyncJob(executor.getJob().getId(),
AsyncJobResult.STATUS_SUCCEEDED, 0, VMExecutorHelper.composeResultObject(
executor.getAsyncJobMgr().getExecutorContext().getManagementServer(), vm, null));
else
executor.getAsyncJobMgr().completeAsyncJob(executor.getJob().getId(),
} else {
executor.getAsyncJobMgr().completeAsyncJob(executor.getJob().getId(),
AsyncJobResult.STATUS_FAILED, BaseCmd.INTERNAL_ERROR, "Unable to start vm");
}
} catch (StorageUnavailableException e) {
s_logger.debug("Unable to start vm because storage is unavailable: " + e.getMessage());
@ -912,12 +923,14 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM
HostVO host = null;
if(vm.getLastHostId() != null) {
host = _hostDao.findById(vm.getLastHostId());
if(host == null || host.getStatus() != com.cloud.host.Status.Up || host.getHypervisorType() != HypervisorType.VmWare)
host = null;
if(host == null || host.getStatus() != com.cloud.host.Status.Up || host.getHypervisorType() != HypervisorType.VmWare) {
host = null;
}
}
if(host == null)
host = (HostVO) _agentMgr.findHost(Host.Type.Routing, dc, pod, sp, offering, template, vm, null, avoid);
if(host == null) {
host = (HostVO) _agentMgr.findHost(Host.Type.Routing, dc, pod, sp, offering, template, vm, null, avoid);
}
if (host == null) {
String description = "Unable to find any host for " + vm.toString();
@ -949,10 +962,11 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM
if (router == null) {
s_logger.error("Unable to add vm " + vm.getId() + " - " + vm.getHostName());
_vmDao.updateIf(vm, VirtualMachine.Event.OperationFailed, null);
if(!vm.getHostName().equals(vm.getDisplayName()))
event.setDescription("Unable to start VM: " + vm.getHostName()+"("+vm.getDisplayName()+")" + "; Unable to add VM to guest network");
else
event.setDescription("Unable to start VM: " + vm.getHostName() + "; Unable to add VM to guest network");
if(!vm.getHostName().equals(vm.getDisplayName())) {
event.setDescription("Unable to start VM: " + vm.getHostName()+"("+vm.getDisplayName()+")" + "; Unable to add VM to guest network");
} else {
event.setDescription("Unable to start VM: " + vm.getHostName() + "; Unable to add VM to guest network");
}
event.setLevel(EventVO.LEVEL_ERROR);
_eventDao.persist(event);
@ -1096,10 +1110,11 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM
} while (--retry > 0 && (host = (HostVO)_agentMgr.findHost(Host.Type.Routing, dc, pod, sp, offering, template, vm, null, avoid)) != null);
if (host == null || retry <= 0) {
if(!vm.getHostName().equals(vm.getDisplayName()))
if(!vm.getHostName().equals(vm.getDisplayName())) {
event.setDescription("Unable to start VM: " + vm.getHostName()+"("+vm.getDisplayName()+")"+ " Reason: "+answer.getDetails());
else
} else {
event.setDescription("Unable to start VM: " + vm.getHostName()+ " Reason: "+answer.getDetails());
}
event.setLevel(EventVO.LEVEL_ERROR);
_eventDao.persist(event);
@ -1107,10 +1122,11 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM
}
if (!_vmDao.updateIf(vm, VirtualMachine.Event.OperationSucceeded, host.getId())) {
if(!vm.getHostName().equals(vm.getDisplayName()))
event.setDescription("unable to start VM: " + vm.getHostName()+"("+vm.getDisplayName()+")");
else
event.setDescription("unable to start VM: " + vm.getHostName());
if(!vm.getHostName().equals(vm.getDisplayName())) {
event.setDescription("unable to start VM: " + vm.getHostName()+"("+vm.getDisplayName()+")");
} else {
event.setDescription("unable to start VM: " + vm.getHostName());
}
event.setLevel(EventVO.LEVEL_ERROR);
_eventDao.persist(event);
throw new ConcurrentOperationException("Starting vm " + vm.getHostName() + " didn't work.");
@ -1120,10 +1136,11 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM
s_logger.debug("Started vm " + vm.getHostName());
}
if(!vm.getHostName().equals(vm.getDisplayName()))
event.setDescription("successfully started VM: " + vm.getHostName()+"("+vm.getDisplayName()+")");
else
event.setDescription("successfully started VM: " + vm.getHostName());
if(!vm.getHostName().equals(vm.getDisplayName())) {
event.setDescription("successfully started VM: " + vm.getHostName()+"("+vm.getDisplayName()+")");
} else {
event.setDescription("successfully started VM: " + vm.getHostName());
}
_eventDao.persist(event);
_networkGroupMgr.handleVmStateTransition(vm, State.Running);
@ -1220,8 +1237,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM
resultDescription = "VM is either removed or deleted";
executor.getAsyncJobMgr().completeAsyncJob(executor.getJob().getId(),
AsyncJobResult.STATUS_SUCCEEDED, 0, resultDescription);
if(s_logger.isDebugEnabled())
s_logger.debug("Execute asynchronize stop VM command: " +resultDescription);
if(s_logger.isDebugEnabled()) {
s_logger.debug("Execute asynchronize stop VM command: " +resultDescription);
}
response = new OperationResponse(OperationResponse.STATUS_SUCCEEDED, resultDescription);
return response;
}
@ -1232,8 +1250,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM
executor.getAsyncJobMgr().completeAsyncJob(executor.getJob().getId(),
AsyncJobResult.STATUS_SUCCEEDED, 0, resultDescription);
if(s_logger.isDebugEnabled())
s_logger.debug("Execute asynchronize stop VM command: " +resultDescription);
if(s_logger.isDebugEnabled()) {
s_logger.debug("Execute asynchronize stop VM command: " +resultDescription);
}
response = new OperationResponse(OperationResponse.STATUS_SUCCEEDED, resultDescription);
return response;
}
@ -1243,8 +1262,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM
executor.getAsyncJobMgr().completeAsyncJob(executor.getJob().getId(),
AsyncJobResult.STATUS_SUCCEEDED, 0, resultDescription);
if(s_logger.isDebugEnabled())
s_logger.debug("Execute asynchronize stop VM command: " +resultDescription);
if(s_logger.isDebugEnabled()) {
s_logger.debug("Execute asynchronize stop VM command: " +resultDescription);
}
response = new OperationResponse(OperationResponse.STATUS_SUCCEEDED, resultDescription);
return response;
}
@ -1254,8 +1274,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM
executor.getAsyncJobMgr().completeAsyncJob(executor.getJob().getId(),
AsyncJobResult.STATUS_FAILED, 0, resultDescription);
if(s_logger.isDebugEnabled())
s_logger.debug("Execute asynchronize stop VM command: " +resultDescription);
if(s_logger.isDebugEnabled()) {
s_logger.debug("Execute asynchronize stop VM command: " +resultDescription);
}
response = new OperationResponse(OperationResponse.STATUS_FAILED, resultDescription);
return response;
}
@ -1265,8 +1286,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM
executor.getAsyncJobMgr().completeAsyncJob(executor.getJob().getId(),
AsyncJobResult.STATUS_FAILED, 0, resultDescription);
if(s_logger.isDebugEnabled())
s_logger.debug("Execute asynchronize stop VM command: " +resultDescription);
if(s_logger.isDebugEnabled()) {
s_logger.debug("Execute asynchronize stop VM command: " +resultDescription);
}
response = new OperationResponse(OperationResponse.STATUS_FAILED, resultDescription);
return response;
}
@ -1281,8 +1303,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM
try {
long seq = _agentMgr.send(vm.getHostId(), new Commands(cmd), new VMOperationListener(executor, param, vm, 0));
resultDescription = "Execute asynchronize stop VM command: sending command to agent, seq - " + seq;
if(s_logger.isDebugEnabled())
s_logger.debug(resultDescription);
if(s_logger.isDebugEnabled()) {
s_logger.debug(resultDescription);
}
response = new OperationResponse(OperationResponse.STATUS_IN_PROGRESS, resultDescription);
return response;
} catch (AgentUnavailableException e) {
@ -1314,17 +1337,19 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM
RebootAnswer answer = (RebootAnswer)_agentMgr.easySend(vm.getHostId(), cmd);
if (answer != null) {
if(!vm.getHostName().equals(vm.getDisplayName()))
event.setDescription("Successfully rebooted VM instance : " + vm.getHostName()+"("+vm.getDisplayName()+")");
else
event.setDescription("Successfully rebooted VM instance : " + vm.getHostName());
if(!vm.getHostName().equals(vm.getDisplayName())) {
event.setDescription("Successfully rebooted VM instance : " + vm.getHostName()+"("+vm.getDisplayName()+")");
} else {
event.setDescription("Successfully rebooted VM instance : " + vm.getHostName());
}
_eventDao.persist(event);
return true;
} else {
if(!vm.getHostName().equals(vm.getDisplayName()))
event.setDescription("failed to reboot VM instance : " + vm.getHostName()+"("+vm.getDisplayName()+")");
else
event.setDescription("failed to reboot VM instance : " + vm.getHostName());
if(!vm.getHostName().equals(vm.getDisplayName())) {
event.setDescription("failed to reboot VM instance : " + vm.getHostName()+"("+vm.getDisplayName()+")");
} else {
event.setDescription("failed to reboot VM instance : " + vm.getHostName());
}
event.setLevel(EventVO.LEVEL_ERROR);
_eventDao.persist(event);
return false;
@ -1673,10 +1698,11 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM
txn.start();
if(vm != null && vm.getHostName() != null && vm.getDisplayName() != null)
{
if(!vm.getHostName().equals(vm.getDisplayName()))
event.setDescription("successfully created VM instance : " + vm.getHostName()+"("+vm.getDisplayName()+")");
else
event.setDescription("successfully created VM instance : " + vm.getHostName());
if(!vm.getHostName().equals(vm.getDisplayName())) {
event.setDescription("successfully created VM instance : " + vm.getHostName()+"("+vm.getDisplayName()+")");
} else {
event.setDescription("successfully created VM instance : " + vm.getHostName());
}
}
else
{
@ -1744,10 +1770,11 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM
event.setAccountId(vm.getAccountId());
event.setType(EventTypes.EVENT_VM_DESTROY);
event.setParameters("id="+vm.getId() + "\nvmName=" + vm.getHostName() + "\nsoId=" + vm.getServiceOfferingId() + "\ntId=" + vm.getTemplateId() + "\ndcId=" + vm.getDataCenterId());
if(!vm.getHostName().equals(vm.getDisplayName()))
event.setDescription("Successfully destroyed VM instance : " + vm.getHostName()+"("+vm.getDisplayName()+")");
else
event.setDescription("Successfully destroyed VM instance : " + vm.getHostName());
if(!vm.getHostName().equals(vm.getDisplayName())) {
event.setDescription("Successfully destroyed VM instance : " + vm.getHostName()+"("+vm.getDisplayName()+")");
} else {
event.setDescription("Successfully destroyed VM instance : " + vm.getHostName());
}
_eventDao.persist(event);
_accountMgr.decrementResourceCount(vm.getAccountId(), ResourceType.user_vm);
@ -1775,8 +1802,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM
Account accountHandle = UserContext.current().getAccount();
//if account is removed, return error
if(accountHandle!=null && accountHandle.getRemoved() != null)
throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, "The account " + accountHandle.getId()+" is removed");
if(accountHandle!=null && accountHandle.getRemoved() != null) {
throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, "The account " + accountHandle.getId()+" is removed");
}
// Verify input parameters
UserVmVO vm = _vmDao.findById(vmId.longValue());
@ -1821,18 +1849,20 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM
account = _accountDao.lockRow(vm.getAccountId(), true);
//if the account is deleted, throw error
if(account.getRemoved()!=null)
throw new CloudRuntimeException("Unable to recover VM as the account is deleted");
if(account.getRemoved()!=null) {
throw new CloudRuntimeException("Unable to recover VM as the account is deleted");
}
// First check that the maximum number of UserVMs for the given accountId will not be exceeded
if (_accountMgr.resourceLimitExceeded(account, ResourceType.user_vm)) {
ResourceAllocationException rae = new ResourceAllocationException("Maximum number of virtual machines for account: " + account.getAccountName() + " has been exceeded.");
rae.setResourceType("vm");
event.setLevel(EventVO.LEVEL_ERROR);
if(!vm.getHostName().equals(vm.getDisplayName()))
event.setDescription("Failed to recover VM instance : " + vm.getHostName()+"("+vm.getDisplayName()+")" + "; the resource limit for account: " + account.getAccountName() + " has been exceeded.");
else
event.setDescription("Failed to recover VM instance : " + vm.getHostName() + "; the resource limit for account: " + account.getAccountName() + " has been exceeded.");
if(!vm.getHostName().equals(vm.getDisplayName())) {
event.setDescription("Failed to recover VM instance : " + vm.getHostName()+"("+vm.getDisplayName()+")" + "; the resource limit for account: " + account.getAccountName() + " has been exceeded.");
} else {
event.setDescription("Failed to recover VM instance : " + vm.getHostName() + "; the resource limit for account: " + account.getAccountName() + " has been exceeded.");
}
_eventDao.persist(event);
txn.commit();
throw rae;
@ -1873,10 +1903,11 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM
_accountMgr.incrementResourceCount(account.getId(), ResourceType.volume, new Long(volumes.size()));
event.setLevel(EventVO.LEVEL_INFO);
if(!vm.getHostName().equals(vm.getDisplayName()))
event.setDescription("successfully recovered VM instance : " + vm.getHostName()+"("+vm.getDisplayName()+")");
else
if(!vm.getHostName().equals(vm.getDisplayName())) {
event.setDescription("successfully recovered VM instance : " + vm.getHostName()+"("+vm.getDisplayName()+")");
} else {
event.setDescription("successfully recovered VM instance : " + vm.getHostName());
}
_eventDao.persist(event);
txn.commit();
@ -2023,10 +2054,11 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM
event.setState(Event.State.Completed);
event.setStartId(startEventId);
event.setParameters("id="+vm.getId() + "\n" + "vmName=" + vm.getHostName() + "\nsoId=" + vm.getServiceOfferingId() + "\ntId=" + vm.getTemplateId() + "\ndcId=" + vm.getDataCenterId());
if(!vm.getHostName().equals(vm.getDisplayName()))
event.setDescription("Successfully stopped VM instance : " + vm.getHostName()+"("+vm.getDisplayName()+")");
else
event.setDescription("Successfully stopped VM instance : " + vm.getHostName());
if(!vm.getHostName().equals(vm.getDisplayName())) {
event.setDescription("Successfully stopped VM instance : " + vm.getHostName()+"("+vm.getDisplayName()+")");
} else {
event.setDescription("Successfully stopped VM instance : " + vm.getHostName());
}
_eventDao.persist(event);
if (_storageMgr.unshare(vm, null) == null) {
@ -2112,10 +2144,11 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM
completeStopCommand(userId, vm, VirtualMachine.Event.OperationSucceeded, 0);
} else
{
if(!vm.getHostName().equals(vm.getDisplayName()))
event.setDescription("failed to stop VM instance : " + vm.getHostName()+"("+vm.getDisplayName()+")");
else
event.setDescription("failed to stop VM instance : " + vm.getHostName());
if(!vm.getHostName().equals(vm.getDisplayName())) {
event.setDescription("failed to stop VM instance : " + vm.getHostName()+"("+vm.getDisplayName()+")");
} else {
event.setDescription("failed to stop VM instance : " + vm.getHostName());
}
event.setLevel(EventVO.LEVEL_ERROR);
_eventDao.persist(event);
_vmDao.updateIf(vm, VirtualMachine.Event.OperationFailed, vm.getHostId());
@ -2238,53 +2271,53 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM
deleteRules = false;
}
if(deleteRules)
{
List<FirewallRuleVO> forwardingRules = null;
forwardingRules = _rulesDao.listByPrivateIp(privateIpAddress);
for(FirewallRuleVO rule: forwardingRules)
{
try
{
IPAddressVO publicIp = _ipAddressDao.findById(rule.getPublicIpAddress());
if(publicIp != null)
{
if((publicIp.getAccountId().longValue() == vm.getAccountId()))
{
if(publicIp.isOneToOneNat()){
_networkMgr.deleteIpForwardingRule(rule.getId());
if(s_logger.isDebugEnabled())
s_logger.debug("Rule "+rule.getId()+" for vm:"+vm.getHostName()+" is deleted successfully during expunge operation");
}else{
_networkMgr.deletePortForwardingRule(rule.getId(),true);//delete the rule with the sys user's credentials
if(s_logger.isDebugEnabled())
s_logger.debug("Rule "+rule.getId()+" for vm:"+vm.getHostName()+" is deleted successfully during expunge operation");
}
}
}
}
catch(Exception e)
{
s_logger.warn("Failed to delete rule:"+rule.getId()+" for vm:"+vm.getHostName());
}
}
}
List<VolumeVO> vols = null;
try {
vols = _volsDao.findByInstanceIdDestroyed(vmId);
_storageMgr.destroy(vm, vols);
_vmDao.remove(vm.getId());
_networkGroupMgr.removeInstanceFromGroups(vm.getId());
removeInstanceFromGroup(vm.getId());
s_logger.debug("vm is destroyed");
} catch (Exception e) {
s_logger.info("VM " + vmId +" expunge failed due to " + e.getMessage());
}
//FIXME if(deleteRules)
// {
// List<PortForwardingRuleVO> forwardingRules = null;
// forwardingRules = _rulesDao.listByPrivateIp(privateIpAddress);
//
// for(PortForwardingRuleVO rule: forwardingRules)
// {
// try
// {
// IPAddressVO publicIp = _ipAddressDao.findById(rule.getSourceIpAddress());
//
// if(publicIp != null)
// {
// if((publicIp.getAccountId().longValue() == vm.getAccountId()))
// {
// if(publicIp.isOneToOneNat()){
// _networkMgr.deleteIpForwardingRule(rule.getId());
// if(s_logger.isDebugEnabled())
// s_logger.debug("Rule "+rule.getId()+" for vm:"+vm.getHostName()+" is deleted successfully during expunge operation");
// }else{
// _networkMgr.deletePortForwardingRule(rule.getId(),true);//delete the rule with the sys user's credentials
// if(s_logger.isDebugEnabled())
// s_logger.debug("Rule "+rule.getId()+" for vm:"+vm.getHostName()+" is deleted successfully during expunge operation");
// }
// }
// }
// }
// catch(Exception e)
// {
// s_logger.warn("Failed to delete rule:"+rule.getId()+" for vm:"+vm.getHostName());
// }
// }
// }
//
// List<VolumeVO> vols = null;
// try {
// vols = _volsDao.findByInstanceIdDestroyed(vmId);
// _storageMgr.destroy(vm, vols);
//
// _vmDao.remove(vm.getId());
// _networkGroupMgr.removeInstanceFromGroups(vm.getId());
// removeInstanceFromGroup(vm.getId());
//
// s_logger.debug("vm is destroyed");
// } catch (Exception e) {
// s_logger.info("VM " + vmId +" expunge failed due to " + e.getMessage());
// }
}
List<VolumeVO> destroyedVolumes = _volsDao.findByDetachedDestroyed();
@ -2328,42 +2361,42 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM
@Override
public void cleanNetworkRules(long userId, long instanceId) {
UserVmVO vm = _vmDao.findById(instanceId);
String guestIpAddr = vm.getGuestIpAddress();
long accountId = vm.getAccountId();
List<LoadBalancerVMMapVO> loadBalancerMappings = _loadBalancerVMMapDao.listByInstanceId(vm.getId());
for (LoadBalancerVMMapVO loadBalancerMapping : loadBalancerMappings) {
List<FirewallRuleVO> lbRules = _rulesDao.listByLoadBalancerId(loadBalancerMapping.getLoadBalancerId());
FirewallRuleVO targetLbRule = null;
for (FirewallRuleVO lbRule : lbRules) {
if (lbRule.getPrivateIpAddress().equals(guestIpAddr)) {
targetLbRule = lbRule;
targetLbRule.setEnabled(false);
break;
}
}
if (targetLbRule != null) {
String ipAddress = targetLbRule.getPublicIpAddress();
DomainRouterVO router = _routerDao.findById(vm.getDomainRouterId());
_networkMgr.updateFirewallRules(ipAddress, lbRules, router);
// now that the rule has been disabled, delete it, also remove the mapping from the load balancer mapping table
_rulesDao.remove(targetLbRule.getId());
_loadBalancerVMMapDao.remove(loadBalancerMapping.getId());
// save off the event for deleting the LB rule
EventVO lbRuleEvent = new EventVO();
lbRuleEvent.setUserId(userId);
lbRuleEvent.setAccountId(accountId);
lbRuleEvent.setType(EventTypes.EVENT_NET_RULE_DELETE);
lbRuleEvent.setDescription("deleted load balancer rule [" + targetLbRule.getPublicIpAddress() + ":" + targetLbRule.getPublicPort() +
"]->[" + targetLbRule.getPrivateIpAddress() + ":" + targetLbRule.getPrivatePort() + "]" + " " + targetLbRule.getAlgorithm());
lbRuleEvent.setLevel(EventVO.LEVEL_INFO);
_eventDao.persist(lbRuleEvent);
}
}
//FIXME UserVmVO vm = _vmDao.findById(instanceId);
// String guestIpAddr = vm.getGuestIpAddress();
// long accountId = vm.getAccountId();
//
// List<LoadBalancerVMMapVO> loadBalancerMappings = _loadBalancerVMMapDao.listByInstanceId(vm.getId());
// for (LoadBalancerVMMapVO loadBalancerMapping : loadBalancerMappings) {
// List<PortForwardingRuleVO> lbRules = _rulesDao.listByLoadBalancerId(loadBalancerMapping.getLoadBalancerId());
// PortForwardingRuleVO targetLbRule = null;
// for (PortForwardingRuleVO lbRule : lbRules) {
// if (lbRule.getDestinationIpAddress().equals(guestIpAddr)) {
// targetLbRule = lbRule;
// targetLbRule.setEnabled(false);
// break;
// }
// }
//
// if (targetLbRule != null) {
// String ipAddress = targetLbRule.getSourceIpAddress();
// DomainRouterVO router = _routerDao.findById(vm.getDomainRouterId());
// _networkMgr.updateFirewallRules(ipAddress, lbRules, router);
//
// // now that the rule has been disabled, delete it, also remove the mapping from the load balancer mapping table
// _rulesDao.remove(targetLbRule.getId());
// _loadBalancerVMMapDao.remove(loadBalancerMapping.getId());
//
// // save off the event for deleting the LB rule
// EventVO lbRuleEvent = new EventVO();
// lbRuleEvent.setUserId(userId);
// lbRuleEvent.setAccountId(accountId);
// lbRuleEvent.setType(EventTypes.EVENT_NET_RULE_DELETE);
// lbRuleEvent.setDescription("deleted load balancer rule [" + targetLbRule.getSourceIpAddress() + ":" + targetLbRule.getSourcePort() +
// "]->[" + targetLbRule.getDestinationIpAddress() + ":" + targetLbRule.getDestinationPort() + "]" + " " + targetLbRule.getAlgorithm());
// lbRuleEvent.setLevel(EventVO.LEVEL_INFO);
// _eventDao.persist(lbRuleEvent);
// }
// }
}
@Override
@ -2664,8 +2697,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM
long dataCenterId = dc.getId();
long serviceOfferingId = offering.getId();
long templateId = -1;
if (template != null)
templateId = template.getId();
if (template != null) {
templateId = template.getId();
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Creating directly attached vm for account id=" + account.getId() +
@ -2778,8 +2812,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM
for(VlanVO vlanForAcc : vlansForAccount)
{
guestIp = _ipAddressDao.assignIpAddress(accountId, account.getDomainId(), vlanForAcc.getId(), false);
if(guestIp!=null)
break; //got an ip
if(guestIp!=null) {
break; //got an ip
}
}
}
else if(!forAccount && !forZone)
@ -2788,8 +2823,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM
for(VlanVO vlanForPod : vlansForPod)
{
guestIp = _ipAddressDao.assignIpAddress(accountId, account.getDomainId(), vlanForPod.getId(), false);
if(guestIp!=null)
break;//got an ip
if(guestIp!=null) {
break;//got an ip
}
}
}
else
@ -2798,8 +2834,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM
for(VlanVO vlanForZone : zoneWideVlans)
{
guestIp = _ipAddressDao.assignIpAddress(accountId, account.getDomainId(), vlanForZone.getId(), false);
if(guestIp!=null)
break;//found an ip
if(guestIp!=null) {
break;//found an ip
}
}
}
@ -2861,10 +2898,11 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM
if (poolId == 0) {
if(vm != null && vm.getHostName()!=null && vm.getDisplayName() != null)
{
if(!vm.getHostName().equals(vm.getDisplayName()))
s_logger.debug("failed to create VM instance : " + name+"("+vm.getInstanceName()+")");
else
s_logger.debug("failed to create VM instance : " + name);
if(!vm.getHostName().equals(vm.getDisplayName())) {
s_logger.debug("failed to create VM instance : " + name+"("+vm.getInstanceName()+")");
} else {
s_logger.debug("failed to create VM instance : " + name);
}
}
else
{
@ -2887,10 +2925,11 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM
String diskOfferingIdentifier = (diskOffering != null) ? String.valueOf(diskOffering.getId()) : "-1";
String eventParams = "id=" + vm.getId() + "\nvmName=" + vm.getHostName() + "\nsoId=" + vm.getServiceOfferingId() + "\ndoId=" + diskOfferingIdentifier + "\ntId=" + vm.getTemplateId() + "\ndcId=" + vm.getDataCenterId();
event.setParameters(eventParams);
if(!vm.getHostName().equals(vm.getDisplayName()))
event.setDescription("successfully created VM instance : " + vm.getHostName()+"("+vm.getInstanceName()+")");
else
event.setDescription("successfully created VM instance : " + vm.getHostName());
if(!vm.getHostName().equals(vm.getDisplayName())) {
event.setDescription("successfully created VM instance : " + vm.getHostName()+"("+vm.getInstanceName()+")");
} else {
event.setDescription("successfully created VM instance : " + vm.getHostName());
}
_eventDao.persist(event);
_vmDao.updateIf(vm, VirtualMachine.Event.OperationSucceeded, null);
@ -2916,8 +2955,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM
long dataCenterId = dc.getId();
long serviceOfferingId = offering.getId();
long templateId = -1;
if (template != null)
templateId = template.getId();
if (template != null) {
templateId = template.getId();
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Creating directly attached vm for account id=" + account.getId() +
@ -3015,10 +3055,11 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM
if (poolId == 0) {
if(vm != null && vm.getHostName()!=null && vm.getDisplayName() != null)
{
if(!vm.getHostName().equals(vm.getDisplayName()))
s_logger.debug("failed to create VM instance : " + name+"("+vm.getDisplayName()+")");
else
s_logger.debug("failed to create VM instance : " + name);
if(!vm.getHostName().equals(vm.getDisplayName())) {
s_logger.debug("failed to create VM instance : " + name+"("+vm.getDisplayName()+")");
} else {
s_logger.debug("failed to create VM instance : " + name);
}
}
else
{
@ -3041,10 +3082,11 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM
String diskOfferingIdentifier = (diskOffering != null) ? String.valueOf(diskOffering.getId()) : "-1";
String eventParams = "id=" + vm.getId() + "\nvmName=" + vm.getHostName() + "\nsoId=" + vm.getServiceOfferingId() + "\ndoId=" + diskOfferingIdentifier + "\ntId=" + vm.getTemplateId() + "\ndcId=" + vm.getDataCenterId();
event.setParameters(eventParams);
if(!vm.getHostName().equals(vm.getDisplayName()))
event.setDescription("successfully created VM instance : " + vm.getHostName()+"("+vm.getDisplayName()+")");
else
event.setDescription("successfully created VM instance : " + vm.getHostName());
if(!vm.getHostName().equals(vm.getDisplayName())) {
event.setDescription("successfully created VM instance : " + vm.getHostName()+"("+vm.getDisplayName()+")");
} else {
event.setDescription("successfully created VM instance : " + vm.getHostName());
}
_eventDao.persist(event);
_vmDao.updateIf(vm, VirtualMachine.Event.OperationSucceeded, null);
@ -3185,8 +3227,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM
Long id = cmd.getId();
//if account is removed, return error
if(account!=null && account.getRemoved() != null)
throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, "The account " + account.getId()+" is removed");
if(account!=null && account.getRemoved() != null) {
throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, "The account " + account.getId()+" is removed");
}
UserVmVO vmInstance = _vmDao.findById(id);
if (vmInstance == null) {
@ -3215,8 +3258,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM
Long id = cmd.getId();
//if account is removed, return error
if(account!=null && account.getRemoved() != null)
throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, "The account " + account.getId()+" is removed");
if(account!=null && account.getRemoved() != null) {
throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, "The account " + account.getId()+" is removed");
}
UserVmVO vmInstance = _vmDao.findById(id.longValue());
if (vmInstance == null) {
@ -3745,8 +3789,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM
Long userId = UserContext.current().getUserId();
//if account is removed, return error
if (caller != null && caller.getRemoved() != null)
if (caller != null && caller.getRemoved() != null) {
throw new PermissionDeniedException("The account " + caller.getId()+" is removed");
}
UserVmVO vm = _vmDao.findById(vmId);
if (vm == null) {
@ -3784,8 +3829,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM
Long userId = UserContext.current().getUserId();
//if account is removed, return error
if(account!=null && account.getRemoved() != null)
if(account!=null && account.getRemoved() != null) {
throw new PermissionDeniedException("The account " + account.getId()+" is removed");
}
UserVmVO vm = _vmDao.findById(vmId);
if (vm == null) {

View File

@ -58,8 +58,6 @@ ALTER TABLE `cloud`.`storage_pool` ADD CONSTRAINT `fk_storage_pool__cluster_id`
ALTER TABLE `cloud`.`storage_pool_details` ADD CONSTRAINT `fk_storage_pool_details__pool_id` FOREIGN KEY `fk_storage_pool__pool_id`(`pool_id`) REFERENCES `storage_pool`(`id`) ON DELETE CASCADE;
ALTER TABLE `cloud`.`storage_pool_details` ADD INDEX `i_storage_pool_details__name__value`(`name`(128), `value`(128));
ALTER TABLE `cloud`.`op_networks` ADD CONSTRAINT `fk_op_networks__id` FOREIGN KEY `fk_op_networks__id`(`id`) REFERENCES `networks`(`id`) ON DELETE CASCADE;
ALTER TABLE `cloud`.`user` ADD INDEX `i_user__secret_key_removed`(`secret_key`, `removed`);
ALTER TABLE `cloud`.`user` ADD INDEX `i_user__removed`(`removed`);
ALTER TABLE `cloud`.`user` ADD UNIQUE `i_user__api_key`(`api_key`);

View File

@ -1,4 +1,5 @@
SET foreign_key_checks = 0;
DROP VIEW IF EXISTS `cloud`.`port_forwarding_rules_view`;
DROP TABLE IF EXISTS `cloud`.`configuration`;
DROP TABLE IF EXISTS `cloud`.`ip_forwarding`;
DROP TABLE IF EXISTS `cloud`.`management_agent`;
@ -84,6 +85,10 @@ DROP TABLE IF EXISTS `cloud`.`instance_group`;
DROP TABLE IF EXISTS `cloud`.`instance_group_vm_map`;
DROP TABLE IF EXISTS `cloud`.`certificate`;
DROP TABLE IF EXISTS `cloud`.`op_it_work`;
DROP TABLE IF EXISTS `cloud`.`load_balancing_ip_map`;
DROP TABLE IF EXISTS `cloud`.`load_balancing_rules`;
DROP TABLE IF EXISTS `cloud`.`port_forwarding_rules`;
DROP TABLE IF EXISTS `cloud`.`firewall_rules`;
CREATE TABLE `cloud`.`op_it_work` (
`id` char(40) COMMENT 'id',
@ -106,7 +111,8 @@ CREATE TABLE `cloud`.`hypervsior_properties` (
CREATE TABLE `cloud`.`op_networks`(
`id` bigint unsigned NOT NULL UNIQUE KEY,
`mac_address_seq` bigint unsigned NOT NULL DEFAULT 1 COMMENT 'mac address',
PRIMARY KEY(`id`)
PRIMARY KEY(`id`),
CONSTRAINT `fk_op_networks__id` FOREIGN KEY (`id`) REFERENCES `networks`(`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `cloud`.`networks` (
@ -425,6 +431,54 @@ CREATE TABLE `cloud`.`op_dc_vnet_alloc` (
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `cloud`.`firewall_rules` (
`id` bigint unsigned NOT NULL auto_increment COMMENT 'id',
`ip_address` bigint unsigned NOT NULL COMMENT 'id_address',
`start_port` int(10) NOT NULL default -1 COMMENT 'starting port of a port range',
`end_port` int(10) NOT NULL default -1 COMMENT 'end port of a port range',
`state` char(32) NOT NULL COMMENT 'current state of this rule',
`protocol` char(16) NOT NULL default 'TCP' COMMENT 'protocol to open these ports for',
`purpose` char(32) NOT NULL COMMENT 'why are these ports opened?',
`account_id` bigint unsigned NOT NULL COMMENT 'owner id',
`domain_id` bigint unsigned NOT NULL COMMENT 'domain id',
`xid` char(40) NOT NULL COMMENT 'external id',
`created` datetime COMMENT 'Date created',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `cloud`.`load_balancing_rules` (
`id` bigint unsigned NOT NULL,
`name` varchar(255) NOT NULL,
`description` varchar(4096) NULL COMMENT 'description',
`default_port_start` int(10) NOT NULL COMMENT 'default private port range start',
`default_port_end` int(10) NOT NULL COMMENT 'default destination port range end',
`algorithm` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `fk_load_balancing_rules__id` FOREIGN KEY(`id`) REFERENCES `firewall_rules`(`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `cloud`.`load_balancer_vm_map` (
`id` bigint unsigned NOT NULL auto_increment,
`load_balancer_id` bigint unsigned NOT NULL,
`instance_id` bigint unsigned NOT NULL,
`pending` tinyint(1) unsigned NOT NULL DEFAULT 0 COMMENT 'whether the vm is being applied to the load balancer (pending=1) or has already been applied (pending=0)',
PRIMARY KEY (`id`),
UNIQUE KEY (`load_balancer_id`, `instance_id`),
CONSTRAINT `fk_load_balancer_vm_map__load_balancer_id` FOREIGN KEY(`load_balancer_id`) REFERENCES `load_balancing_rules`(`id`) ON DELETE CASCADE,
CONSTRAINT `fk_load_balancer_vm_map__instance_id` FOREIGN KEY(`instance_id`) REFERENCES `vm_instance`(`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `cloud`.`port_forwarding_rules` (
`id` bigint unsigned NOT NULL COMMENT 'id',
`dest_ip_address` bigint unsigned NOT NULL COMMENT 'id_address',
`dest_port_start` int(10) NOT NULL COMMENT 'starting port of the port range to map to',
`dest_port_end` int(10) NOT NULL COMMENT 'end port of the the port range to map to',
PRIMARY KEY (`id`),
CONSTRAINT `fk_port_forwarding_rules__id` FOREIGN KEY(`id`) REFERENCES `firewall_rules`(`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE VIEW `cloud`.`port_forwarding_rules_view` AS SELECT fw.id, INET_NTOA(fw.ip_address) as src_ip_address, INET_NTOA(pf.dest_ip_address), fw.start_port as src_port_start, pf.dest_port_start, fw.end_port as src_end_port, pf.dest_port_end as dest_end_port, fw.state, fw.protocol, fw.purpose, fw.account_id from firewall_rules as fw inner join port_forwarding_rules as pf on fw.id=pf.id;
CREATE TABLE `cloud`.`ip_forwarding` (
`id` bigint unsigned NOT NULL auto_increment,
`group_id` bigint unsigned default NULL,
@ -439,6 +493,7 @@ CREATE TABLE `cloud`.`ip_forwarding` (
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
CREATE TABLE `cloud`.`host` (
`id` bigint unsigned NOT NULL auto_increment,
`name` varchar(255) NOT NULL,
@ -946,14 +1001,6 @@ CREATE TABLE `cloud`.`security_group_vm_map` (
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `cloud`.`load_balancer_vm_map` (
`id` bigint unsigned NOT NULL auto_increment,
`load_balancer_id` bigint unsigned NOT NULL,
`instance_id` bigint unsigned NOT NULL,
`pending` tinyint(1) unsigned NOT NULL DEFAULT 0 COMMENT 'whether the vm is being applied to the load balancer (pending=1) or has already been applied (pending=0)',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `cloud`.`load_balancer` (
`id` bigint unsigned NOT NULL auto_increment,
`name` varchar(255) NOT NULL,

View File

@ -23,8 +23,31 @@ import java.util.Map;
import com.cloud.utils.component.ComponentLocator.ComponentInfo;
import com.cloud.utils.db.GenericDao;
/**
* ComponentLibrary specifies the implementation classes that a server needs
* to do its work. You can specify the implementation class in the "library"
* attribute of the server element within components.xml. ComponentLocator
* first loads the implementations specified here, then, it loads the
* implementations from components.xml. If an interface is specified in both
* the ComponentLibrary and the components.xml for the same server, the interface
* within the components.xml overrides the one within ComponentLibrary.
*
*/
public interface ComponentLibrary {
/**
* @return all of the daos
*/
Map<String, ComponentInfo<GenericDao<?,?>>> getDaos();
/**
* @return all of the Managers
*/
Map<String, ComponentInfo<Manager>> getManagers();
/**
* @return all of the adapters
*/
Map<String, List<ComponentInfo<Adapter>>> getAdapters();
Map<Class<?>, Class<?>> getFactories();
}

View File

@ -89,6 +89,7 @@ public class ComponentLocator implements ComponentLocatorMBean {
protected LinkedHashMap<String, ComponentInfo<GenericDao<?, ?>>> _daoMap;
protected String _serverName;
protected Object _component;
protected HashMap<Class<?>, Class<?>> _factories;
static {
Runtime.getRuntime().addShutdownHook(new CleanupThread());
@ -114,6 +115,7 @@ public class ComponentLocator implements ComponentLocatorMBean {
_daoMap = new LinkedHashMap<String, ComponentInfo<GenericDao<?, ? extends Serializable>>>();
_managerMap = new LinkedHashMap<String, ComponentInfo<Manager>>();
_adapterMap = new HashMap<String, Adapters<? extends Adapter>>();
_factories = new HashMap<Class<?>, Class<?>>();
File file = PropertiesUtil.findConfigFile(filename);
if (file == null) {
s_logger.info("Unable to find " + filename);
@ -136,6 +138,7 @@ public class ComponentLocator implements ComponentLocatorMBean {
adapters.putAll(parentLocator.parse2(parentFile).second());
_daoMap.putAll(parentLocator._daoMap);
_managerMap.putAll(parentLocator._managerMap);
_factories.putAll(parentLocator._factories);
}
ComponentLibrary library = null;
@ -145,6 +148,7 @@ public class ComponentLocator implements ComponentLocatorMBean {
_daoMap.putAll(library.getDaos());
_managerMap.putAll(library.getManagers());
adapters.putAll(library.getAdapters());
_factories.putAll(library.getFactories());
}
_daoMap.putAll(handler.daos);
@ -594,6 +598,14 @@ public class ComponentLocator implements ComponentLocatorMBean {
return (T)createInstance(clazz, true, false);
}
public <T> T createInstance(Class<T> clazz) {
Class<? extends T> impl = (Class<? extends T>)_factories.get(clazz);
if (impl == null) {
throw new CloudRuntimeException("Unable to find a factory for " + clazz);
}
return inject(impl);
}
public static <T> T inject(Class<T> clazz, Object... args) {
return (T)createInstance(clazz, true, false, args);
}

View File

@ -39,6 +39,11 @@ public interface GenericDao<T, ID extends Serializable> {
*/
static final String CREATED_COLUMN = "created";
/**
* This column can be used if the value is exposed to the external.
*/
static final String XID_COLUMN = "xid";
/**
* Look for an entity bean using the database id. Does not lock the row.
* @param id database unique id for the entity bean.

View File

@ -40,6 +40,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.UUID;
import javax.naming.ConfigurationException;
import javax.persistence.AttributeOverride;
@ -67,6 +68,8 @@ import com.cloud.utils.Pair;
import com.cloud.utils.Ternary;
import com.cloud.utils.db.SearchCriteria.SelectType;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.net.Ip;
import com.cloud.utils.net.NetUtils;
/**
* GenericDaoBase is a simple way to implement DAOs. It DOES NOT
@ -529,6 +532,17 @@ public abstract class GenericDaoBase<T, ID extends Serializable> implements Gene
} catch (MalformedURLException e) {
throw new CloudRuntimeException("Invalid URL: " + rs.getString(index), e);
}
} else if (type == Ip.class) {
final Enumerated enumerated = field.getAnnotation(Enumerated.class);
final EnumType enumType = (enumerated == null) ? EnumType.STRING : enumerated.value();
Ip ip = null;
if (enumType == EnumType.STRING) {
ip = new Ip(NetUtils.ip2Long(rs.getString(index)));
} else {
ip = new Ip(rs.getLong(index));
}
field.set(entity, ip);
} else if (type == short.class) {
field.setShort(entity, rs.getShort(index));
} else if (type == Short.class) {
@ -582,7 +596,7 @@ public abstract class GenericDaoBase<T, ID extends Serializable> implements Gene
throw new CloudRuntimeException("UnsupportedEncodingException exception while converting UTF-8 data");
}
} else {
return (M)null;
return null;
}
} else if (type == int.class) {
return (M)new Integer(rs.getInt(index));
@ -827,8 +841,9 @@ public abstract class GenericDaoBase<T, ID extends Serializable> implements Gene
@Override @DB(txn=false)
public T findById(final ID id, boolean fresh) {
if(!fresh)
return findById(id);
if(!fresh) {
return findById(id);
}
if (_cache != null) {
_cache.remove(id);
@ -909,8 +924,9 @@ public abstract class GenericDaoBase<T, ID extends Serializable> implements Gene
for(int i = 0; i < groupBys.size(); i++) {
Attribute attr = groupBys.get(i);
sql.append(attr.table).append(".").append(attr.columnName);
if(i < groupBys.size() - 1)
sql.append(", ");
if(i < groupBys.size() - 1) {
sql.append(", ");
}
}
}
}
@ -1188,6 +1204,9 @@ public abstract class GenericDaoBase<T, ID extends Serializable> implements Gene
return null;
// Not sure what to do here.
} else if (attr.is(Attribute.Flag.AutoGV)) {
if (attr.columnName == GenericDao.XID_COLUMN) {
UUID.randomUUID().toString();
}
assert (false) : "Auto generation is not supported.";
return null;
} else if (attr.is(Attribute.Flag.SequenceGV)) {
@ -1278,6 +1297,14 @@ public abstract class GenericDaoBase<T, ID extends Serializable> implements Gene
pstmt.setURL(j, (URL)value);
} else if (attr.field.getType() == byte[].class) {
pstmt.setBytes(j, (byte[])value);
} else if (attr.field.getType() == Ip.class) {
final Enumerated enumerated = attr.field.getType().getAnnotation(Enumerated.class);
final EnumType type = (enumerated == null) ? EnumType.ORDINAL : enumerated.value();
if (type == EnumType.STRING) {
pstmt.setString(j, value == null ? null : value.toString());
} else if (type == EnumType.ORDINAL) {
pstmt.setLong(j, value != null ? null : ((Ip)value).longValue());
}
} else {
pstmt.setObject(j, value);
}

View File

@ -142,12 +142,21 @@ public class GenericSearchBuilder<T, K> implements MethodInterceptor {
if (name.startsWith("get")) {
String fieldName = Character.toLowerCase(name.charAt(3)) + name.substring(4);
set(fieldName);
return null;
} else if (name.startsWith("is")) {
String fieldName = Character.toLowerCase(name.charAt(2)) + name.substring(3);
set(fieldName);
return null;
} else {
name = name.toLowerCase();
for (String fieldName : _attrs.keySet()) {
if (name.endsWith(fieldName.toLowerCase())) {
set(fieldName);
return null;
}
}
assert false : "Perhaps you need to make the method start with get or is?";
}
}
return methodProxy.invokeSuper(object, args);
}
@ -207,8 +216,9 @@ public class GenericSearchBuilder<T, K> implements MethodInterceptor {
}
Attribute[] attrs = _specifiedAttrs.toArray(new Attribute[_specifiedAttrs.size()]);
for(Attribute attr : attrs)
for(Attribute attr : attrs) {
_groupBys.add(attr);
}
_specifiedAttrs.clear();
return this;

View File

@ -223,6 +223,18 @@ public class SqlGenerator {
attr.setTrue(Attribute.Flag.Nullable);
attr.setTrue(Attribute.Flag.Removed);
}
attr = findAttribute(GenericDao.XID_COLUMN);
if (attr != null && attr.field.getType() == String.class) {
attr.setTrue(Attribute.Flag.DaoGenerated);
attr.setFalse(Attribute.Flag.Insertable);
attr.setFalse(Attribute.Flag.Updatable);
attr.setFalse(Attribute.Flag.TimeStamp);
attr.setFalse(Attribute.Flag.Time);
attr.setFalse(Attribute.Flag.Date);
attr.setFalse(Attribute.Flag.Nullable);
attr.setFalse(Attribute.Flag.Removed);
}
}
public Attribute findAttribute(String name) {

View File

@ -47,7 +47,7 @@ public class UpdateBuilder implements MethodInterceptor {
makeIncrChange(name, args);
} else if (name.startsWith("decr")) {
makeDecrChange(name, args);
}
}
return methodProxy.invokeSuper(object, args);
}

View File

@ -0,0 +1,78 @@
/**
* Copyright (C) 2010 Cloud.com, Inc. All rights reserved.
*
* This software is licensed under the GNU General Public License v3 or later.
*
* It is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.cloud.utils.net;
import com.cloud.utils.NumbersUtil;
/**
* Simple Ip implementation class that works with both ip4 and ip6.
*
*/
public class Ip {
long ip;
public Ip(long ip) {
this.ip = ip;
}
public Ip(String ip) {
this.ip = NetUtils.ip2Long(ip);
}
protected Ip() {
}
public String addr() {
return toString();
}
public long longValue() {
return ip;
}
@Override
public String toString() {
return NetUtils.long2Ip(ip);
}
public boolean isIp4() {
return ip < Integer.MAX_VALUE;
}
public boolean isIp6() {
return ip > Integer.MAX_VALUE;
}
@Override
public int hashCode() {
return NumbersUtil.hash(ip);
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Ip) {
return ip == ((Ip)obj).ip;
} else if (obj instanceof String) {
return ip == NetUtils.ip2Long((String)obj);
} else if (obj instanceof Long) {
return ip == (Long)obj;
} else {
return false;
}
}
}

View File

@ -89,8 +89,9 @@ public class NetUtils {
}
InetAddress[] addrs = new InetAddress[addrList.size()];
if(addrList.size() > 0)
System.arraycopy(addrList.toArray(), 0, addrs, 0, addrList.size());
if(addrList.size() > 0) {
System.arraycopy(addrList.toArray(), 0, addrs, 0, addrList.size());
}
return addrs;
}
@ -98,11 +99,13 @@ public class NetUtils {
InetAddress[] addrs = getAllLocalInetAddresses();
if(addrs != null) {
for(InetAddress addr : addrs) {
if(s_logger.isInfoEnabled())
s_logger.info("Check local InetAddress : " + addr.toString() + ", total count :" + addrs.length);
if(s_logger.isInfoEnabled()) {
s_logger.info("Check local InetAddress : " + addr.toString() + ", total count :" + addrs.length);
}
if(!addr.isLoopbackAddress())
return addr;
if(!addr.isLoopbackAddress()) {
return addr;
}
}
}
@ -125,8 +128,9 @@ public class NetUtils {
}
InetAddress[] addrs = new InetAddress[addrList.size()];
if(addrList.size() > 0)
System.arraycopy(addrList.toArray(), 0, addrs, 0, addrList.size());
if(addrList.size() > 0) {
System.arraycopy(addrList.toArray(), 0, addrs, 0, addrList.size());
}
return addrs;
}
@ -151,8 +155,9 @@ public class NetUtils {
if(addrs != null) {
for(InetAddress self : addrs) {
if(self.equals(addr))
return true;
if(self.equals(addr)) {
return true;
}
}
}
return false;
@ -191,8 +196,9 @@ public class NetUtils {
NetworkInterface ni = NetworkInterface.getByInetAddress(address);
byte[] mac = ni.getHardwareAddress();
for (int i = 0; i < mac.length; i++)
macAddressAsLong |= ((long)(mac[i] & 0xff) << (mac.length - i - 1)*8);
for (int i = 0; i < mac.length; i++) {
macAddressAsLong |= ((long)(mac[i] & 0xff) << (mac.length - i - 1)*8);
}
} catch (SocketException e) {
s_logger.error("SocketException when trying to retrieve MAC address", e);
@ -337,8 +343,9 @@ public class NetUtils {
public static boolean isValidPrivateIp(String ipAddress, String guestIPAddress) {
InetAddress privIp = parseIpAddress(ipAddress);
if (privIp == null)
return false;
if (privIp == null) {
return false;
}
if (!privIp.isSiteLocalAddress()) {
return false;
}
@ -350,7 +357,9 @@ public class NetUtils {
}
String[] ipList = ipAddress.split("\\.");
if (!ipList[0].equals(firstGuestOctet)) return false;
if (!ipList[0].equals(firstGuestOctet)) {
return false;
}
return true;
}
@ -365,7 +374,9 @@ public class NetUtils {
}
public static boolean validIpRange(String startIP, String endIP) {
if (endIP == null || endIP.isEmpty()) return true;
if (endIP == null || endIP.isEmpty()) {
return true;
}
long startIPLong = NetUtils.ip2Long(startIP);
long endIPLong = NetUtils.ip2Long(endIP);
@ -390,10 +401,14 @@ public class NetUtils {
return false;
}
// Each octet must be between 0 and 255, inclusive
if (octet < 0 || octet > 255) return false;
if (octet < 0 || octet > 255) {
return false;
}
// Each octetString must have between 1 and 3 characters
if (octetString.length() < 1 || octetString.length() > 3) return false;
if (octetString.length() < 1 || octetString.length() > 3) {
return false;
}
}
@ -402,12 +417,18 @@ public class NetUtils {
}
public static boolean isValidCIDR(final String cidr) {
if (cidr == null || cidr.isEmpty()) return false;
if (cidr == null || cidr.isEmpty()) {
return false;
}
String[] cidrPair = cidr.split("\\/");
if (cidrPair.length != 2) return false;
if (cidrPair.length != 2) {
return false;
}
String cidrAddress = cidrPair[0];
String cidrSize = cidrPair[1];
if (!isValidIp(cidrAddress)) return false;
if (!isValidIp(cidrAddress)) {
return false;
}
int cidrSizeNum = -1;
try {
@ -416,14 +437,17 @@ public class NetUtils {
return false;
}
if (cidrSizeNum < 0 || cidrSizeNum > 32) return false;
if (cidrSizeNum < 0 || cidrSizeNum > 32) {
return false;
}
return true;
}
public static boolean isValidNetmask(String netmask) {
if (!isValidIp(netmask))
return false;
if (!isValidIp(netmask)) {
return false;
}
long ip = ip2Long(netmask);
int count = 0;
@ -432,14 +456,16 @@ public class NetUtils {
if (((ip >> i) & 0x1) == 0) {
finished = true;
} else {
if (finished)
return false;
if (finished) {
return false;
}
count += 1;
}
}
if (count == 0)
return false;
if (count == 0) {
return false;
}
return true;
}
@ -523,7 +549,9 @@ public class NetUtils {
}
public static boolean sameSubnet(final String ip1, final String ip2, final String netmask) {
if (ip1 == null || ip1.isEmpty() || ip2 == null || ip2.isEmpty()) return true;
if (ip1 == null || ip1.isEmpty() || ip2 == null || ip2.isEmpty()) {
return true;
}
String subnet1 = NetUtils.getSubNet(ip1, netmask);
String subnet2 = NetUtils.getSubNet(ip2, netmask);
@ -531,7 +559,9 @@ public class NetUtils {
}
public static boolean sameSubnetCIDR(final String ip1, final String ip2, final long cidrSize) {
if (ip1 == null || ip1.isEmpty() || ip2 == null || ip2.isEmpty()) return true;
if (ip1 == null || ip1.isEmpty() || ip2 == null || ip2.isEmpty()) {
return true;
}
String subnet1 = NetUtils.getCidrSubNet(ip1, cidrSize);
String subnet2 = NetUtils.getCidrSubNet(ip2, cidrSize);
@ -557,8 +587,9 @@ public class NetUtils {
long result = ipAddr & subnet;
int bits = (subnet == 0)?0:1;
long subnet2 = subnet;
while ((subnet2 = (subnet2 >> 1) & subnet) != 0 )
bits++;
while ((subnet2 = (subnet2 >> 1) & subnet) != 0 ) {
bits++;
}
return long2Ip(result) + "/" + Integer.toString(bits);
}
@ -569,8 +600,9 @@ public class NetUtils {
long start = (ipAddr & subnet) + 1;
long end = start;
int bits = (subnet == 0)?0:1;
while ((subnet = (subnet >> 1) & subnet) != 0 )
bits++;
while ((subnet = (subnet >> 1) & subnet) != 0 ) {
bits++;
}
end = end >> (32 - bits);
end++;
@ -590,12 +622,18 @@ public class NetUtils {
}
public static Long cidrToLong(String cidr) {
if (cidr == null || cidr.isEmpty()) return null;
if (cidr == null || cidr.isEmpty()) {
return null;
}
String[] cidrPair = cidr.split("\\/");
if (cidrPair.length != 2) return null;
if (cidrPair.length != 2) {
return null;
}
String cidrAddress = cidrPair[0];
String cidrSize = cidrPair[1];
if (!isValidIp(cidrAddress)) return null;
if (!isValidIp(cidrAddress)) {
return null;
}
int cidrSizeNum = -1;
try {
@ -609,12 +647,18 @@ public class NetUtils {
}
public static String getCidrSubNet(String cidr) {
if (cidr == null || cidr.isEmpty()) return null;
if (cidr == null || cidr.isEmpty()) {
return null;
}
String[] cidrPair = cidr.split("\\/");
if (cidrPair.length != 2) return null;
if (cidrPair.length != 2) {
return null;
}
String cidrAddress = cidrPair[0];
String cidrSize = cidrPair[1];
if (!isValidIp(cidrAddress)) return null;
if (!isValidIp(cidrAddress)) {
return null;
}
int cidrSizeNum = -1;
try {
@ -660,6 +704,10 @@ public class NetUtils {
}
}
public static boolean isValidPort(int p) {
return !(p > 65535 || p < 1);
}
public static boolean isValidLBPort(String p) {
try {
int port = Integer.parseInt(p);