diff --git a/api/src/com/cloud/agent/api/routing/RoutingCommand.java b/api/src/com/cloud/agent/api/routing/RoutingCommand.java
new file mode 100644
index 00000000000..37c94f1de7c
--- /dev/null
+++ b/api/src/com/cloud/agent/api/routing/RoutingCommand.java
@@ -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 .
+ *
+ */
+package com.cloud.agent.api.routing;
+
+import java.util.HashMap;
+
+import com.cloud.agent.api.Command;
+
+public abstract class RoutingCommand extends Command {
+ HashMap accessDetails = new HashMap(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;
+ }
+
+}
diff --git a/api/src/com/cloud/agent/api/routing/SetFirewallRulesAnswer.java b/api/src/com/cloud/agent/api/routing/SetFirewallRulesAnswer.java
new file mode 100644
index 00000000000..701b5f5aeb8
--- /dev/null
+++ b/api/src/com/cloud/agent/api/routing/SetFirewallRulesAnswer.java
@@ -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 .
+ *
+ */
+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;
+ }
+}
diff --git a/api/src/com/cloud/agent/api/routing/SetFirewallRulesCommand.java b/api/src/com/cloud/agent/api/routing/SetFirewallRulesCommand.java
new file mode 100644
index 00000000000..56d5c1d1a81
--- /dev/null
+++ b/api/src/com/cloud/agent/api/routing/SetFirewallRulesCommand.java
@@ -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 .
+ *
+ */
+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 rules) {
+ this.rules = rules.toArray(new FirewallRuleTO[rules.size()]);
+ }
+
+ public FirewallRuleTO[] getRules() {
+ return rules;
+ }
+}
diff --git a/api/src/com/cloud/agent/api/routing/SetPortForwardingRulesAnswer.java b/api/src/com/cloud/agent/api/routing/SetPortForwardingRulesAnswer.java
new file mode 100644
index 00000000000..b24d077a540
--- /dev/null
+++ b/api/src/com/cloud/agent/api/routing/SetPortForwardingRulesAnswer.java
@@ -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 .
+ *
+ */
+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;
+ }
+}
diff --git a/api/src/com/cloud/agent/api/routing/SetPortForwardingRulesCommand.java b/api/src/com/cloud/agent/api/routing/SetPortForwardingRulesCommand.java
new file mode 100644
index 00000000000..17b9f11c74b
--- /dev/null
+++ b/api/src/com/cloud/agent/api/routing/SetPortForwardingRulesCommand.java
@@ -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 .
+ *
+ */
+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 rules) {
+ this.rules = rules.toArray(new PortForwardingRuleTO[rules.size()]);
+ }
+
+ public PortForwardingRuleTO[] getRules() {
+ return rules;
+ }
+}
diff --git a/api/src/com/cloud/agent/api/to/FirewallRuleTO.java b/api/src/com/cloud/agent/api/to/FirewallRuleTO.java
new file mode 100644
index 00000000000..e26be6afb0f
--- /dev/null
+++ b/api/src/com/cloud/agent/api/to/FirewallRuleTO.java
@@ -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 .
+ *
+ */
+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;
+ }
+}
diff --git a/api/src/com/cloud/agent/api/to/PortForwardingRuleTO.java b/api/src/com/cloud/agent/api/to/PortForwardingRuleTO.java
new file mode 100644
index 00000000000..6ca81d84844
--- /dev/null
+++ b/api/src/com/cloud/agent/api/to/PortForwardingRuleTO.java
@@ -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 .
+ *
+ */
+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;
+ }
+}
diff --git a/api/src/com/cloud/api/BaseCmd.java b/api/src/com/cloud/api/BaseCmd.java
index ae103291e6d..15c9bd62ed8 100755
--- a/api/src/com/cloud/api/BaseCmd.java
+++ b/api/src/com/cloud/api/BaseCmd.java
@@ -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("<");
- else if (c == '>')
- sOUT.append(">");
- else if (c == '&')
- sOUT.append("&");
- else if (c == '"')
- sOUT.append(""");
- else if (c == '\'')
- sOUT.append("'");
- else
- sOUT.append(c);
+ if (c == '<') {
+ sOUT.append("<");
+ } else if (c == '>') {
+ sOUT.append(">");
+ } else if (c == '&') {
+ sOUT.append("&");
+ } else if (c == '"') {
+ sOUT.append(""");
+ } else if (c == '\'') {
+ sOUT.append("'");
+ } else {
+ sOUT.append(c);
+ }
}
return sOUT.toString();
}
diff --git a/api/src/com/cloud/api/ResponseGenerator.java b/api/src/com/cloud/api/ResponseGenerator.java
index 75dad3250e8..6f2f6ad2ef7 100644
--- a/api/src/com/cloud/api/ResponseGenerator.java
+++ b/api/src/com/cloud/api/ResponseGenerator.java
@@ -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);
diff --git a/api/src/com/cloud/api/commands/AssignToLoadBalancerRuleCmd.java b/api/src/com/cloud/api/commands/AssignToLoadBalancerRuleCmd.java
index 4bc5494b85c..405cda1d635 100644
--- a/api/src/com/cloud/api/commands/AssignToLoadBalancerRuleCmd.java
+++ b/api/src/com/cloud/api/commands/AssignToLoadBalancerRuleCmd.java
@@ -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();
+ }
+
+ 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");
}
}
}
diff --git a/api/src/com/cloud/api/commands/CreateIpForwardingRuleCmd.java b/api/src/com/cloud/api/commands/CreateIpForwardingRuleCmd.java
index bbff4bf0343..b6af0dbeef6 100644
--- a/api/src/com/cloud/api/commands/CreateIpForwardingRuleCmd.java
+++ b/api/src/com/cloud/api/commands/CreateIpForwardingRuleCmd.java
@@ -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 {
diff --git a/api/src/com/cloud/api/commands/CreateLoadBalancerRuleCmd.java b/api/src/com/cloud/api/commands/CreateLoadBalancerRuleCmd.java
index 61c585fb1f4..65a5cd3c93a 100644
--- a/api/src/com/cloud/api/commands/CreateLoadBalancerRuleCmd.java
+++ b/api/src/com/cloud/api/commands/CreateLoadBalancerRuleCmd.java
@@ -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");
}
}
diff --git a/api/src/com/cloud/api/commands/CreatePortForwardingRuleCmd.java b/api/src/com/cloud/api/commands/CreatePortForwardingRuleCmd.java
index aa58fd14a7b..dca0fbf816e 100644
--- a/api/src/com/cloud/api/commands/CreatePortForwardingRuleCmd.java
+++ b/api/src/com/cloud/api/commands/CreatePortForwardingRuleCmd.java
@@ -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);
+ }
}
diff --git a/api/src/com/cloud/api/commands/DeleteIpForwardingRuleCmd.java b/api/src/com/cloud/api/commands/DeleteIpForwardingRuleCmd.java
index 916c78151ab..2c62fc0a9f5 100644
--- a/api/src/com/cloud/api/commands/DeleteIpForwardingRuleCmd.java
+++ b/api/src/com/cloud/api/commands/DeleteIpForwardingRuleCmd.java
@@ -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);
diff --git a/api/src/com/cloud/api/commands/DeleteLoadBalancerRuleCmd.java b/api/src/com/cloud/api/commands/DeleteLoadBalancerRuleCmd.java
index 9bb6255d167..356e9c0398b 100644
--- a/api/src/com/cloud/api/commands/DeleteLoadBalancerRuleCmd.java
+++ b/api/src/com/cloud/api/commands/DeleteLoadBalancerRuleCmd.java
@@ -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);
diff --git a/api/src/com/cloud/api/commands/DeletePortForwardingRuleCmd.java b/api/src/com/cloud/api/commands/DeletePortForwardingRuleCmd.java
index 230902236b6..a29628c2864 100644
--- a/api/src/com/cloud/api/commands/DeletePortForwardingRuleCmd.java
+++ b/api/src/com/cloud/api/commands/DeletePortForwardingRuleCmd.java
@@ -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 {
diff --git a/api/src/com/cloud/api/commands/ListIpForwardingRulesCmd.java b/api/src/com/cloud/api/commands/ListIpForwardingRulesCmd.java
index a371a48c822..7554c8b28fb 100644
--- a/api/src/com/cloud/api/commands/ListIpForwardingRulesCmd.java
+++ b/api/src/com/cloud/api/commands/ListIpForwardingRulesCmd.java
@@ -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 response = new ListResponse();
List ipForwardingResponses = new ArrayList();
- for (FirewallRule rule : result) {
+ for (PortForwardingRule rule : result) {
IpForwardingRuleResponse resp = _responseGenerator.createIpForwardingRuleResponse(rule);
if (resp != null) {
ipForwardingResponses.add(resp);
diff --git a/api/src/com/cloud/api/commands/ListLoadBalancerRuleInstancesCmd.java b/api/src/com/cloud/api/commands/ListLoadBalancerRuleInstancesCmd.java
index d8a467d90ac..d7b8563b876 100644
--- a/api/src/com/cloud/api/commands/ListLoadBalancerRuleInstancesCmd.java
+++ b/api/src/com/cloud/api/commands/ListLoadBalancerRuleInstancesCmd.java
@@ -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 response = new ListResponse();
List vmResponses = new ArrayList();
for (UserVm instance : result) {
diff --git a/api/src/com/cloud/api/commands/ListLoadBalancerRulesCmd.java b/api/src/com/cloud/api/commands/ListLoadBalancerRulesCmd.java
index 37b12409fc8..2ac47421894 100644
--- a/api/src/com/cloud/api/commands/ListLoadBalancerRulesCmd.java
+++ b/api/src/com/cloud/api/commands/ListLoadBalancerRulesCmd.java
@@ -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 response = new ListResponse();
List lbResponses = new ArrayList();
for (LoadBalancer loadBalancer : loadBalancers) {
diff --git a/api/src/com/cloud/api/commands/ListPortForwardingRulesCmd.java b/api/src/com/cloud/api/commands/ListPortForwardingRulesCmd.java
index 558871cdf89..230f9c67f4d 100644
--- a/api/src/com/cloud/api/commands/ListPortForwardingRulesCmd.java
+++ b/api/src/com/cloud/api/commands/ListPortForwardingRulesCmd.java
@@ -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 response = new ListResponse();
List fwResponses = new ArrayList();
- for (FirewallRule fwRule : result) {
+ for (PortForwardingRule fwRule : result) {
FirewallRuleResponse ruleData = _responseGenerator.createFirewallRuleResponse(fwRule);
ruleData.setObjectName("portforwardingrule");
fwResponses.add(ruleData);
diff --git a/api/src/com/cloud/api/commands/RemoveFromLoadBalancerRuleCmd.java b/api/src/com/cloud/api/commands/RemoveFromLoadBalancerRuleCmd.java
index b5ab094b8ca..5c08fc4ba8a 100644
--- a/api/src/com/cloud/api/commands/RemoveFromLoadBalancerRuleCmd.java
+++ b/api/src/com/cloud/api/commands/RemoveFromLoadBalancerRuleCmd.java
@@ -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();
+ }
+
+ if (virtualMachineId != null) {
+ virtualMachineIds.add(virtualMachineId);
+ }
+
+ boolean result = _lbService.removeFromLoadBalancer(id, virtualMachineIds);
if (result) {
SuccessResponse response = new SuccessResponse(getName());
this.setResponseObject(response);
diff --git a/api/src/com/cloud/api/commands/UpdateLoadBalancerRuleCmd.java b/api/src/com/cloud/api/commands/UpdateLoadBalancerRuleCmd.java
index 35c0b3c4799..4481fcfb37f 100644
--- a/api/src/com/cloud/api/commands/UpdateLoadBalancerRuleCmd.java
+++ b/api/src/com/cloud/api/commands/UpdateLoadBalancerRuleCmd.java
@@ -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());
diff --git a/api/src/com/cloud/api/commands/UpdatePortForwardingRuleCmd.java b/api/src/com/cloud/api/commands/UpdatePortForwardingRuleCmd.java
index c676b4f3b62..bf786930fdd 100644
--- a/api/src/com/cloud/api/commands/UpdatePortForwardingRuleCmd.java
+++ b/api/src/com/cloud/api/commands/UpdatePortForwardingRuleCmd.java
@@ -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");
+// }
}
}
diff --git a/api/src/com/cloud/network/NetworkService.java b/api/src/com/cloud/network/NetworkService.java
index 04ad345671f..249dcc7fe64 100644
--- a/api/src/com/cloud/network/NetworkService.java
+++ b/api/src/com/cloud/network/NetworkService.java
@@ -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;
diff --git a/api/src/com/cloud/network/element/NetworkElement.java b/api/src/com/cloud/network/element/NetworkElement.java
index 4439861792b..cabdd12424c 100644
--- a/api/src/com/cloud/network/element/NetworkElement.java
+++ b/api/src/com/cloud/network/element/NetworkElement.java
@@ -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;
}
diff --git a/api/src/com/cloud/network/lb/LoadBalancingRulesService.java b/api/src/com/cloud/network/lb/LoadBalancingRulesService.java
new file mode 100644
index 00000000000..c8db7e5d69a
--- /dev/null
+++ b/api/src/com/cloud/network/lb/LoadBalancingRulesService.java
@@ -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 .
+ *
+ */
+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 vmIds);
+
+ boolean removeFromLoadBalancer(long lbRuleId, List 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);
+
+}
diff --git a/api/src/com/cloud/network/rules/FirewallRule.java b/api/src/com/cloud/network/rules/FirewallRule.java
index b87b6eeccab..7e4e94f2338 100644
--- a/api/src/com/cloud/network/rules/FirewallRule.java
+++ b/api/src/com/cloud/network/rules/FirewallRule.java
@@ -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();
}
diff --git a/api/src/com/cloud/network/LoadBalancer.java b/api/src/com/cloud/network/rules/LoadBalancer.java
similarity index 67%
rename from api/src/com/cloud/network/LoadBalancer.java
rename to api/src/com/cloud/network/rules/LoadBalancer.java
index 792f789fc50..a16cd599767 100644
--- a/api/src/com/cloud/network/LoadBalancer.java
+++ b/api/src/com/cloud/network/rules/LoadBalancer.java
@@ -15,30 +15,30 @@
* along with this program. If not, see .
*
*/
-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();
+ }
}
diff --git a/api/src/com/cloud/network/rules/PortForwardingRule.java b/api/src/com/cloud/network/rules/PortForwardingRule.java
new file mode 100644
index 00000000000..7ba685c6d46
--- /dev/null
+++ b/api/src/com/cloud/network/rules/PortForwardingRule.java
@@ -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 .
+ *
+ */
+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();
+}
diff --git a/api/src/com/cloud/network/rules/RulesService.java b/api/src/com/cloud/network/rules/RulesService.java
new file mode 100644
index 00000000000..96d77d18087
--- /dev/null
+++ b/api/src/com/cloud/network/rules/RulesService.java
@@ -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 .
+ *
+ */
+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);
+
+}
diff --git a/api/src/com/cloud/server/ManagementService.java b/api/src/com/cloud/server/ManagementService.java
index 4ebb4769926..009fe7ae061 100644
--- a/api/src/com/cloud/server/ManagementService.java
+++ b/api/src/com/cloud/server/ManagementService.java
@@ -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();
/**
diff --git a/core/src/com/cloud/agent/api/routing/SetFirewallRuleCommand.java b/core/src/com/cloud/agent/api/routing/SetFirewallRuleCommand.java
deleted file mode 100755
index d04e91ba8ff..00000000000
--- a/core/src/com/cloud/agent/api/routing/SetFirewallRuleCommand.java
+++ /dev/null
@@ -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 .
- *
- */
-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;
- }
-
-}
diff --git a/core/src/com/cloud/agent/resource/virtualnetwork/VirtualRoutingResource.java b/core/src/com/cloud/agent/resource/virtualnetwork/VirtualRoutingResource.java
index 62a2dc8960a..115efd2803d 100755
--- a/core/src/com/cloud/agent/resource/virtualnetwork/VirtualRoutingResource.java
+++ b/core/src/com/cloud/agent/resource/virtualnetwork/VirtualRoutingResource.java
@@ -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;
diff --git a/core/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java b/core/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java
index 44f6c4d50e3..8a230c23844 100644
--- a/core/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java
+++ b/core/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java
@@ -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 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 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();
// 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 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 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 pbds = sr.getPBDs(conn);
- if (pbds.isEmpty())
+ if (pbds.isEmpty()) {
continue;
+ }
PBD pbd = pbds.iterator().next();
Map 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 srs = SR.getAll(conn);
for (SR sr : srs) {
- if (!SRType.NFS.equals(sr.getType(conn)))
+ if (!SRType.NFS.equals(sr.getType(conn))) {
continue;
+ }
Set pbds = sr.getPBDs(conn);
- if (pbds.isEmpty())
+ if (pbds.isEmpty()) {
continue;
+ }
PBD pbd = pbds.iterator().next();
Map 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;
diff --git a/core/src/com/cloud/network/FirewallRuleVO.java b/core/src/com/cloud/network/FirewallRuleVO.java
deleted file mode 100644
index 159d6ee44e2..00000000000
--- a/core/src/com/cloud/network/FirewallRuleVO.java
+++ /dev/null
@@ -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 .
- *
- */
-
-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;
- }
-
-}
-
diff --git a/core/src/com/cloud/network/LoadBalancerConfigurator.java b/core/src/com/cloud/network/LoadBalancerConfigurator.java
index df7bda4a658..f79ae8f15f4 100644
--- a/core/src/com/cloud/network/LoadBalancerConfigurator.java
+++ b/core/src/com/cloud/network/LoadBalancerConfigurator.java
@@ -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 fwRules);
- public String [][] generateFwRules(List fwRules);
+ public String [] generateConfiguration(List fwRules);
+ public String [][] generateFwRules(List fwRules);
}
diff --git a/server/src/com/cloud/api/ApiDBUtils.java b/server/src/com/cloud/api/ApiDBUtils.java
index 02a3f4a2a11..f6baeab15cc 100755
--- a/server/src/com/cloud/api/ApiDBUtils.java
+++ b/server/src/com/cloud/api/ApiDBUtils.java
@@ -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) {
diff --git a/server/src/com/cloud/api/ApiResponseHelper.java b/server/src/com/cloud/api/ApiResponseHelper.java
index 9e75c94801a..fc9b458793f 100644
--- a/server/src/com/cloud/api/ApiResponseHelper.java
+++ b/server/src/com/cloud/api/ApiResponseHelper.java
@@ -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());
diff --git a/server/src/com/cloud/async/executor/UpdateLoadBalancerRuleExecutor.java b/server/src/com/cloud/async/executor/UpdateLoadBalancerRuleExecutor.java
deleted file mode 100644
index 7e182bddd24..00000000000
--- a/server/src/com/cloud/async/executor/UpdateLoadBalancerRuleExecutor.java
+++ /dev/null
@@ -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;
- }
-}
diff --git a/server/src/com/cloud/async/executor/UpdatePortForwardingRuleExecutor.java b/server/src/com/cloud/async/executor/UpdatePortForwardingRuleExecutor.java
deleted file mode 100644
index 65c2d668205..00000000000
--- a/server/src/com/cloud/async/executor/UpdatePortForwardingRuleExecutor.java
+++ /dev/null
@@ -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 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;
- }
-}
diff --git a/server/src/com/cloud/configuration/DefaultComponentLibrary.java b/server/src/com/cloud/configuration/DefaultComponentLibrary.java
index fe1c9f8cbdc..99dc726a6cf 100644
--- a/server/src/com/cloud/configuration/DefaultComponentLibrary.java
+++ b/server/src/com/cloud/configuration/DefaultComponentLibrary.java
@@ -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>> _daos = new LinkedHashMap>>();
+ protected final Map>> _daos = new LinkedHashMap>>();
protected ComponentInfo extends GenericDao, ? extends Serializable>> addDao(String name, Class extends GenericDao, ? extends Serializable>> clazz) {
return addDao(name, clazz, new ArrayList>(), 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> _managers = new HashMap>();
@@ -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 List> addAdapterChain(Class interphace, List>> adapters) {
@@ -311,4 +316,11 @@ public class DefaultComponentLibrary implements ComponentLibrary {
}
return _adapters;
}
+
+ @Override
+ public synchronized Map, Class>> getFactories() {
+ HashMap, Class>> factories = new HashMap, Class>>();
+ factories.put(EntityManager.class, EntityManagerImpl.class);
+ return factories;
+ }
}
diff --git a/server/src/com/cloud/dao/EntityManagerImpl.java b/server/src/com/cloud/dao/EntityManagerImpl.java
index 2b287257f7f..0a968ec0b9d 100644
--- a/server/src/com/cloud/dao/EntityManagerImpl.java
+++ b/server/src/com/cloud/dao/EntityManagerImpl.java
@@ -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 findById(Class 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 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() {
diff --git a/server/src/com/cloud/network/HAProxyConfigurator.java b/server/src/com/cloud/network/HAProxyConfigurator.java
index bae703d8e23..2a834a67436 100644
--- a/server/src/com/cloud/network/HAProxyConfigurator.java
+++ b/server/src/com/cloud/network/HAProxyConfigurator.java
@@ -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 fwRules) {
+ public String[] generateConfiguration(List fwRules) {
//Group the rules by publicip:publicport
- Map> pools = new HashMap>();
+ Map> pools = new HashMap>();
- 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 fwList = pools.get(poolName);
+ String poolName = sb.append(rule.getSrcIp().replace(".", "_")).append('-').append(rule.getSrcPortRange()[0]).toString();
+ if (!rule.revoked()) {
+ List fwList = pools.get(poolName);
if (fwList == null) {
- fwList = new ArrayList();
+ fwList = new ArrayList();
pools.put(poolName, fwList);
}
fwList.add(rule);
@@ -95,7 +96,7 @@ public class HAProxyConfigurator implements LoadBalancerConfigurator {
}
result.add(getBlankLine());
- for (Map.Entry> e : pools.entrySet()){
+ for (Map.Entry> e : pools.entrySet()){
List 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 getRulesForPool(String poolName, List fwRules) {
- FirewallRuleVO firstRule = fwRules.get(0);
- String publicIP = firstRule.getPublicIpAddress();
- String publicPort = firstRule.getPublicPort();
- String algorithm = firstRule.getAlgorithm();
+ private List getRulesForPool(String poolName, List fwRules) {
+ PortForwardingRuleTO firstRule = fwRules.get(0);
+ String publicIP = firstRule.getSrcIp();
+ String publicPort = Integer.toString(firstRule.getSrcPortRange()[0]);
+// FIXEME: String algorithm = firstRule.getAlgorithm();
List result = new ArrayList();
//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 fwRules) {
+ public String[][] generateFwRules(List fwRules) {
String [][] result = new String [2][];
Set toAdd = new HashSet();
Set toRemove = new HashSet();
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;
}
-
}
diff --git a/server/src/com/cloud/network/IPAddressVO.java b/server/src/com/cloud/network/IPAddressVO.java
index 0592921893f..08a34ab8ae7 100644
--- a/server/src/com/cloud/network/IPAddressVO.java
+++ b/server/src/com/cloud/network/IPAddressVO.java
@@ -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();
}
-
}
diff --git a/server/src/com/cloud/network/LoadBalancerVMMapVO.java b/server/src/com/cloud/network/LoadBalancerVMMapVO.java
index 72d8599bc25..f8381a9bc8b 100644
--- a/server/src/com/cloud/network/LoadBalancerVMMapVO.java
+++ b/server/src/com/cloud/network/LoadBalancerVMMapVO.java
@@ -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;
}
diff --git a/server/src/com/cloud/network/LoadBalancerVO.java b/server/src/com/cloud/network/LoadBalancerVO.java
index b929df23bbb..7e7788f7c60 100644
--- a/server/src/com/cloud/network/LoadBalancerVO.java
+++ b/server/src/com/cloud/network/LoadBalancerVO.java
@@ -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;
}
}
diff --git a/server/src/com/cloud/network/NetworkManager.java b/server/src/com/cloud/network/NetworkManager.java
index 06ec7fd910a..3b2822647b0 100644
--- a/server/src/com/cloud/network/NetworkManager.java
+++ b/server/src/com/cloud/network/NetworkManager.java
@@ -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 updatePortForwardingRules(List 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 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 updateFirewallRules(String publicIpAddress, List 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 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;
}
diff --git a/server/src/com/cloud/network/NetworkManagerImpl.java b/server/src/com/cloud/network/NetworkManagerImpl.java
index a805d08baaa..9c0b37e240c 100755
--- a/server/src/com/cloud/network/NetworkManagerImpl.java
+++ b/server/src/com/cloud/network/NetworkManagerImpl.java
@@ -23,10 +23,8 @@ import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
-import java.util.HashSet;
import java.util.List;
import java.util.Map;
-import java.util.Set;
import java.util.concurrent.ScheduledExecutorService;
import javax.ejb.Local;
@@ -39,29 +37,20 @@ import com.cloud.agent.AgentManager.OnError;
import com.cloud.agent.api.Answer;
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.SetFirewallRuleCommand;
import com.cloud.agent.api.to.NicTO;
import com.cloud.agent.manager.Commands;
import com.cloud.alert.AlertManager;
import com.cloud.api.BaseCmd;
import com.cloud.api.ServerApiException;
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.async.AsyncJobManager;
import com.cloud.capacity.dao.CapacityDao;
import com.cloud.configuration.Config;
@@ -94,12 +83,10 @@ import com.cloud.exception.InsufficientAddressCapacityException;
import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.InsufficientNetworkCapacityException;
import com.cloud.exception.InvalidParameterValueException;
-import com.cloud.exception.NetworkRuleConflictException;
import com.cloud.exception.OperationTimedoutException;
import com.cloud.exception.PermissionDeniedException;
import com.cloud.exception.ResourceAllocationException;
import com.cloud.exception.ResourceUnavailableException;
-import com.cloud.host.HostVO;
import com.cloud.host.dao.HostDao;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.network.Networks.AddressFormat;
@@ -134,7 +121,6 @@ import com.cloud.storage.dao.VolumeDao;
import com.cloud.user.Account;
import com.cloud.user.AccountManager;
import com.cloud.user.AccountVO;
-import com.cloud.user.User;
import com.cloud.user.UserContext;
import com.cloud.user.UserStatisticsVO;
import com.cloud.user.dao.AccountDao;
@@ -142,9 +128,6 @@ import com.cloud.user.dao.UserDao;
import com.cloud.user.dao.UserStatisticsDao;
import com.cloud.uservm.UserVm;
import com.cloud.utils.Pair;
-import com.cloud.utils.PasswordGenerator;
-import com.cloud.utils.StringUtils;
-import com.cloud.utils.Ternary;
import com.cloud.utils.component.Adapters;
import com.cloud.utils.component.Inject;
import com.cloud.utils.component.Manager;
@@ -156,6 +139,7 @@ import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.exception.CloudRuntimeException;
+import com.cloud.utils.net.Ip;
import com.cloud.utils.net.NetUtils;
import com.cloud.vm.DomainRouterVO;
import com.cloud.vm.Nic;
@@ -821,812 +805,141 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
return answers[0].getResult();
}
- @Override
- public boolean updateFirewallRule(final FirewallRuleVO rule, String oldPrivateIP, String oldPrivatePort) {
-
- final IPAddressVO ipVO = _ipAddressDao.findById(rule.getPublicIpAddress());
- if (ipVO == null || ipVO.getAllocated() == null) {
- return false;
- }
-
- final DomainRouterVO router = _routerMgr.getRouter(ipVO.getAccountId(), ipVO.getDataCenterId());
- Long hostId = router.getHostId();
- if (router == null || router.getHostId() == null) {
- return true;
- }
-
- if (rule.isForwarding()) {
- return updatePortForwardingRule(rule, router, hostId, oldPrivateIP, oldPrivatePort);
- } else if (rule.getGroupId() != null) {
- final List fwRules = _rulesDao.listIPForwardingForLB(ipVO.getAccountId(), ipVO.getDataCenterId());
-
- return updateLoadBalancerRules(fwRules, router, hostId);
- }
- return true;
- }
-
- @Override
- public List updateFirewallRules(final String publicIpAddress, final List fwRules, final DomainRouterVO router) {
- final List result = new ArrayList();
- if (fwRules.size() == 0) {
- return result;
- }
-
- if (router == null || router.getHostId() == null) {
- return fwRules;
- } else {
- final HostVO host = _hostDao.findById(router.getHostId());
- return updateFirewallRules(host, router.getInstanceName(), router.getPrivateIpAddress(), fwRules);
- }
- }
-
- public List updateFirewallRules(final HostVO host, final String routerName, final String routerIp, final List fwRules) {
- final List result = new ArrayList();
- if (fwRules.size() == 0) {
- s_logger.debug("There are no firewall rules");
- return result;
- }
-
- Commands cmds = new Commands(OnError.Continue);
- final List lbRules = new ArrayList();
- final List fwdRules = new ArrayList();
-
- int i=0;
- for (FirewallRuleVO rule : fwRules) {
- // Determine the VLAN ID and netmask of the rule's public IP address
- IPAddressVO ip = _ipAddressDao.findById(rule.getPublicIpAddress());
- VlanVO vlan = _vlanDao.findById(new Long(ip.getVlanDbId()));
- String vlanNetmask = vlan.getVlanNetmask();
- rule.setVlanNetmask(vlanNetmask);
-
- if (rule.isForwarding()) {
- fwdRules.add(rule);
- final SetFirewallRuleCommand cmd = new SetFirewallRuleCommand(routerName, routerIp, rule, true);
- cmds.addCommand(cmd);
- } else if (rule.getGroupId() != null){
- lbRules.add(rule);
- }
-
- }
- if (lbRules.size() > 0) { //at least one load balancer rule
- final LoadBalancerConfigurator cfgrtr = new HAProxyConfigurator();
- final String [] cfg = cfgrtr.generateConfiguration(fwRules);
- final String [][] addRemoveRules = cfgrtr.generateFwRules(fwRules);
- final LoadBalancerCfgCommand cmd = new LoadBalancerCfgCommand(cfg, addRemoveRules, routerName, routerIp);
- cmds.addCommand(cmd);
- }
- if (cmds.size() == 0) {
- return result;
- }
- Answer [] answers = null;
- try {
- answers = _agentMgr.send(host.getId(), cmds);
- } catch (final AgentUnavailableException e) {
- s_logger.warn("agent unavailable", e);
- } catch (final OperationTimedoutException e) {
- s_logger.warn("Timed Out", e);
- }
- if (answers == null ){
- return result;
- }
- i=0;
- for (final FirewallRuleVO rule:fwdRules){
- final Answer ans = answers[i++];
- if (ans != null) {
- if (ans.getResult()) {
- result.add(rule);
- } else {
- s_logger.warn("Unable to update firewall rule: " + rule.toString());
- }
- }
- }
- if (i == (answers.length-1)) {
- final Answer lbAnswer = answers[i];
- if (lbAnswer.getResult()) {
- result.addAll(lbRules);
- } else {
- s_logger.warn("Unable to update lb rules.");
- }
- }
- return result;
- }
-
- private boolean updatePortForwardingRule(final FirewallRuleVO rule, final DomainRouterVO router, Long hostId, String oldPrivateIP, String oldPrivatePort) {
- IPAddressVO ip = _ipAddressDao.findById(rule.getPublicIpAddress());
- VlanVO vlan = _vlanDao.findById(new Long(ip.getVlanDbId()));
- rule.setVlanNetmask(vlan.getVlanNetmask());
-
- final SetFirewallRuleCommand cmd = new SetFirewallRuleCommand(router.getInstanceName(), router.getPrivateIpAddress(), rule, oldPrivateIP, oldPrivatePort);
- final Answer ans = _agentMgr.easySend(hostId, cmd);
- if (ans == null) {
- return false;
- } else {
- return ans.getResult();
- }
- }
-
- @Override
- public List updatePortForwardingRules(final List fwRules, final DomainRouterVO router, Long hostId ){
- final List fwdRules = new ArrayList();
- final List result = new ArrayList();
-
- if (fwRules.size() == 0) {
- return result;
- }
-
- Commands cmds = new Commands(OnError.Continue);
- int i=0;
- for (final FirewallRuleVO rule: fwRules) {
- IPAddressVO ip = _ipAddressDao.findById(rule.getPublicIpAddress());
- VlanVO vlan = _vlanDao.findById(new Long(ip.getVlanDbId()));
- String vlanNetmask = vlan.getVlanNetmask();
- rule.setVlanNetmask(vlanNetmask);
- if (rule.isForwarding()) {
- fwdRules.add(rule);
- final SetFirewallRuleCommand cmd = new SetFirewallRuleCommand(router.getInstanceName(), router.getPrivateIpAddress(),rule, false);
- cmds.addCommand(cmd);
- }
- }
- try {
- _agentMgr.send(hostId, cmds);
- } catch (final AgentUnavailableException e) {
- s_logger.warn("agent unavailable", e);
- } catch (final OperationTimedoutException e) {
- s_logger.warn("Timed Out", e);
- }
- Answer[] answers = cmds.getAnswers();
- if (answers == null ){
- return result;
- }
- i=0;
- for (final FirewallRuleVO rule:fwdRules){
- final Answer ans = answers[i++];
- if (ans != null) {
- if (ans.getResult()) {
- result.add(rule);
- }
- }
- }
- return result;
- }
-
- @Override
- public FirewallRuleVO createPortForwardingRule(CreatePortForwardingRuleCmd cmd) throws InvalidParameterValueException, PermissionDeniedException, NetworkRuleConflictException {
- // validate IP Address exists
- IPAddressVO ipAddress = _ipAddressDao.findById(cmd.getIpAddress());
- if (ipAddress == null) {
- throw new InvalidParameterValueException("Unable to create port forwarding rule on address " + ipAddress + ", invalid IP address specified.");
- }
-
- // validate user VM exists
- UserVmVO userVM = _vmDao.findById(cmd.getVirtualMachineId());
- if (userVM == null) {
- throw new InvalidParameterValueException("Unable to create port forwarding rule on address " + ipAddress + ", invalid virtual machine id specified (" + cmd.getVirtualMachineId() + ").");
- }
-
- // validate that IP address and userVM belong to the same account
- if ((ipAddress.getAccountId() == null) || (ipAddress.getAccountId().longValue() != userVM.getAccountId())) {
- throw new InvalidParameterValueException("Unable to create port forwarding rule, IP address " + ipAddress + " owner is not the same as owner of virtual machine " + userVM.toString());
- }
-
- // validate that userVM is in the same availability zone as the IP address
- if (ipAddress.getDataCenterId() != userVM.getDataCenterId()) {
- throw new InvalidParameterValueException("Unable to create port forwarding rule, IP address " + ipAddress + " is not in the same availability zone as virtual machine " + userVM.toString());
- }
-
- // if an admin account was passed in, or no account was passed in, make sure we honor the accountName/domainId parameters
- Account account = UserContext.current().getAccount();
- if (account != null) {
- if ((account.getType() == Account.ACCOUNT_TYPE_ADMIN) || (account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN)) {
- if (!_domainDao.isChildDomain(account.getDomainId(), userVM.getDomainId())) {
- throw new PermissionDeniedException("Unable to create port forwarding rule, IP address " + ipAddress + " to virtual machine " + cmd.getVirtualMachineId() + ", permission denied.");
- }
- } else if (account.getId() != userVM.getAccountId()) {
- throw new PermissionDeniedException("Unable to create port forwarding rule, IP address " + ipAddress + " to virtual machine " + cmd.getVirtualMachineId() + ", permission denied.");
- }
- }
-
- // set up some local variables
- String protocol = cmd.getProtocol();
- String publicPort = cmd.getPublicPort();
- String privatePort = cmd.getPrivatePort();
-
- // sanity check that the vm can be applied to the load balancer
- ServiceOfferingVO offering = _serviceOfferingDao.findById(userVM.getServiceOfferingId());
- if ((offering == null) || !GuestIpType.Virtualized.equals(offering.getGuestIpType())) {
- if (s_logger.isDebugEnabled()) {
- s_logger.debug("Unable to create port forwarding rule (" + protocol + ":" + publicPort + "->" + privatePort + ") for virtual machine " + userVM.toString() + ", bad network type (" + ((offering == null) ? "null" : offering.getGuestIpType()) + ")");
- }
-
- throw new IllegalArgumentException("Unable to create port forwarding rule (" + protocol + ":" + publicPort + "->" + privatePort + ") for virtual machine " + userVM.toString() + ", bad network type (" + ((offering == null) ? "null" : offering.getGuestIpType()) + ")");
- }
-
- // check for ip address/port conflicts by checking existing forwarding and load balancing rules
- List existingRulesOnPubIp = _rulesDao.listIPForwarding(ipAddress.getAddress());
-
- // FIXME: The mapped ports should be String, String, List since more than one proto can be mapped...
- Map>> mappedPublicPorts = new HashMap>>();
-
- if (existingRulesOnPubIp != null) {
- for (FirewallRuleVO fwRule : existingRulesOnPubIp) {
- Ternary> portMappings = mappedPublicPorts.get(fwRule.getPublicPort());
- List protocolList = null;
- if (portMappings == null) {
- protocolList = new ArrayList();
- } else {
- protocolList = portMappings.third();
- }
- protocolList.add(fwRule.getProtocol());
- mappedPublicPorts.put(fwRule.getPublicPort(), new Ternary>(fwRule.getPrivateIpAddress(), fwRule.getPrivatePort(), protocolList));
- }
- }
-
- Ternary> privateIpPort = mappedPublicPorts.get(publicPort);
- if (privateIpPort != null) {
- if (privateIpPort.first().equals(userVM.getGuestIpAddress()) && privateIpPort.second().equals(privatePort)) {
- List protocolList = privateIpPort.third();
- for (String mappedProtocol : protocolList) {
- if (mappedProtocol.equalsIgnoreCase(protocol)) {
- if (s_logger.isDebugEnabled()) {
- s_logger.debug("skipping the creating of firewall rule " + ipAddress + ":" + publicPort + " to " + userVM.getGuestIpAddress() + ":" + privatePort + "; rule already exists.");
- }
- // already mapped
- throw new NetworkRuleConflictException("An existing port forwarding service rule for " + ipAddress + ":" + publicPort
- + " already exists, found while trying to create mapping to " + userVM.getGuestIpAddress() + ":" + privatePort + ".");
- }
- }
- } else {
- // FIXME: Will we need to refactor this for both assign port forwarding service and create port forwarding rule?
- // throw new NetworkRuleConflictException("An existing port forwarding service rule for " + ipAddress + ":" + publicPort
- // + " already exists, found while trying to create mapping to " + userVM.getGuestIpAddress() + ":" + privatePort + ((securityGroupId == null) ? "." : " from port forwarding service "
- // + securityGroupId.toString() + "."));
- throw new NetworkRuleConflictException("An existing port forwarding service rule for " + ipAddress + ":" + publicPort
- + " already exists, found while trying to create mapping to " + userVM.getGuestIpAddress() + ":" + privatePort + ".");
- }
- }
-
- FirewallRuleVO newFwRule = new FirewallRuleVO();
- newFwRule.setEnabled(true);
- newFwRule.setForwarding(true);
- newFwRule.setPrivatePort(privatePort);
- newFwRule.setProtocol(protocol);
- newFwRule.setPublicPort(publicPort);
- newFwRule.setPublicIpAddress(ipAddress.getAddress());
- newFwRule.setPrivateIpAddress(userVM.getGuestIpAddress());
- // newFwRule.setGroupId(securityGroupId);
- newFwRule.setGroupId(null);
-
- // In 1.0 the rules were always persisted when a user created a rule. When the rules get sent down
- // the stopOnError parameter is set to false, so the agent will apply all rules that it can. That
- // behavior is preserved here by persisting the rule before sending it to the agent.
- _rulesDao.persist(newFwRule);
-
- boolean success = updateFirewallRule(newFwRule, null, null);
-
- // Save and create the event
- String description;
- String ruleName = "ip forwarding";
- String level = EventVO.LEVEL_INFO;
-
- if (success == true) {
- description = "created new " + ruleName + " rule [" + newFwRule.getPublicIpAddress() + ":" + newFwRule.getPublicPort() + "]->["
- + newFwRule.getPrivateIpAddress() + ":" + newFwRule.getPrivatePort() + "]" + " " + newFwRule.getProtocol();
- } else {
- level = EventVO.LEVEL_ERROR;
- description = "failed to create new " + ruleName + " rule [" + newFwRule.getPublicIpAddress() + ":" + newFwRule.getPublicPort() + "]->["
- + newFwRule.getPrivateIpAddress() + ":" + newFwRule.getPrivatePort() + "]" + " " + newFwRule.getProtocol();
- }
-
- EventUtils.saveEvent(UserContext.current().getUserId(), userVM.getAccountId(), level, EventTypes.EVENT_NET_RULE_ADD, description);
-
- return newFwRule;
- }
-
- @Override
- public List listPortForwardingRules(ListPortForwardingRulesCmd cmd) throws InvalidParameterValueException, PermissionDeniedException {
- String ipAddress = cmd.getIpAddress();
- Account account = UserContext.current().getAccount();
-
- IPAddressVO ipAddressVO = _ipAddressDao.findById(ipAddress);
- if (ipAddressVO == null) {
- throw new InvalidParameterValueException("Unable to find IP address " + ipAddress);
- }
-
- Account addrOwner = _accountDao.findById(ipAddressVO.getAccountId());
-
- // if an admin account was passed in, or no account was passed in, make sure we honor the accountName/domainId parameters
- if ((account != null) && isAdmin(account.getType())) {
- if (ipAddressVO.getAccountId() != null) {
- if ((addrOwner != null) && !_domainDao.isChildDomain(account.getDomainId(), addrOwner.getDomainId())) {
- throw new PermissionDeniedException("Unable to list port forwarding rules for address " + ipAddress + ", permission denied for account " + account.getId());
- }
- }
- } else {
- if (account != null) {
- if ((ipAddressVO.getAccountId() == null) || (account.getId() != ipAddressVO.getAccountId().longValue())) {
- throw new PermissionDeniedException("Unable to list port forwarding rules for address " + ipAddress + ", permission denied for account " + account.getId());
- }
- }
- }
-
- return _rulesDao.listIPForwarding(cmd.getIpAddress(), true);
- }
-
- @Override @DB
- public boolean assignToLoadBalancer(AssignToLoadBalancerRuleCmd cmd) throws NetworkRuleConflictException {
- Long loadBalancerId = cmd.getLoadBalancerId();
- Long instanceIdParam = cmd.getVirtualMachineId();
- List instanceIds = cmd.getVirtualMachineIds();
-
- if ((instanceIdParam == null) && (instanceIds == null)) {
- throw new InvalidParameterValueException("Unable to assign to load balancer " + loadBalancerId + ", no instance id is specified.");
- }
-
- if ((instanceIds == null) && (instanceIdParam != null)) {
- instanceIds = new ArrayList();
- instanceIds.add(instanceIdParam);
- }
-
- // FIXME: We should probably lock the load balancer here to prevent multiple updates...
- LoadBalancerVO loadBalancer = _loadBalancerDao.findById(loadBalancerId);
- if (loadBalancer == null) {
- throw new InvalidParameterValueException("Failed to assign to load balancer " + loadBalancerId + ", the load balancer was not found.");
- }
-
-
- // Permission check...
- Account account = UserContext.current().getAccount();
- if (account != null) {
- if (account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) {
- if (!_domainDao.isChildDomain(account.getDomainId(), loadBalancer.getDomainId())) {
- throw new PermissionDeniedException("Failed to assign to load balancer " + loadBalancerId + ", permission denied.");
- }
- } else if (account.getType() != Account.ACCOUNT_TYPE_ADMIN && account.getId() != loadBalancer.getAccountId()) {
- throw new PermissionDeniedException("Failed to assign to load balancer " + loadBalancerId + ", permission denied.");
- }
- }
-
- Transaction txn = Transaction.currentTxn();
- List firewallRulesToApply = new ArrayList();
- long accountId = 0;
- DomainRouterVO router = null;
-
- List mappedInstances = _loadBalancerVMMapDao.listByLoadBalancerId(loadBalancerId, false);
- Set mappedInstanceIds = new HashSet();
- if (mappedInstances != null) {
- for (LoadBalancerVMMapVO mappedInstance : mappedInstances) {
- mappedInstanceIds.add(Long.valueOf(mappedInstance.getInstanceId()));
- }
- }
-
- List finalInstanceIds = new ArrayList();
- for (Long instanceId : instanceIds) {
- if (mappedInstanceIds.contains(instanceId)) {
- continue;
- } else {
- finalInstanceIds.add(instanceId);
- }
-
- UserVmVO userVm = _vmDao.findById(instanceId);
- if (userVm == null) {
- s_logger.warn("Unable to find virtual machine with id " + instanceId);
- throw new InvalidParameterValueException("Unable to find virtual machine with id " + instanceId);
- } else {
- // sanity check that the vm can be applied to the load balancer
- ServiceOfferingVO offering = _serviceOfferingDao.findById(userVm.getServiceOfferingId());
- if ((offering == null) || !GuestIpType.Virtualized.equals(offering.getGuestIpType())) {
- // we previously added these instanceIds to the loadBalancerVMMap, so remove them here as we are rejecting the API request
- // without actually modifying the load balancer
- _loadBalancerVMMapDao.remove(loadBalancerId, instanceIds, Boolean.TRUE);
-
- if (s_logger.isDebugEnabled()) {
- s_logger.debug("Unable to add virtual machine " + userVm.toString() + " to load balancer " + loadBalancerId + ", bad network type (" + ((offering == null) ? "null" : offering.getGuestIpType()) + ")");
- }
-
- throw new InvalidParameterValueException("Unable to add virtual machine " + userVm.toString() + " to load balancer " + loadBalancerId + ", bad network type (" + ((offering == null) ? "null" : offering.getGuestIpType()) + ")");
- }
- }
-
- if (accountId == 0) {
- accountId = userVm.getAccountId();
- } else if (accountId != userVm.getAccountId()) {
- s_logger.warn("guest vm " + userVm.getHostName() + " (id:" + userVm.getId() + ") belongs to account " + userVm.getAccountId()
- + ", previous vm in list belongs to account " + accountId);
- throw new InvalidParameterValueException("guest vm " + userVm.getHostName() + " (id:" + userVm.getId() + ") belongs to account " + userVm.getAccountId()
- + ", previous vm in list belongs to account " + accountId);
- }
-
- DomainRouterVO nextRouter = null;
- if (userVm.getDomainRouterId() != null) {
- nextRouter = _routerMgr.getRouter(userVm.getDomainRouterId());
- }
- if (nextRouter == null) {
- s_logger.warn("Unable to find router (" + userVm.getDomainRouterId() + ") for virtual machine with id " + instanceId);
- throw new InvalidParameterValueException("Unable to find router (" + userVm.getDomainRouterId() + ") for virtual machine with id " + instanceId);
- }
-
- if (router == null) {
- router = nextRouter;
-
- // Make sure owner of router is owner of load balancer. Since we are already checking that all VMs belong to the same router, by checking router
- // ownership once we'll make sure all VMs belong to the owner of the load balancer.
- if (router.getAccountId() != loadBalancer.getAccountId()) {
- throw new InvalidParameterValueException("guest vm " + userVm.getHostName() + " (id:" + userVm.getId() + ") does not belong to the owner of load balancer " +
- loadBalancer.getName() + " (owner is account id " + loadBalancer.getAccountId() + ")");
- }
- } else if (router.getId() != nextRouter.getId()) {
- throw new InvalidParameterValueException("guest vm " + userVm.getHostName() + " (id:" + userVm.getId() + ") belongs to router " + nextRouter.getHostName()
- + ", previous vm in list belongs to router " + router.getHostName());
- }
-
- // check for ip address/port conflicts by checking exising forwarding and loadbalancing rules
- String ipAddress = loadBalancer.getIpAddress();
- String privateIpAddress = userVm.getGuestIpAddress();
- List existingRulesOnPubIp = _rulesDao.listIPForwarding(ipAddress);
-
- if (existingRulesOnPubIp != null) {
- for (FirewallRuleVO fwRule : existingRulesOnPubIp) {
- if (!( (fwRule.isForwarding() == false) &&
- (fwRule.getGroupId() != null) &&
- (fwRule.getGroupId() == loadBalancer.getId()) )) {
- // if the rule is not for the current load balancer, check to see if the private IP is our target IP,
- // in which case we have a conflict
- if (fwRule.getPublicPort().equals(loadBalancer.getPublicPort())) {
- throw new NetworkRuleConflictException("An existing port forwarding service rule for " + ipAddress + ":" + loadBalancer.getPublicPort()
- + " exists, found while trying to apply load balancer " + loadBalancer.getName() + " (id:" + loadBalancer.getId() + ") to instance "
- + userVm.getHostName() + ".");
- }
- } else if (fwRule.getPrivateIpAddress().equals(privateIpAddress) && fwRule.getPrivatePort().equals(loadBalancer.getPrivatePort()) && fwRule.isEnabled()) {
- // for the current load balancer, don't add the same instance to the load balancer more than once
- continue;
- }
- }
- }
-
- FirewallRuleVO newFwRule = new FirewallRuleVO();
- newFwRule.setAlgorithm(loadBalancer.getAlgorithm());
- newFwRule.setEnabled(true);
- newFwRule.setForwarding(false);
- newFwRule.setPrivatePort(loadBalancer.getPrivatePort());
- newFwRule.setPublicPort(loadBalancer.getPublicPort());
- newFwRule.setPublicIpAddress(loadBalancer.getIpAddress());
- newFwRule.setPrivateIpAddress(userVm.getGuestIpAddress());
- newFwRule.setGroupId(loadBalancer.getId());
-
- firewallRulesToApply.add(newFwRule);
- }
-
- // if there's no work to do, bail out early rather than reconfiguring the proxy with the existing rules
- if (firewallRulesToApply.isEmpty()) {
- return true;
- }
-
- //Sync on domR
- if(router == null){
- throw new InvalidParameterValueException("Failed to assign to load balancer " + loadBalancerId + ", the domain router was not found at " + loadBalancer.getIpAddress());
- }
- else{
- cmd.synchronizeCommand("Router", router.getId());
- }
-
- IPAddressVO ipAddr = _ipAddressDao.findById(loadBalancer.getIpAddress());
- List ipAddrs = listPublicIpAddressesInVirtualNetwork(accountId, ipAddr.getDataCenterId(), null);
- for (IPAddressVO ipv : ipAddrs) {
- List rules = _rulesDao.listIpForwardingRulesForLoadBalancers(ipv.getAddress());
- firewallRulesToApply.addAll(rules);
- }
-
- txn.start();
-
- List updatedRules = null;
- if (router.getState().equals(State.Starting)) {
- // Starting is a special case...if the router is starting that means the IP address hasn't yet been assigned to the domR and the update firewall rules script will fail.
- // In this case, just store the rules and they will be applied when the router state is resent (after the router is started).
- updatedRules = firewallRulesToApply;
- } else {
- updatedRules = updateFirewallRules(loadBalancer.getIpAddress(), firewallRulesToApply, router);
- }
-
- // Save and create the event
- String description;
- String type = EventTypes.EVENT_NET_RULE_ADD;
- String ruleName = "load balancer";
- String level = EventVO.LEVEL_INFO;
-
- LoadBalancerVO loadBalancerLock = null;
- try {
- loadBalancerLock = _loadBalancerDao.acquireInLockTable(loadBalancerId);
- if (loadBalancerLock == null) {
- s_logger.warn("assignToLoadBalancer: Failed to lock load balancer " + loadBalancerId + ", proceeding with updating loadBalancerVMMappings...");
- }
- if ((updatedRules != null) && (updatedRules.size() == firewallRulesToApply.size())) {
- // flag the instances as mapped to the load balancer
- for (Long addedInstanceId : finalInstanceIds) {
- LoadBalancerVMMapVO mappedVM = new LoadBalancerVMMapVO(loadBalancerId, addedInstanceId);
- _loadBalancerVMMapDao.persist(mappedVM);
- }
-
- /* We used to add these instances as pending when the API command is received on the server, and once they were applied,
- * the pending status was removed. In the 2.2 API framework, this is no longer done and instead the new mappings just
- * need to be persisted
- List pendingMappedVMs = _loadBalancerVMMapDao.listByLoadBalancerId(loadBalancerId, true);
- for (LoadBalancerVMMapVO pendingMappedVM : pendingMappedVMs) {
- if (instanceIds.contains(pendingMappedVM.getInstanceId())) {
- LoadBalancerVMMapVO pendingMappedVMForUpdate = _loadBalancerVMMapDao.createForUpdate();
- pendingMappedVMForUpdate.setPending(false);
- _loadBalancerVMMapDao.update(pendingMappedVM.getId(), pendingMappedVMForUpdate);
- }
- }
- */
-
- for (FirewallRuleVO updatedRule : updatedRules) {
- _rulesDao.persist(updatedRule);
-
- description = "created new " + ruleName + " rule [" + updatedRule.getPublicIpAddress() + ":"
- + updatedRule.getPublicPort() + "]->[" + updatedRule.getPrivateIpAddress() + ":"
- + updatedRule.getPrivatePort() + "]" + " " + updatedRule.getProtocol();
-
- EventUtils.saveEvent(UserContext.current().getUserId(), loadBalancer.getAccountId(), level, type, description);
- }
- txn.commit();
- return true;
- } else {
- // Remove the instanceIds from the load balancer since there was a failure. Make sure to commit the
- // transaction here, otherwise the act of throwing the internal error exception will cause this
- // remove operation to be rolled back.
- _loadBalancerVMMapDao.remove(loadBalancerId, instanceIds, null);
- txn.commit();
-
- s_logger.warn("Failed to apply load balancer " + loadBalancer.getName() + " (id:" + loadBalancerId + ") to guest virtual machines " + StringUtils.join(instanceIds, ","));
- throw new CloudRuntimeException("Failed to apply load balancer " + loadBalancer.getName() + " (id:" + loadBalancerId + ") to guest virtual machine " + StringUtils.join(instanceIds, ","));
- }
- } finally {
- if (loadBalancerLock != null) {
- _loadBalancerDao.releaseFromLockTable(loadBalancerId);
- }
- }
- }
-
- @Override @DB
- public LoadBalancer createLoadBalancerRule(CreateLoadBalancerRuleCmd cmd) throws InvalidParameterValueException, PermissionDeniedException {
- String publicIp = cmd.getPublicIp();
-
- // make sure ip address exists
- IPAddressVO ipAddr = _ipAddressDao.findById(cmd.getPublicIp());
- if (ipAddr == null) {
- throw new InvalidParameterValueException("Unable to create load balancer rule, invalid IP address " + publicIp);
- }
-
- VlanVO vlan = _vlanDao.findById(ipAddr.getVlanDbId());
- if (vlan != null) {
- if (!VlanType.VirtualNetwork.equals(vlan.getVlanType())) {
- throw new InvalidParameterValueException("Unable to create load balancer rule for IP address " + publicIp + ", only VirtualNetwork type IP addresses can be used for load balancers.");
- }
- } // else ERROR?
-
- // Verify input parameters
- if ((ipAddr.getAccountId() == null) || (ipAddr.getAllocated() == null)) {
- throw new InvalidParameterValueException("Unable to create load balancer rule, cannot find account owner for ip " + publicIp);
- }
-
- Account account = UserContext.current().getAccount();
- if (account != null) {
- if ((account.getType() == Account.ACCOUNT_TYPE_ADMIN) || (account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN)) {
- if (!_domainDao.isChildDomain(account.getDomainId(), ipAddr.getDomainId())) {
- throw new PermissionDeniedException("Unable to create load balancer rule on IP address " + publicIp + ", permission denied.");
- }
- } else if (account.getId() != ipAddr.getAccountId().longValue()) {
- throw new PermissionDeniedException("Unable to create load balancer rule, account " + account.getAccountName() + " doesn't own ip address " + publicIp);
- }
- }
-
- String loadBalancerName = cmd.getLoadBalancerRuleName();
- LoadBalancerVO existingLB = _loadBalancerDao.findByAccountAndName(ipAddr.getAccountId(), loadBalancerName);
- if (existingLB != null) {
- throw new InvalidParameterValueException("Unable to create load balancer rule, an existing load balancer rule with name " + loadBalancerName + " already exists.");
- }
-
- // validate params
- String publicPort = cmd.getPublicPort();
- String privatePort = cmd.getPrivatePort();
- String algorithm = cmd.getAlgorithm();
-
- if (!NetUtils.isValidPort(publicPort)) {
- throw new InvalidParameterValueException("publicPort is an invalid value");
- }
- if (!NetUtils.isValidPort(privatePort)) {
- throw new InvalidParameterValueException("privatePort is an invalid value");
- }
- if ((algorithm == null) || !NetUtils.isValidAlgorithm(algorithm)) {
- throw new InvalidParameterValueException("Invalid algorithm");
- }
-
- boolean locked = false;
- try {
- LoadBalancerVO exitingLB = _loadBalancerDao.findByIpAddressAndPublicPort(publicIp, publicPort);
- if (exitingLB != null) {
- throw new InvalidParameterValueException("IP Address/public port already load balanced by an existing load balancer rule");
- }
-
- List existingFwRules = _rulesDao.listIPForwarding(publicIp, publicPort, true);
- if ((existingFwRules != null) && !existingFwRules.isEmpty()) {
- throw new InvalidParameterValueException("IP Address (" + publicIp + ") and port (" + publicPort + ") already in use");
- }
-
- ipAddr = _ipAddressDao.acquireInLockTable(publicIp);
- if (ipAddr == null) {
- throw new PermissionDeniedException("User does not own ip address " + publicIp);
- }
-
- locked = true;
-
- LoadBalancerVO loadBalancer = new LoadBalancerVO(loadBalancerName, cmd.getDescription(), ipAddr.getAccountId(), publicIp, publicPort, privatePort, algorithm);
- loadBalancer = _loadBalancerDao.persist(loadBalancer);
- Long id = loadBalancer.getId();
-
- // Save off information for the event that the security group was applied
- Long userId = UserContext.current().getUserId();
- if (userId == null) {
- userId = Long.valueOf(User.UID_SYSTEM);
- }
-
- EventVO event = new EventVO();
- event.setUserId(userId);
- event.setAccountId(ipAddr.getAccountId());
- event.setType(EventTypes.EVENT_LOAD_BALANCER_CREATE);
-
- if (id == null) {
- event.setDescription("Failed to create load balancer " + loadBalancer.getName() + " on ip address " + publicIp + "[" + publicPort + "->" + privatePort + "]");
- event.setLevel(EventVO.LEVEL_ERROR);
- } else {
- event.setDescription("Successfully created load balancer " + loadBalancer.getName() + " on ip address " + publicIp + "[" + publicPort + "->" + privatePort + "]");
- String params = "id="+loadBalancer.getId()+"\ndcId="+ipAddr.getDataCenterId();
- event.setParameters(params);
- event.setLevel(EventVO.LEVEL_INFO);
- }
- _eventDao.persist(event);
-
- return _loadBalancerDao.findById(id);
- } finally {
- if (locked) {
- _ipAddressDao.releaseFromLockTable(publicIp);
- }
- }
- }
-
@Override @DB
public boolean releasePublicIpAddress(long userId, final String ipAddress) {
- IPAddressVO ip = null;
- try {
- ip = _ipAddressDao.acquireInLockTable(ipAddress);
-
- if (ip == null) {
- s_logger.warn("Unable to find allocated ip: " + ipAddress);
- return false;
- }
-
- if(s_logger.isDebugEnabled()) {
- s_logger.debug("lock on ip " + ipAddress + " is acquired");
- }
-
- if (ip.getAllocated() == null) {
- s_logger.warn("ip: " + ipAddress + " is already released");
- return false;
- }
-
- if (s_logger.isDebugEnabled()) {
- s_logger.debug("Releasing ip " + ipAddress + "; sourceNat = " + ip.isSourceNat());
- }
-
- final List ipAddrs = new ArrayList();
- ipAddrs.add(ip.getAddress());
- final List firewallRules = _rulesDao.listIPForwardingForUpdate(ipAddress);
-
- if (s_logger.isDebugEnabled()) {
- s_logger.debug("Found firewall rules: " + firewallRules.size());
- }
-
- for (final FirewallRuleVO fw: firewallRules) {
- fw.setEnabled(false);
- }
-
- DomainRouterVO router = null;
- if (ip.isSourceNat()) {
- router = _routerMgr.getRouter(ipAddress);
- if (router != null) {
- if (router.getPublicIpAddress() != null) {
- return false;
- }
- }
- } else {
- router = _routerMgr.getRouter(ip.getAccountId(), ip.getDataCenterId());
- }
-
- // Now send the updates down to the domR (note: we still hold locks on address and firewall)
- updateFirewallRules(ipAddress, firewallRules, router);
-
- for (final FirewallRuleVO rule: firewallRules) {
- _rulesDao.remove(rule.getId());
-
- // Save and create the event
- String ruleName = (rule.isForwarding() ? "ip forwarding" : "load balancer");
- String description = "deleted " + ruleName + " rule [" + rule.getPublicIpAddress() + ":" + rule.getPublicPort()
- + "]->[" + rule.getPrivateIpAddress() + ":" + rule.getPrivatePort() + "]" + " "
- + rule.getProtocol();
-
- // save off an event for removing the network rule
- EventVO event = new EventVO();
- event.setUserId(userId);
- event.setAccountId(ip.getAccountId());
- event.setType(EventTypes.EVENT_NET_RULE_DELETE);
- event.setDescription(description);
- event.setLevel(EventVO.LEVEL_INFO);
- _eventDao.persist(event);
- }
-
- List loadBalancers = _loadBalancerDao.listByIpAddress(ipAddress);
- for (LoadBalancerVO loadBalancer : loadBalancers) {
- _loadBalancerDao.remove(loadBalancer.getId());
-
- // save off an event for removing the load balancer
- EventVO event = new EventVO();
- event.setUserId(userId);
- event.setAccountId(ip.getAccountId());
- event.setType(EventTypes.EVENT_LOAD_BALANCER_DELETE);
- String params = "id="+loadBalancer.getId();
- event.setParameters(params);
- event.setDescription("Successfully deleted load balancer " + loadBalancer.getId());
- event.setLevel(EventVO.LEVEL_INFO);
- _eventDao.persist(event);
- }
-
- if ((router != null) && (router.getState() == State.Running)) {
- if (s_logger.isDebugEnabled()) {
- s_logger.debug("Disassociate ip " + router.getHostName());
- }
-
- if (associateIP(router, ip.getAddress(), false, 0)) {
- _ipAddressDao.unassignIpAddress(ipAddress);
- } else {
- if (s_logger.isDebugEnabled()) {
- s_logger.debug("Unable to dissociate IP : " + ipAddress + " due to failing to dissociate with router: " + router.getHostName());
- }
-
- final EventVO event = new EventVO();
- event.setUserId(userId);
- event.setAccountId(ip.getAccountId());
- event.setType(EventTypes.EVENT_NET_IP_RELEASE);
- event.setLevel(EventVO.LEVEL_ERROR);
- event.setParameters("address=" + ipAddress + "\nsourceNat="+ip.isSourceNat());
- event.setDescription("failed to released a public ip: " + ipAddress + " due to failure to disassociate with router " + router.getHostName());
- _eventDao.persist(event);
-
- return false;
- }
- } else {
- _ipAddressDao.unassignIpAddress(ipAddress);
- }
- s_logger.debug("released a public ip: " + ipAddress);
- final EventVO event = new EventVO();
- event.setUserId(userId);
- event.setAccountId(ip.getAccountId());
- event.setType(EventTypes.EVENT_NET_IP_RELEASE);
- event.setParameters("address=" + ipAddress + "\nsourceNat="+ip.isSourceNat());
- event.setDescription("released a public ip: " + ipAddress);
- _eventDao.persist(event);
-
- return true;
- } catch (final Throwable e) {
- s_logger.warn("ManagementServer error", e);
- return false;
- } finally {
- if(ip != null) {
- if(s_logger.isDebugEnabled()) {
- s_logger.debug("Releasing lock on ip " + ipAddress);
- }
- _ipAddressDao.releaseFromLockTable(ipAddress);
- }
- }
+ return false; // FIXME
+// IPAddressVO ip = null;
+// try {
+// ip = _ipAddressDao.acquireInLockTable(ipAddress);
+//
+// if (ip == null) {
+// s_logger.warn("Unable to find allocated ip: " + ipAddress);
+// return false;
+// }
+//
+// if(s_logger.isDebugEnabled()) {
+// s_logger.debug("lock on ip " + ipAddress + " is acquired");
+// }
+//
+// if (ip.getAllocated() == null) {
+// s_logger.warn("ip: " + ipAddress + " is already released");
+// return false;
+// }
+//
+// if (s_logger.isDebugEnabled()) {
+// s_logger.debug("Releasing ip " + ipAddress + "; sourceNat = " + ip.isSourceNat());
+// }
+//
+//
+// final List ipAddrs = new ArrayList();
+// ipAddrs.add(ip.getAddress());
+// final List firewallRules = _rulesDao.listIPForwardingForUpdate(ipAddress);
+//
+// if (s_logger.isDebugEnabled()) {
+// s_logger.debug("Found firewall rules: " + firewallRules.size());
+// }
+//
+// for (final PortForwardingRuleVO fw: firewallRules) {
+// fw.setEnabled(false);
+// }
+//
+// DomainRouterVO router = null;
+// if (ip.isSourceNat()) {
+// router = _routerMgr.getRouter(ipAddress);
+// if (router != null) {
+// if (router.getPublicIpAddress() != null) {
+// return false;
+// }
+// }
+// } else {
+// router = _routerMgr.getRouter(ip.getAccountId(), ip.getDataCenterId());
+// }
+//
+// // Now send the updates down to the domR (note: we still hold locks on address and firewall)
+// updateFirewallRules(ipAddress, firewallRules, router);
+//
+// for (final PortForwardingRuleVO rule: firewallRules) {
+// _rulesDao.remove(rule.getId());
+//
+// // Save and create the event
+// String ruleName = (rule.isForwarding() ? "ip forwarding" : "load balancer");
+// String description = "deleted " + ruleName + " rule [" + rule.getSourceIpAddress() + ":" + rule.getSourcePort()
+// + "]->[" + rule.getDestinationIpAddress() + ":" + rule.getDestinationPort() + "]" + " "
+// + rule.getProtocol();
+//
+// // save off an event for removing the network rule
+// EventVO event = new EventVO();
+// event.setUserId(userId);
+// event.setAccountId(ip.getAccountId());
+// event.setType(EventTypes.EVENT_NET_RULE_DELETE);
+// event.setDescription(description);
+// event.setLevel(EventVO.LEVEL_INFO);
+// _eventDao.persist(event);
+// }
+//
+// List loadBalancers = _loadBalancerDao.listByIpAddress(ipAddress);
+// for (LoadBalancerVO loadBalancer : loadBalancers) {
+// _loadBalancerDao.remove(loadBalancer.getId());
+//
+// // save off an event for removing the load balancer
+// EventVO event = new EventVO();
+// event.setUserId(userId);
+// event.setAccountId(ip.getAccountId());
+// event.setType(EventTypes.EVENT_LOAD_BALANCER_DELETE);
+// String params = "id="+loadBalancer.getId();
+// event.setParameters(params);
+// event.setDescription("Successfully deleted load balancer " + loadBalancer.getId());
+// event.setLevel(EventVO.LEVEL_INFO);
+// _eventDao.persist(event);
+// }
+//
+// if ((router != null) && (router.getState() == State.Running)) {
+// if (s_logger.isDebugEnabled()) {
+// s_logger.debug("Disassociate ip " + router.getHostName());
+// }
+//
+// if (associateIP(router, ip.getAddress(), false, 0)) {
+// _ipAddressDao.unassignIpAddress(ipAddress);
+// } else {
+// if (s_logger.isDebugEnabled()) {
+// s_logger.debug("Unable to dissociate IP : " + ipAddress + " due to failing to dissociate with router: " + router.getHostName());
+// }
+//
+// final EventVO event = new EventVO();
+// event.setUserId(userId);
+// event.setAccountId(ip.getAccountId());
+// event.setType(EventTypes.EVENT_NET_IP_RELEASE);
+// event.setLevel(EventVO.LEVEL_ERROR);
+// event.setParameters("address=" + ipAddress + "\nsourceNat="+ip.isSourceNat());
+// event.setDescription("failed to released a public ip: " + ipAddress + " due to failure to disassociate with router " + router.getHostName());
+// _eventDao.persist(event);
+//
+// return false;
+// }
+// } else {
+// _ipAddressDao.unassignIpAddress(ipAddress);
+// }
+// s_logger.debug("released a public ip: " + ipAddress);
+// final EventVO event = new EventVO();
+// event.setUserId(userId);
+// event.setAccountId(ip.getAccountId());
+// event.setType(EventTypes.EVENT_NET_IP_RELEASE);
+// event.setParameters("address=" + ipAddress + "\nsourceNat="+ip.isSourceNat());
+// event.setDescription("released a public ip: " + ipAddress);
+// _eventDao.persist(event);
+//
+// return true;
+// } catch (final Throwable e) {
+// s_logger.warn("ManagementServer error", e);
+// return false;
+// } finally {
+// if(ip != null) {
+// if(s_logger.isDebugEnabled()) {
+// s_logger.debug("Releasing lock on ip " + ipAddress);
+// }
+// _ipAddressDao.releaseFromLockTable(ipAddress);
+// }
+// }
}
@Override
@@ -1639,29 +952,6 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
return _routerMgr.getRouters(hostId);
}
- @Override
- public boolean updateLoadBalancerRules(final List fwRules, final DomainRouterVO router, Long hostId) {
-
- for (FirewallRuleVO rule : fwRules) {
- // Determine the the VLAN ID and netmask of the rule's public IP address
- IPAddressVO ip = _ipAddressDao.findById(rule.getPublicIpAddress());
- VlanVO vlan = _vlanDao.findById(new Long(ip.getVlanDbId()));
- String vlanNetmask = vlan.getVlanNetmask();
-
- rule.setVlanNetmask(vlanNetmask);
- }
-
- final LoadBalancerConfigurator cfgrtr = new HAProxyConfigurator();
- final String [] cfg = cfgrtr.generateConfiguration(fwRules);
- final String [][] addRemoveRules = cfgrtr.generateFwRules(fwRules);
- final LoadBalancerCfgCommand cmd = new LoadBalancerCfgCommand(cfg, addRemoveRules, router.getInstanceName(), router.getPrivateIpAddress());
- final Answer ans = _agentMgr.easySend(hostId, cmd);
- if (ans == null) {
- return false;
- } else {
- return ans.getResult();
- }
- }
private Integer getIntegerConfigValue(String configKey, Integer dflt) {
String value = _configs.get(configKey);
@@ -2122,320 +1412,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
return _nicDao.listBy(vm.getId());
}
- @Override @DB
- public boolean removeFromLoadBalancer(RemoveFromLoadBalancerRuleCmd cmd) throws InvalidParameterValueException {
- Long userId = UserContext.current().getUserId();
- Account account = UserContext.current().getAccount();
- Long loadBalancerId = cmd.getId();
- Long vmInstanceId = cmd.getVirtualMachineId();
- List instanceIds = cmd.getVirtualMachineIds();
-
- if ((vmInstanceId == null) && (instanceIds == null)) {
- throw new ServerApiException(BaseCmd.PARAM_ERROR, "No virtual machine id specified.");
- }
-
- // if a single instanceId was given, add it to the list so we can always just process the list if instanceIds
- if (instanceIds == null) {
- instanceIds = new ArrayList();
- instanceIds.add(vmInstanceId);
- }
-
- if (userId == null) {
- userId = Long.valueOf(1);
- }
-
- LoadBalancerVO loadBalancer = _loadBalancerDao.findById(Long.valueOf(loadBalancerId));
-
- if (loadBalancer == null) {
- throw new ServerApiException(BaseCmd.PARAM_ERROR, "Unable to find load balancer rule with id " + loadBalancerId);
- } else if (account != null) {
- if (!isAdmin(account.getType()) && (loadBalancer.getAccountId() != account.getId())) {
- throw new ServerApiException(BaseCmd.PARAM_ERROR, "Account " + account.getAccountName() + " does not own load balancer rule " + loadBalancer.getName() +
- " (id:" + loadBalancer.getId() + ")");
- } else if (!_domainDao.isChildDomain(account.getDomainId(), loadBalancer.getDomainId())) {
- throw new ServerApiException(BaseCmd.PARAM_ERROR, "Invalid load balancer rule id (" + loadBalancer.getId() + ") given, unable to remove virtual machine instances.");
- }
- }
-
- Transaction txn = Transaction.currentTxn();
- LoadBalancerVO loadBalancerLock = null;
- boolean success = true;
- try {
-
- IPAddressVO ipAddress = _ipAddressDao.findById(loadBalancer.getIpAddress());
- if (ipAddress == null) {
- return false;
- }
-
- DomainRouterVO router = _routerMgr.getRouter(ipAddress.getAccountId(), ipAddress.getDataCenterId());
- if (router == null) {
- return false;
- }
-
- txn.start();
- for (Long instanceId : instanceIds) {
- UserVm userVm = _userVmDao.findById(instanceId);
- if (userVm == null) {
- s_logger.warn("Unable to find virtual machine with id " + instanceId);
- throw new InvalidParameterValueException("Unable to find virtual machine with id " + instanceId);
- }
- FirewallRuleVO fwRule = _rulesDao.findByGroupAndPrivateIp(loadBalancerId, userVm.getGuestIpAddress(), false);
- if (fwRule != null) {
- fwRule.setEnabled(false);
- _rulesDao.update(fwRule.getId(), fwRule);
- }
- }
-
- List allLbRules = new ArrayList();
- IPAddressVO ipAddr = _ipAddressDao.findById(loadBalancer.getIpAddress());
- List ipAddrs = listPublicIpAddressesInVirtualNetwork(loadBalancer.getAccountId(), ipAddr.getDataCenterId(), null);
- for (IPAddressVO ipv : ipAddrs) {
- List rules = _rulesDao.listIPForwarding(ipv.getAddress(), false);
- allLbRules.addAll(rules);
- }
-
- updateFirewallRules(loadBalancer.getIpAddress(), allLbRules, router);
-
- // firewall rules are updated, lock the load balancer as mappings are updated
- loadBalancerLock = _loadBalancerDao.acquireInLockTable(loadBalancerId);
- if (loadBalancerLock == null) {
- s_logger.warn("removeFromLoadBalancer: failed to lock load balancer " + loadBalancerId + ", deleting mappings anyway...");
- }
-
- // remove all the loadBalancer->VM mappings
- _loadBalancerVMMapDao.remove(loadBalancerId, instanceIds, Boolean.FALSE);
-
- // Save and create the event
- String description;
- String type = EventTypes.EVENT_NET_RULE_DELETE;
- String level = EventVO.LEVEL_INFO;
-
- for (FirewallRuleVO updatedRule : allLbRules) {
- if (!updatedRule.isEnabled()) {
- _rulesDao.remove(updatedRule.getId());
-
- description = "deleted load balancer rule [" + updatedRule.getPublicIpAddress() + ":" + updatedRule.getPublicPort() + "]->["
- + updatedRule.getPrivateIpAddress() + ":" + updatedRule.getPrivatePort() + "]" + " " + updatedRule.getProtocol();
-
- EventUtils.saveEvent(userId, loadBalancer.getAccountId(), level, type, description);
- }
- }
- txn.commit();
- } catch (Exception ex) {
- s_logger.warn("Failed to delete load balancing rule with exception: ", ex);
- success = false;
- txn.rollback();
- } finally {
- if (loadBalancerLock != null) {
- _loadBalancerDao.releaseFromLockTable(loadBalancerId);
- }
- }
- return success;
- }
-
- @Override @DB
- public boolean deleteLoadBalancerRule(DeleteLoadBalancerRuleCmd cmd) throws InvalidParameterValueException, PermissionDeniedException{
- Long loadBalancerId = cmd.getId();
- Long userId = UserContext.current().getUserId();
- Account account = UserContext.current().getAccount();
-
- ///verify input parameters
- LoadBalancerVO loadBalancer = _loadBalancerDao.findById(loadBalancerId);
- if (loadBalancer == null) {
- throw new InvalidParameterValueException ("Unable to find load balancer rule with id " + loadBalancerId);
- }
-
- if (account != null) {
- if (!isAdmin(account.getType())) {
- if (loadBalancer.getAccountId() != account.getId()) {
- throw new PermissionDeniedException("Account " + account.getAccountName() + " does not own load balancer rule " + loadBalancer.getName() + " (id:" + loadBalancerId + "), permission denied");
- }
- } else if (!_domainDao.isChildDomain(account.getDomainId(), loadBalancer.getDomainId())) {
- throw new PermissionDeniedException("Unable to delete load balancer rule " + loadBalancer.getName() + " (id:" + loadBalancerId + "), permission denied.");
- }
- }
-
- if (userId == null) {
- userId = Long.valueOf(1);
- }
-
- Transaction txn = Transaction.currentTxn();
- LoadBalancerVO loadBalancerLock = null;
- try {
-
- IPAddressVO ipAddress = _ipAddressDao.findById(loadBalancer.getIpAddress());
- if (ipAddress == null) {
- return false;
- }
-
- DomainRouterVO router = _routerMgr.getRouter(ipAddress.getAccountId(), ipAddress.getDataCenterId());
- List fwRules = _firewallRulesDao.listByLoadBalancerId(loadBalancerId);
-
- txn.start();
-
- if ((fwRules != null) && !fwRules.isEmpty()) {
- for (FirewallRuleVO fwRule : fwRules) {
- fwRule.setEnabled(false);
- _firewallRulesDao.update(fwRule.getId(), fwRule);
- }
-
- List allLbRules = new ArrayList();
- List ipAddrs = listPublicIpAddressesInVirtualNetwork(loadBalancer.getAccountId(), ipAddress.getDataCenterId(), null);
- for (IPAddressVO ipv : ipAddrs) {
- List rules = _firewallRulesDao.listIPForwarding(ipv.getAddress(), false);
- allLbRules.addAll(rules);
- }
-
- updateFirewallRules(loadBalancer.getIpAddress(), allLbRules, router);
-
- // firewall rules are updated, lock the load balancer as the mappings are updated
- loadBalancerLock = _loadBalancerDao.acquireInLockTable(loadBalancerId);
- if (loadBalancerLock == null) {
- s_logger.warn("deleteLoadBalancer: failed to lock load balancer " + loadBalancerId + ", deleting mappings anyway...");
- }
-
- // remove all loadBalancer->VM mappings
- List lbVmMap = _loadBalancerVMMapDao.listByLoadBalancerId(loadBalancerId);
- if (lbVmMap != null && !lbVmMap.isEmpty()) {
- for (LoadBalancerVMMapVO lb : lbVmMap) {
- _loadBalancerVMMapDao.remove(lb.getId());
- }
- }
-
- // Save and create the event
- String description;
- String type = EventTypes.EVENT_NET_RULE_DELETE;
- String ruleName = "load balancer";
- String level = EventVO.LEVEL_INFO;
- Account accountOwner = _accountDao.findById(loadBalancer.getAccountId());
-
- for (FirewallRuleVO updatedRule : fwRules) {
- _firewallRulesDao.remove(updatedRule.getId());
-
- description = "deleted " + ruleName + " rule [" + updatedRule.getPublicIpAddress() + ":" + updatedRule.getPublicPort() + "]->["
- + updatedRule.getPrivateIpAddress() + ":" + updatedRule.getPrivatePort() + "]" + " " + updatedRule.getProtocol();
-
- EventUtils.saveEvent(userId, accountOwner.getId(), level, type, description);
- }
- }
-
- txn.commit();
- } catch (Exception ex) {
- txn.rollback();
- s_logger.error("Unexpected exception deleting load balancer " + loadBalancerId, ex);
- return false;
- } finally {
- if (loadBalancerLock != null) {
- _loadBalancerDao.releaseFromLockTable(loadBalancerId);
- }
- }
-
- boolean success = _loadBalancerDao.remove(loadBalancerId);
-
- // save off an event for removing the load balancer
- EventVO event = new EventVO();
- event.setUserId(userId);
- event.setAccountId(loadBalancer.getAccountId());
- event.setType(EventTypes.EVENT_LOAD_BALANCER_DELETE);
- if (success) {
- event.setLevel(EventVO.LEVEL_INFO);
- String params = "id="+loadBalancer.getId();
- event.setParameters(params);
- event.setDescription("Successfully deleted load balancer " + loadBalancer.getName() + " (id:" + loadBalancer.getId() + ")");
- } else {
- event.setLevel(EventVO.LEVEL_ERROR);
- event.setDescription("Failed to delete load balancer " + loadBalancer.getName() + " (id:" + loadBalancer.getId() + ")");
- }
- _eventDao.persist(event);
- return success;
- }
-
-
- @Override @DB
- public LoadBalancerVO updateLoadBalancerRule(UpdateLoadBalancerRuleCmd cmd) throws InvalidParameterValueException, PermissionDeniedException{
- Long loadBalancerId = cmd.getId();
- String privatePort = cmd.getPrivatePort();
- String algorithm = cmd.getAlgorithm();
- String name = cmd.getLoadBalancerName();
- String description = cmd.getDescription();
- Account account = UserContext.current().getAccount();
-
- //Verify input parameters
- LoadBalancerVO loadBalancer = _loadBalancerDao.findById(loadBalancerId);
- if (loadBalancer == null) {
- throw new InvalidParameterValueException("Unable to find load balancer rule " + loadBalancerId + " for update.");
- }
-
- // make sure the name's not already in use
- if (name != null) {
- LoadBalancerVO existingLB = _loadBalancerDao.findByAccountAndName(loadBalancer.getAccountId(), name);
- if ((existingLB != null) && (existingLB.getId() != loadBalancer.getId())) {
- throw new InvalidParameterValueException("Unable to update load balancer " + loadBalancer.getName() + " with new name " + name + ", the name is already in use.");
- }
- }
-
- Account lbOwner = _accountDao.findById(loadBalancer.getAccountId());
- if (lbOwner == null) {
- throw new InvalidParameterValueException("Unable to update load balancer rule, cannot find owning account");
- }
-
- Long accountId = lbOwner.getId();
- if (account != null) {
- if (!isAdmin(account.getType())) {
- if (account.getId() != accountId.longValue()) {
- throw new PermissionDeniedException("Unable to update load balancer rule, permission denied");
- }
- } else if (!_domainDao.isChildDomain(account.getDomainId(), lbOwner.getDomainId())) {
- throw new PermissionDeniedException("Unable to update load balancer rule, permission denied.");
- }
- }
-
- String updatedPrivatePort = ((privatePort == null) ? loadBalancer.getPrivatePort() : privatePort);
- String updatedAlgorithm = ((algorithm == null) ? loadBalancer.getAlgorithm() : algorithm);
- String updatedName = ((name == null) ? loadBalancer.getName() : name);
- String updatedDescription = ((description == null) ? loadBalancer.getDescription() : description);
-
- Transaction txn = Transaction.currentTxn();
- try {
- txn.start();
- loadBalancer.setPrivatePort(updatedPrivatePort);
- loadBalancer.setAlgorithm(updatedAlgorithm);
- loadBalancer.setName(updatedName);
- loadBalancer.setDescription(updatedDescription);
- _loadBalancerDao.update(loadBalancer.getId(), loadBalancer);
-
- List fwRules = _firewallRulesDao.listByLoadBalancerId(loadBalancer.getId());
- if ((fwRules != null) && !fwRules.isEmpty()) {
- for (FirewallRuleVO fwRule : fwRules) {
- fwRule.setPrivatePort(updatedPrivatePort);
- fwRule.setAlgorithm(updatedAlgorithm);
- _firewallRulesDao.update(fwRule.getId(), fwRule);
- }
- }
- txn.commit();
- } catch (RuntimeException ex) {
- s_logger.warn("Unhandled exception trying to update load balancer rule", ex);
- txn.rollback();
- throw ex;
- } finally {
- txn.close();
- }
-
- // now that the load balancer has been updated, reconfigure the HA Proxy on the router with all the LB rules
- List allLbRules = new ArrayList();
- IPAddressVO ipAddress = _ipAddressDao.findById(loadBalancer.getIpAddress());
- List ipAddrs = listPublicIpAddressesInVirtualNetwork(loadBalancer.getAccountId(), ipAddress.getDataCenterId(), null);
- for (IPAddressVO ipv : ipAddrs) {
- List rules = _firewallRulesDao.listIPForwarding(ipv.getAddress(), false);
- allLbRules.addAll(rules);
- }
-
- IPAddressVO ip = _ipAddressDao.findById(loadBalancer.getIpAddress());
- DomainRouterVO router = _routerMgr.getRouter(ip.getAccountId(), ip.getDataCenterId());
- updateFirewallRules(loadBalancer.getIpAddress(), allLbRules, router);
- return _loadBalancerDao.findById(loadBalancer.getId());
- }
public static boolean isAdmin(short accountType) {
return ((accountType == Account.ACCOUNT_TYPE_ADMIN) ||
@@ -2544,121 +1521,6 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
}
}
- @Override @DB
- public boolean deletePortForwardingRule(Long id, boolean sysContext) {
- Long ruleId = id;
- Long userId = null;
- Account account = null;
- if(sysContext){
- userId = User.UID_SYSTEM;
- account = _accountDao.findById(User.UID_SYSTEM);
- }else{
- userId = UserContext.current().getUserId();
- account = UserContext.current().getAccount();
- }
-
-
- //verify input parameters here
- FirewallRuleVO rule = _firewallRulesDao.findById(ruleId);
- if (rule == null) {
- throw new InvalidParameterValueException("Unable to find port forwarding rule " + ruleId);
- }
-
- String publicIp = rule.getPublicIpAddress();
- String privateIp = rule.getPrivateIpAddress();
-
- IPAddressVO ipAddress = _ipAddressDao.findById(publicIp);
- if (ipAddress == null) {
- throw new InvalidParameterValueException("Unable to find IP address for port forwarding rule " + ruleId);
- }
-
- // although we are not writing these values to the DB, we will check
- // them out of an abundance
- // of caution (may not be warranted)
- String privatePort = rule.getPrivatePort();
- String publicPort = rule.getPublicPort();
- if (!NetUtils.isValidPort(publicPort) || !NetUtils.isValidPort(privatePort)) {
- throw new InvalidParameterValueException("Invalid value for port");
- }
-
- String proto = rule.getProtocol();
- if (!NetUtils.isValidProto(proto)) {
- throw new InvalidParameterValueException("Invalid protocol");
- }
-
- Account ruleOwner = _accountDao.findById(ipAddress.getAccountId());
- if (ruleOwner == null) {
- throw new InvalidParameterValueException("Unable to find owning account for port forwarding rule " + ruleId);
- }
-
- // 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(), ruleOwner.getDomainId())) {
- throw new PermissionDeniedException("Unable to delete port forwarding rule " + ruleId + ", permission denied.");
- }
- } else if (account.getId() != ruleOwner.getId()) {
- throw new PermissionDeniedException("Unable to delete port forwarding rule " + ruleId + ", permission denied.");
- }
- }
-
- Transaction txn = Transaction.currentTxn();
- boolean locked = false;
- boolean success = false;
- try {
-
- IPAddressVO ipVO = _ipAddressDao.acquireInLockTable(publicIp);
- if (ipVO == null) {
- // throw this exception because hackers can use the api to probe for allocated ips
- throw new PermissionDeniedException("User does not own supplied address");
- }
-
- locked = true;
- txn.start();
- List fwdings = _firewallRulesDao.listIPForwardingForUpdate(publicIp, publicPort, proto);
- FirewallRuleVO fwRule = null;
- if (fwdings.size() == 0) {
- throw new InvalidParameterValueException("No such rule");
- } else if (fwdings.size() == 1) {
- fwRule = fwdings.get(0);
- if (fwRule.getPrivateIpAddress().equalsIgnoreCase(privateIp) && fwRule.getPrivatePort().equals(privatePort)) {
- _firewallRulesDao.expunge(fwRule.getId());
- } else {
- throw new InvalidParameterValueException("No such rule");
- }
- } else {
- throw new CloudRuntimeException("Multiple matches. Please contact support");
- }
- fwRule.setEnabled(false);
- success = updateFirewallRule(fwRule, null, null);
-
- String description;
- String type = EventTypes.EVENT_NET_RULE_DELETE;
- String level = EventVO.LEVEL_INFO;
- String ruleName = rule.isForwarding() ? "ip forwarding" : "load balancer";
-
- if (success) {
- description = "deleted " + ruleName + " rule [" + publicIp + ":" + rule.getPublicPort() + "]->[" + rule.getPrivateIpAddress() + ":"
- + rule.getPrivatePort() + "] " + rule.getProtocol();
- } else {
- level = EventVO.LEVEL_ERROR;
- description = "Error while deleting " + ruleName + " rule [" + publicIp + ":" + rule.getPublicPort() + "]->[" + rule.getPrivateIpAddress() + ":"
- + rule.getPrivatePort() + "] " + rule.getProtocol();
- }
- EventUtils.saveEvent(userId, ipAddress.getAccountId(), level, type, description);
- txn.commit();
- }catch (Exception ex) {
- txn.rollback();
- s_logger.error("Unexpected exception deleting port forwarding rule " + ruleId, ex);
- return false;
- }finally {
- if (locked) {
- _ipAddressDao.releaseFromLockTable(publicIp);
- }
- txn.close();
- }
- return success;
- }
@Override
public List getAccountsUsingNetworkConfiguration(long configurationId) {
@@ -2698,124 +1560,125 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
@DB
public RemoteAccessVpnVO createRemoteAccessVpn(CreateRemoteAccessVpnCmd cmd)
throws InvalidParameterValueException, PermissionDeniedException, ConcurrentOperationException {
- String publicIp = cmd.getPublicIp();
- IPAddressVO ipAddr = null;
- Account account = getAccountForApiCommand(cmd.getAccountName(), cmd.getDomainId());
- if (publicIp == null) {
- List accountAddrs = _ipAddressDao.listByAccount(account.getId());
- for (IPAddressVO addr: accountAddrs){
- if (addr.getSourceNat() && addr.getDataCenterId() == cmd.getZoneId()){
- ipAddr = addr;
- publicIp = ipAddr.getAddress();
- break;
- }
- }
- if (ipAddr == null) {
- throw new InvalidParameterValueException("Account " + account.getAccountName() + " does not have any public ip addresses in zone " + cmd.getZoneId());
- }
- }
-
- // make sure ip address exists
- ipAddr = _ipAddressDao.findById(publicIp);
- if (ipAddr == null) {
- throw new InvalidParameterValueException("Unable to create remote access vpn, invalid public IP address " + publicIp);
- }
-
- VlanVO vlan = _vlanDao.findById(ipAddr.getVlanDbId());
- if (vlan != null) {
- if (!VlanType.VirtualNetwork.equals(vlan.getVlanType())) {
- throw new InvalidParameterValueException("Unable to create VPN for IP address " + publicIp + ", only VirtualNetwork type IP addresses can be used for VPN.");
- }
- }
- assert vlan != null:"Inconsistent DB state -- ip address does not belong to any vlan?";
-
- if ((ipAddr.getAccountId() == null) || (ipAddr.getAllocated() == null)) {
- throw new PermissionDeniedException("Unable to create VPN, permission denied for ip " + publicIp);
- }
-
- if (account != null) {
- if ((account.getType() == Account.ACCOUNT_TYPE_ADMIN) || (account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN)) {
- if (!_domainDao.isChildDomain(account.getDomainId(), ipAddr.getDomainId())) {
- throw new PermissionDeniedException("Unable to create VPN with public IP address " + publicIp + ", permission denied.");
- }
- } else if (account.getId() != ipAddr.getAccountId().longValue()) {
- throw new PermissionDeniedException("Unable to create VPN for account " + account.getAccountName() + " doesn't own ip address " + publicIp);
- }
- }
-
- RemoteAccessVpnVO vpnVO = _remoteAccessVpnDao.findByPublicIpAddress(publicIp);
- if (vpnVO != null) {
- throw new InvalidParameterValueException("A Remote Access VPN already exists for this public Ip address");
- }
- //TODO: assumes one virtual network / domr per account per zone
- vpnVO = _remoteAccessVpnDao.findByAccountAndZone(account.getId(), cmd.getZoneId());
- if (vpnVO != null) {
- throw new InvalidParameterValueException("A Remote Access VPN already exists for this account");
- }
- String ipRange = cmd.getIpRange();
- if (ipRange == null) {
- ipRange = _configs.get(Config.RemoteAccessVpnClientIpRange.key());
- }
- String [] range = ipRange.split("-");
- if (range.length != 2) {
- throw new InvalidParameterValueException("Invalid ip range");
- }
- if (!NetUtils.isValidIp(range[0]) || !NetUtils.isValidIp(range[1])){
- throw new InvalidParameterValueException("Invalid ip in range specification " + ipRange);
- }
- if (!NetUtils.validIpRange(range[0], range[1])){
- throw new InvalidParameterValueException("Invalid ip range " + ipRange);
- }
- String [] guestIpRange = getGuestIpRange();
- if (NetUtils.ipRangesOverlap(range[0], range[1], guestIpRange[0], guestIpRange[1])) {
- throw new InvalidParameterValueException("Invalid ip range: " + ipRange + " overlaps with guest ip range " + guestIpRange[0] + "-" + guestIpRange[1]);
- }
- //TODO: check sufficient range
- //TODO: check overlap with private and public ip ranges in datacenter
-
- long startIp = NetUtils.ip2Long(range[0]);
- String newIpRange = NetUtils.long2Ip(++startIp) + "-" + range[1];
- String sharedSecret = PasswordGenerator.generatePresharedKey(getIntegerConfigValue(Config.RemoteAccessVpnPskLength.key(), 24));
- Transaction txn = Transaction.currentTxn();
- txn.start();
- boolean locked = false;
- try {
- ipAddr = _ipAddressDao.acquireInLockTable(publicIp);
- if (ipAddr == null) {
- throw new ConcurrentOperationException("Another operation active, unable to create vpn");
- }
- locked = true;
- //check overlap with port forwarding rules on this ip (udp ports 500, 4500)
- List existing = _rulesDao.listIPForwardingByPortAndProto(publicIp, NetUtils.VPN_PORT, NetUtils.UDP_PROTO);
- if (!existing.isEmpty()) {
- throw new InvalidParameterValueException("UDP Port " + NetUtils.VPN_PORT + " is configured for destination NAT");
- }
- existing = _rulesDao.listIPForwardingByPortAndProto(publicIp, NetUtils.VPN_NATT_PORT, NetUtils.UDP_PROTO);
- if (!existing.isEmpty()) {
- throw new InvalidParameterValueException("UDP Port " + NetUtils.VPN_NATT_PORT + " is configured for destination NAT");
- }
- existing = _rulesDao.listIPForwardingByPortAndProto(publicIp, NetUtils.VPN_L2TP_PORT, NetUtils.UDP_PROTO);
- if (!existing.isEmpty()) {
- throw new InvalidParameterValueException("UDP Port " + NetUtils.VPN_L2TP_PORT + " is configured for destination NAT");
- }
- if (_rulesDao.isPublicIpOneToOneNATted(publicIp)) {
- throw new InvalidParameterValueException("Public Ip " + publicIp + " is configured for destination NAT");
- }
- vpnVO = new RemoteAccessVpnVO(account.getId(), cmd.getZoneId(), publicIp, range[0], newIpRange, sharedSecret);
- vpnVO = _remoteAccessVpnDao.persist(vpnVO);
- FirewallRuleVO rule = new FirewallRuleVO(null, publicIp, NetUtils.VPN_PORT, guestIpRange[0], NetUtils.VPN_PORT, true, NetUtils.UDP_PROTO, false, null);
- _rulesDao.persist(rule);
- rule = new FirewallRuleVO(null, publicIp, NetUtils.VPN_NATT_PORT, guestIpRange[0], NetUtils.VPN_NATT_PORT, true, NetUtils.UDP_PROTO, false, null);
- _rulesDao.persist(rule);
- rule = new FirewallRuleVO(null, publicIp, NetUtils.VPN_L2TP_PORT, guestIpRange[0], NetUtils.VPN_L2TP_PORT, true, NetUtils.UDP_PROTO, false, null);
- _rulesDao.persist(rule);
- txn.commit();
- return vpnVO;
- } finally {
- if (locked) {
- _ipAddressDao.releaseFromLockTable(publicIp);
- }
- }
+ return null;
+// String publicIp = cmd.getPublicIp();
+// IPAddressVO ipAddr = null;
+// Account account = getAccountForApiCommand(cmd.getAccountName(), cmd.getDomainId());
+// if (publicIp == null) {
+// List accountAddrs = _ipAddressDao.listByAccount(account.getId());
+// for (IPAddressVO addr: accountAddrs){
+// if (addr.getSourceNat() && addr.getDataCenterId() == cmd.getZoneId()){
+// ipAddr = addr;
+// publicIp = ipAddr.getAddress();
+// break;
+// }
+// }
+// if (ipAddr == null) {
+// throw new InvalidParameterValueException("Account " + account.getAccountName() + " does not have any public ip addresses in zone " + cmd.getZoneId());
+// }
+// }
+//
+// // make sure ip address exists
+// ipAddr = _ipAddressDao.findById(publicIp);
+// if (ipAddr == null) {
+// throw new InvalidParameterValueException("Unable to create remote access vpn, invalid public IP address " + publicIp);
+// }
+//
+// VlanVO vlan = _vlanDao.findById(ipAddr.getVlanDbId());
+// if (vlan != null) {
+// if (!VlanType.VirtualNetwork.equals(vlan.getVlanType())) {
+// throw new InvalidParameterValueException("Unable to create VPN for IP address " + publicIp + ", only VirtualNetwork type IP addresses can be used for VPN.");
+// }
+// }
+// assert vlan != null:"Inconsistent DB state -- ip address does not belong to any vlan?";
+//
+// if ((ipAddr.getAccountId() == null) || (ipAddr.getAllocated() == null)) {
+// throw new PermissionDeniedException("Unable to create VPN, permission denied for ip " + publicIp);
+// }
+//
+// if (account != null) {
+// if ((account.getType() == Account.ACCOUNT_TYPE_ADMIN) || (account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN)) {
+// if (!_domainDao.isChildDomain(account.getDomainId(), ipAddr.getDomainId())) {
+// throw new PermissionDeniedException("Unable to create VPN with public IP address " + publicIp + ", permission denied.");
+// }
+// } else if (account.getId() != ipAddr.getAccountId().longValue()) {
+// throw new PermissionDeniedException("Unable to create VPN for account " + account.getAccountName() + " doesn't own ip address " + publicIp);
+// }
+// }
+//
+// RemoteAccessVpnVO vpnVO = _remoteAccessVpnDao.findByPublicIpAddress(publicIp);
+// if (vpnVO != null) {
+// throw new InvalidParameterValueException("A Remote Access VPN already exists for this public Ip address");
+// }
+// //TODO: assumes one virtual network / domr per account per zone
+// vpnVO = _remoteAccessVpnDao.findByAccountAndZone(account.getId(), cmd.getZoneId());
+// if (vpnVO != null) {
+// throw new InvalidParameterValueException("A Remote Access VPN already exists for this account");
+// }
+// String ipRange = cmd.getIpRange();
+// if (ipRange == null) {
+// ipRange = _configs.get(Config.RemoteAccessVpnClientIpRange.key());
+// }
+// String [] range = ipRange.split("-");
+// if (range.length != 2) {
+// throw new InvalidParameterValueException("Invalid ip range");
+// }
+// if (!NetUtils.isValidIp(range[0]) || !NetUtils.isValidIp(range[1])){
+// throw new InvalidParameterValueException("Invalid ip in range specification " + ipRange);
+// }
+// if (!NetUtils.validIpRange(range[0], range[1])){
+// throw new InvalidParameterValueException("Invalid ip range " + ipRange);
+// }
+// String [] guestIpRange = getGuestIpRange();
+// if (NetUtils.ipRangesOverlap(range[0], range[1], guestIpRange[0], guestIpRange[1])) {
+// throw new InvalidParameterValueException("Invalid ip range: " + ipRange + " overlaps with guest ip range " + guestIpRange[0] + "-" + guestIpRange[1]);
+// }
+// //TODO: check sufficient range
+// //TODO: check overlap with private and public ip ranges in datacenter
+//
+// long startIp = NetUtils.ip2Long(range[0]);
+// String newIpRange = NetUtils.long2Ip(++startIp) + "-" + range[1];
+// String sharedSecret = PasswordGenerator.generatePresharedKey(getIntegerConfigValue(Config.RemoteAccessVpnPskLength.key(), 24));
+// Transaction txn = Transaction.currentTxn();
+// txn.start();
+// boolean locked = false;
+// try {
+// ipAddr = _ipAddressDao.acquireInLockTable(publicIp);
+// if (ipAddr == null) {
+// throw new ConcurrentOperationException("Another operation active, unable to create vpn");
+// }
+// locked = true;
+// //check overlap with port forwarding rules on this ip (udp ports 500, 4500)
+// List existing = _rulesDao.listIPForwardingByPortAndProto(publicIp, NetUtils.VPN_PORT, NetUtils.UDP_PROTO);
+// if (!existing.isEmpty()) {
+// throw new InvalidParameterValueException("UDP Port " + NetUtils.VPN_PORT + " is configured for destination NAT");
+// }
+// existing = _rulesDao.listIPForwardingByPortAndProto(publicIp, NetUtils.VPN_NATT_PORT, NetUtils.UDP_PROTO);
+// if (!existing.isEmpty()) {
+// throw new InvalidParameterValueException("UDP Port " + NetUtils.VPN_NATT_PORT + " is configured for destination NAT");
+// }
+// existing = _rulesDao.listIPForwardingByPortAndProto(publicIp, NetUtils.VPN_L2TP_PORT, NetUtils.UDP_PROTO);
+// if (!existing.isEmpty()) {
+// throw new InvalidParameterValueException("UDP Port " + NetUtils.VPN_L2TP_PORT + " is configured for destination NAT");
+// }
+// if (_rulesDao.isPublicIpOneToOneNATted(publicIp)) {
+// throw new InvalidParameterValueException("Public Ip " + publicIp + " is configured for destination NAT");
+// }
+// vpnVO = new RemoteAccessVpnVO(account.getId(), cmd.getZoneId(), publicIp, range[0], newIpRange, sharedSecret);
+// vpnVO = _remoteAccessVpnDao.persist(vpnVO);
+// PortForwardingRuleVO rule = new PortForwardingRuleVO(null, publicIp, NetUtils.VPN_PORT, guestIpRange[0], NetUtils.VPN_PORT, true, NetUtils.UDP_PROTO, false, null);
+// _rulesDao.persist(rule);
+// rule = new PortForwardingRuleVO(null, publicIp, NetUtils.VPN_NATT_PORT, guestIpRange[0], NetUtils.VPN_NATT_PORT, true, NetUtils.UDP_PROTO, false, null);
+// _rulesDao.persist(rule);
+// rule = new PortForwardingRuleVO(null, publicIp, NetUtils.VPN_L2TP_PORT, guestIpRange[0], NetUtils.VPN_L2TP_PORT, true, NetUtils.UDP_PROTO, false, null);
+// _rulesDao.persist(rule);
+// txn.commit();
+// return vpnVO;
+// } finally {
+// if (locked) {
+// _ipAddressDao.releaseFromLockTable(publicIp);
+// }
+// }
}
@Override
@@ -2859,44 +1722,45 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
@Override
@DB
public boolean destroyRemoteAccessVpn(DeleteRemoteAccessVpnCmd cmd) throws ConcurrentOperationException {
- Long userId = UserContext.current().getUserId();
- Account account = getAccountForApiCommand(cmd.getAccountName(), cmd.getDomainId());
- //TODO: assumes one virtual network / domr per account per zone
- RemoteAccessVpnVO vpnVO = _remoteAccessVpnDao.findByAccountAndZone(account.getId(), cmd.getZoneId());
- if (vpnVO == null) {
- throw new InvalidParameterValueException("No VPN found for account " + account.getAccountName() + " in zone " + cmd.getZoneId());
- }
- EventUtils.saveStartedEvent(userId, account.getId(), EventTypes.EVENT_REMOTE_ACCESS_VPN_DESTROY, "Deleting Remote Access VPN for account: " + account.getAccountName() + " in zone " + cmd.getZoneId(), cmd.getStartEventId());
- String publicIp = vpnVO.getVpnServerAddress();
- Long vpnId = vpnVO.getId();
- Transaction txn = Transaction.currentTxn();
- txn.start();
- boolean locked = false;
- boolean deleted = false;
- try {
- IPAddressVO ipAddr = _ipAddressDao.acquireInLockTable(publicIp);
- if (ipAddr == null) {
- throw new ConcurrentOperationException("Another operation active, unable to create vpn");
- }
- locked = true;
-
- deleted = _routerMgr.deleteRemoteAccessVpn(vpnVO);
- return deleted;
- } finally {
- if (deleted) {
- _remoteAccessVpnDao.remove(vpnId);
- _rulesDao.deleteIPForwardingByPublicIpAndPort(publicIp, NetUtils.VPN_PORT);
- _rulesDao.deleteIPForwardingByPublicIpAndPort(publicIp, NetUtils.VPN_NATT_PORT);
- _rulesDao.deleteIPForwardingByPublicIpAndPort(publicIp, NetUtils.VPN_L2TP_PORT);
- EventUtils.saveEvent(userId, account.getId(), EventTypes.EVENT_REMOTE_ACCESS_VPN_DESTROY, "Deleted Remote Access VPN for account: " + account.getAccountName() + " in zone " + cmd.getZoneId());
- } else {
- EventUtils.saveEvent(userId, account.getId(), EventVO.LEVEL_ERROR, EventTypes.EVENT_REMOTE_ACCESS_VPN_DESTROY, "Unable to delete Remote Access VPN ", account.getAccountName() + " in zone " + cmd.getZoneId());
- }
- txn.commit();
- if (locked) {
- _ipAddressDao.releaseFromLockTable(publicIp);
- }
- }
+// Long userId = UserContext.current().getUserId();
+// Account account = getAccountForApiCommand(cmd.getAccountName(), cmd.getDomainId());
+// //TODO: assumes one virtual network / domr per account per zone
+// RemoteAccessVpnVO vpnVO = _remoteAccessVpnDao.findByAccountAndZone(account.getId(), cmd.getZoneId());
+// if (vpnVO == null) {
+// throw new InvalidParameterValueException("No VPN found for account " + account.getAccountName() + " in zone " + cmd.getZoneId());
+// }
+// EventUtils.saveStartedEvent(userId, account.getId(), EventTypes.EVENT_REMOTE_ACCESS_VPN_DESTROY, "Deleting Remote Access VPN for account: " + account.getAccountName() + " in zone " + cmd.getZoneId(), cmd.getStartEventId());
+// String publicIp = vpnVO.getVpnServerAddress();
+// Long vpnId = vpnVO.getId();
+// Transaction txn = Transaction.currentTxn();
+// txn.start();
+// boolean locked = false;
+// boolean deleted = false;
+// try {
+// IPAddressVO ipAddr = _ipAddressDao.acquireInLockTable(publicIp);
+// if (ipAddr == null) {
+// throw new ConcurrentOperationException("Another operation active, unable to create vpn");
+// }
+// locked = true;
+//
+// deleted = _routerMgr.deleteRemoteAccessVpn(vpnVO);
+// return deleted;
+// } finally {
+// if (deleted) {
+// _remoteAccessVpnDao.remove(vpnId);
+// _rulesDao.deleteIPForwardingByPublicIpAndPort(publicIp, NetUtils.VPN_PORT);
+// _rulesDao.deleteIPForwardingByPublicIpAndPort(publicIp, NetUtils.VPN_NATT_PORT);
+// _rulesDao.deleteIPForwardingByPublicIpAndPort(publicIp, NetUtils.VPN_L2TP_PORT);
+// EventUtils.saveEvent(userId, account.getId(), EventTypes.EVENT_REMOTE_ACCESS_VPN_DESTROY, "Deleted Remote Access VPN for account: " + account.getAccountName() + " in zone " + cmd.getZoneId());
+// } else {
+// EventUtils.saveEvent(userId, account.getId(), EventVO.LEVEL_ERROR, EventTypes.EVENT_REMOTE_ACCESS_VPN_DESTROY, "Unable to delete Remote Access VPN ", account.getAccountName() + " in zone " + cmd.getZoneId());
+// }
+// txn.commit();
+// if (locked) {
+// _ipAddressDao.releaseFromLockTable(publicIp);
+// }
+// }
+ return false; // FIXME
}
@Override
@@ -3024,286 +1888,10 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
}
@Override @DB
- public Network getNetworkConfiguration(long id) {
+ public Network getNetwork(long id) {
return _networkConfigDao.findById(id);
}
- @Override @DB
- public FirewallRule createIpForwardingRuleOnDomr(long ruleId) {
- Transaction txn = Transaction.currentTxn();
- txn.start();
- boolean success = false;
- FirewallRuleVO rule = null;
- IPAddressVO ipAddress = null;
- boolean locked = false;
- try {
- //get the rule
- rule = _rulesDao.findById(ruleId);
-
- if(rule == null){
- throw new PermissionDeniedException("Cannot create ip forwarding rule in db");
- }
-
- //get ip address
- ipAddress = _ipAddressDao.findById(rule.getPublicIpAddress());
- if (ipAddress == null) {
- throw new InvalidParameterValueException("Unable to create ip forwarding rule on address " + ipAddress + ", invalid IP address specified.");
- }
-
- //sync point
- ipAddress = _ipAddressDao.acquireInLockTable(ipAddress.getAddress());
-
- if(ipAddress == null){
- s_logger.warn("Unable to acquire lock on ipAddress for creating static NAT rule");
- return rule;
- }else{
- locked = true;
- }
-
- //get the domain router object
- DomainRouterVO router = _routerMgr.getRouter(ipAddress.getAccountId(), ipAddress.getDataCenterId());
- success = createOrDeleteIpForwardingRuleOnDomr(rule,router,rule.getPrivateIpAddress(),true); //true +> create
-
- if(!success){
- //corner case; delete record from db as domR rule creation failed
- _rulesDao.remove(ruleId);
- throw new PermissionDeniedException("Cannot create ip forwarding rule on domr, hence deleting created record in db");
- }
-
- //update the user_ip_address record
- ipAddress.setOneToOneNat(true);
- _ipAddressDao.update(ipAddress.getAddress(),ipAddress);
-
- // Save and create the event
- String description;
- String ruleName = "ip forwarding";
- String level = EventVO.LEVEL_INFO;
-
- description = "created new " + ruleName + " rule [" + rule.getPublicIpAddress() + "]->["
- + rule.getPrivateIpAddress() + "]" + ":" + rule.getProtocol();
-
- EventUtils.saveEvent(UserContext.current().getUserId(), ipAddress.getAccountId(), level, EventTypes.EVENT_NET_RULE_ADD, description);
- txn.commit();
- } catch (Exception e) {
- txn.rollback();
- throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage());
- }finally{
- if(locked){
- _ipAddressDao.releaseFromLockTable(ipAddress.getAddress());
- }
- }
- return rule;
- }
-
- @Override @DB
- public FirewallRule createIpForwardingRuleInDb(String ipAddr, long virtualMachineId) {
-
- Transaction txn = Transaction.currentTxn();
- txn.start();
- UserVmVO userVM = null;
- FirewallRuleVO newFwRule = null;
- boolean locked = false;
- try {
- // validate IP Address exists
- IPAddressVO ipAddress = _ipAddressDao.findById(ipAddr);
- if (ipAddress == null) {
- throw new InvalidParameterValueException("Unable to create ip forwarding rule on address " + ipAddress + ", invalid IP address specified.");
- }
-
- // validate user VM exists
- userVM = _vmDao.findById(virtualMachineId);
- if (userVM == null) {
- throw new InvalidParameterValueException("Unable to create ip forwarding rule on address " + ipAddress + ", invalid virtual machine id specified (" + virtualMachineId + ").");
- }
-
- //sync point; cannot lock on rule ; hence sync on vm
- userVM = _vmDao.acquireInLockTable(userVM.getId());
-
- if(userVM == null){
- s_logger.warn("Unable to acquire lock on user vm for creating static NAT rule");
- return newFwRule;
- }else{
- locked = true;
- }
-
- // validate that IP address and userVM belong to the same account
- if ((ipAddress.getAccountId() == null) || (ipAddress.getAccountId().longValue() != userVM.getAccountId())) {
- throw new InvalidParameterValueException("Unable to create ip forwarding rule, IP address " + ipAddress + " owner is not the same as owner of virtual machine " + userVM.toString());
- }
-
- // validate that userVM is in the same availability zone as the IP address
- if (ipAddress.getDataCenterId() != userVM.getDataCenterId()) {
- throw new InvalidParameterValueException("Unable to create ip forwarding rule, IP address " + ipAddress + " is not in the same availability zone as virtual machine " + userVM.toString());
- }
-
- // if an admin account was passed in, or no account was passed in, make sure we honor the accountName/domainId parameters
- Account account = UserContext.current().getAccount();
- if (account != null) {
- if ((account.getType() == Account.ACCOUNT_TYPE_ADMIN) || (account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN)) {
- if (!_domainDao.isChildDomain(account.getDomainId(), userVM.getDomainId())) {
- throw new PermissionDeniedException("Unable to create ip forwarding rule, IP address " + ipAddress + " to virtual machine " + virtualMachineId + ", permission denied.");
- }
- } else if (account.getId() != userVM.getAccountId()) {
- throw new PermissionDeniedException("Unable to create ip forwarding rule, IP address " + ipAddress + " to virtual machine " + virtualMachineId + ", permission denied.");
- }
- }
-
- // check for ip address/port conflicts by checking existing port/ip forwarding rules
- List existingFirewallRules = _rulesDao.findRuleByPublicIp(ipAddr);
-
- if(existingFirewallRules.size() > 0){
- throw new NetworkRuleConflictException("There already exists a firewall rule for public ip:"+ipAddr);
- }
-
- //check for ip address/port conflicts by checking existing load balancing rules
- List existingLoadBalancerRules = _loadBalancerDao.listByIpAddress(ipAddr);
-
- if(existingLoadBalancerRules.size() > 0){
- throw new NetworkRuleConflictException("There already exists a load balancer rule for public ip:"+ipAddr);
- }
-
- //if given ip address is already source nat, return error
- if(ipAddress.isSourceNat()){
- throw new PermissionDeniedException("Cannot create a static nat rule for the ip:"+ipAddress.getAddress()+" ,this is already a source nat ip address");
- }
-
- //if given ip address is already static nat, return error
- if(ipAddress.isOneToOneNat()){
- throw new PermissionDeniedException("Cannot create a static nat rule for the ip:"+ipAddress.getAddress()+" ,this is already a static nat ip address");
- }
-
- newFwRule = new FirewallRuleVO();
- newFwRule.setEnabled(true);
- newFwRule.setForwarding(true);
- newFwRule.setPrivatePort(null);
- newFwRule.setProtocol(NetUtils.NAT_PROTO);//protocol cannot be null; adding this as a NAT
- newFwRule.setPublicPort(null);
- newFwRule.setPublicIpAddress(ipAddress.getAddress());
- newFwRule.setPrivateIpAddress(userVM.getGuestIpAddress());
- newFwRule.setGroupId(null);
-
- _rulesDao.persist(newFwRule);
- txn.commit();
- } catch (Exception e) {
- s_logger.warn("Unable to create new firewall rule for static NAT");
- txn.rollback();
- throw new ServerApiException(BaseCmd.INTERNAL_ERROR,"Unable to create new firewall rule for static NAT:"+e.getMessage());
- }finally{
- if(locked) {
- _vmDao.releaseFromLockTable(userVM.getId());
- }
- }
-
- return newFwRule;
- }
-
- @Override @DB
- public boolean deleteIpForwardingRule(Long id) {
- Long ruleId = id;
- Long userId = UserContext.current().getUserId();
- Account account = UserContext.current().getAccount();
-
- //verify input parameters here
- FirewallRuleVO rule = _firewallRulesDao.findById(ruleId);
- if (rule == null) {
- throw new InvalidParameterValueException("Unable to find port forwarding rule " + ruleId);
- }
-
- String publicIp = rule.getPublicIpAddress();
-
-
- IPAddressVO ipAddress = _ipAddressDao.findById(publicIp);
- if (ipAddress == null) {
- throw new InvalidParameterValueException("Unable to find IP address for ip forwarding rule " + ruleId);
- }
-
- // although we are not writing these values to the DB, we will check
- // them out of an abundance
- // of caution (may not be warranted)
-
- Account ruleOwner = _accountDao.findById(ipAddress.getAccountId());
- if (ruleOwner == null) {
- throw new InvalidParameterValueException("Unable to find owning account for ip forwarding rule " + ruleId);
- }
-
- // 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(), ruleOwner.getDomainId())) {
- throw new PermissionDeniedException("Unable to delete ip forwarding rule " + ruleId + ", permission denied.");
- }
- } else if (account.getId() != ruleOwner.getId()) {
- throw new PermissionDeniedException("Unable to delete ip forwarding rule " + ruleId + ", permission denied.");
- }
- }
-
- Transaction txn = Transaction.currentTxn();
- boolean locked = false;
- boolean success = false;
- try {
-
- ipAddress = _ipAddressDao.acquireInLockTable(publicIp);
- if (ipAddress == null) {
- throw new PermissionDeniedException("Unable to obtain lock on record for deletion");
- }
-
- locked = true;
- txn.start();
-
- final DomainRouterVO router = _routerMgr.getRouter(ipAddress.getAccountId(), ipAddress.getDataCenterId());
- success = createOrDeleteIpForwardingRuleOnDomr(rule, router, rule.getPrivateIpAddress(), false);
- _firewallRulesDao.remove(ruleId);
-
- //update the ip_address record
- ipAddress.setOneToOneNat(false);
- _ipAddressDao.persist(ipAddress);
-
- String description;
- String type = EventTypes.EVENT_NET_RULE_DELETE;
- String level = EventVO.LEVEL_INFO;
- String ruleName = rule.isForwarding() ? "ip forwarding" : "load balancer";
-
- if (success) {
- description = "deleted " + ruleName + " rule [" + publicIp +"]->[" + rule.getPrivateIpAddress() + "] " + rule.getProtocol();
- } else {
- level = EventVO.LEVEL_ERROR;
- description = "Error while deleting " + ruleName + " rule [" + publicIp + "]->[" + rule.getPrivateIpAddress() +"] " + rule.getProtocol();
- }
- EventUtils.saveEvent(userId, ipAddress.getAccountId(), level, type, description);
- txn.commit();
- }catch (Exception ex) {
- txn.rollback();
- s_logger.error("Unexpected exception deleting port forwarding rule " + ruleId, ex);
- return false;
- }finally {
- if (locked) {
- _ipAddressDao.releaseFromLockTable(publicIp);
- }
- txn.close();
- }
- return success;
- }
-
- private boolean createOrDeleteIpForwardingRuleOnDomr(FirewallRuleVO fwRule, DomainRouterVO router, String guestIp, boolean create){
-
- Commands cmds = new Commands(OnError.Continue);
- final SetFirewallRuleCommand cmd = new SetFirewallRuleCommand(router.getInstanceName(), router.getPrivateIpAddress(),fwRule, create);
- cmds.addCommand(cmd);
- try {
- _agentMgr.send(router.getHostId(), cmds);
- } catch (final AgentUnavailableException e) {
- s_logger.warn("agent unavailable", e);
- } catch (final OperationTimedoutException e) {
- s_logger.warn("Timed Out", e);
- }
- Answer[] answers = cmds.getAnswers();
- if (answers == null || answers[0].getResult() == false ){
- return false;
- }else{
- return true;
- }
- }
-
@Override @DB
public Network createNetwork(CreateNetworkCmd cmd) throws InvalidParameterValueException, PermissionDeniedException{
Account ctxAccount = UserContext.current().getAccount();
@@ -3533,4 +2121,10 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
}
}
+
+ @Override
+ public boolean applyRules(Ip ip, List extends FirewallRule> rules, boolean continueOnError) throws ResourceUnavailableException {
+ // TODO Auto-generated method stub
+ return false;
+ }
}
diff --git a/server/src/com/cloud/network/configuration/GuestNetworkGuru.java b/server/src/com/cloud/network/configuration/GuestNetworkGuru.java
index e134aca6033..bed759bc580 100644
--- a/server/src/com/cloud/network/configuration/GuestNetworkGuru.java
+++ b/server/src/com/cloud/network/configuration/GuestNetworkGuru.java
@@ -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;
}
}
diff --git a/server/src/com/cloud/network/dao/FirewallRulesDao.java b/server/src/com/cloud/network/dao/FirewallRulesDao.java
index 62cb4bde12e..c7941f7c45e 100644
--- a/server/src/com/cloud/network/dao/FirewallRulesDao.java
+++ b/server/src/com/cloud/network/dao/FirewallRulesDao.java
@@ -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 {
- public List listIPForwarding(String publicIPAddress, boolean forwarding);
- public List listIPForwarding(String publicIPAddress, String port, boolean forwarding);
-
- public List listIPForwarding(long userId);
- public List listIPForwarding(long userId, long dcId);
- public void deleteIPForwardingByPublicIpAddress(String ipAddress);
- public List listIPForwarding(String publicIPAddress);
- public List listIPForwardingForUpdate(String publicIPAddress);
- public void disableIPForwarding(String publicIPAddress);
- public List listIPForwardingForUpdate(String publicIp, boolean fwding);
- public List listIPForwardingForUpdate(String publicIp, String publicPort, String proto);
- public List listIPForwardingByPortAndProto(String publicIp, String publicPort, String proto);
-
- public List listLoadBalanceRulesForUpdate(String publicIp, String publicPort, String algo);
- public List listIpForwardingRulesForLoadBalancers(String publicIp);
-
-
- public List listRulesExcludingPubIpPort(String publicIpAddress, long securityGroupId);
- public List listBySecurityGroupId(long securityGroupId);
- public List listByLoadBalancerId(long loadBalancerId);
- public List listForwardingByPubAndPrivIp(boolean forwarding, String publicIPAddress, String privateIp);
- public FirewallRuleVO findByGroupAndPrivateIp(long groupId, String privateIp, boolean forwarding);
- public List listByPrivateIp(String privateIp);
- public boolean isPublicIpOneToOneNATted(String publicIp);
- void deleteIPForwardingByPublicIpAndPort(String ipAddress, String port);
- public List listIPForwardingForLB(long userId, long dcId);
- public List findRuleByPublicIp(String publicIp);
+public interface FirewallRulesDao extends GenericDao {
+ List listByIpAndNotRevoked(Ip ip);
+
+ boolean setStateToAdd(FirewallRuleVO rule);
+
+ boolean revoke(FirewallRuleVO rule);
+
+// public List listIPForwarding(String publicIPAddress, boolean forwarding);
+// public List listIPForwarding(String publicIPAddress, String port, boolean forwarding);
+//
+// public List listIPForwarding(long userId);
+// public List listIPForwarding(long userId, long dcId);
+// public void deleteIPForwardingByPublicIpAddress(String ipAddress);
+// public List listIPForwarding(String publicIPAddress);
+// public List listIPForwardingForUpdate(String publicIPAddress);
+// public void disableIPForwarding(String publicIPAddress);
+// public List listIPForwardingForUpdate(String publicIp, boolean fwding);
+// public List listIPForwardingForUpdate(String publicIp, String publicPort, String proto);
+// public List listIPForwardingByPortAndProto(String publicIp, String publicPort, String proto);
+//
+// public List listLoadBalanceRulesForUpdate(String publicIp, String publicPort, String algo);
+// public List listIpForwardingRulesForLoadBalancers(String publicIp);
+//
+//
+// public List listRulesExcludingPubIpPort(String publicIpAddress, long securityGroupId);
+// public List listBySecurityGroupId(long securityGroupId);
+// public List listByLoadBalancerId(long loadBalancerId);
+// public List listForwardingByPubAndPrivIp(boolean forwarding, String publicIPAddress, String privateIp);
+// public PortForwardingRuleVO findByGroupAndPrivateIp(long groupId, String privateIp, boolean forwarding);
+// public List findByPublicIpPrivateIpForNatRule(String publicIp,String privateIp);
+// public List listByPrivateIp(String privateIp);
+// public boolean isPublicIpOneToOneNATted(String publicIp);
+// void deleteIPForwardingByPublicIpAndPort(String ipAddress, String port);
+// public List listIPForwardingForLB(long userId, long dcId);
}
diff --git a/server/src/com/cloud/network/dao/FirewallRulesDaoImpl.java b/server/src/com/cloud/network/dao/FirewallRulesDaoImpl.java
index 8a2033d7cea..d7a507a8195 100644
--- a/server/src/com/cloud/network/dao/FirewallRulesDaoImpl.java
+++ b/server/src/com/cloud/network/dao/FirewallRulesDaoImpl.java
@@ -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 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 FWByIPSearch;
- protected SearchBuilder FWByIPAndForwardingSearch;
- protected SearchBuilder FWByIPPortAndForwardingSearch;
- protected SearchBuilder FWByIPPortProtoSearch;
- protected SearchBuilder FWByIPPortAlgoSearch;
- protected SearchBuilder FWByPrivateIPSearch;
- protected SearchBuilder RulesExcludingPubIpPort;
- protected SearchBuilder FWByGroupId;
- protected SearchBuilder FWByIpForLB;
-
- protected SearchBuilder FWByGroupAndPrivateIp;
- protected SearchBuilder FWByPublicIpSearch;
- protected SearchBuilder OneToOneNATSearch;
-
-
- protected FirewallRulesDaoImpl() {
- }
-
- @Override
- public boolean configure(String name, Map 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 listIPForwarding(String publicIPAddress, boolean forwarding) {
- SearchCriteria sc = FWByIPAndForwardingSearch.create();
- sc.setParameters("publicIpAddress", publicIPAddress);
- sc.setParameters("forwarding", forwarding);
- return listBy(sc);
- }
-
- @Override
- public List listIPForwarding(long userId) {
- Transaction txn = Transaction.currentTxn();
- List forwardings = new ArrayList();
- 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 listIPForwarding(long userId, long dcId) {
- Transaction txn = Transaction.currentTxn();
- List forwardings = new ArrayList();
- 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 AllFieldsSearch;
+ protected final SearchBuilder 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 listIPForwarding(String publicIPAddress) {
- SearchCriteria sc = FWByIPSearch.create();
- sc.setParameters("publicIpAddress", publicIPAddress);
- return listBy(sc);
- }
-
- @Override
- public List listIPForwardingForUpdate(String publicIPAddress) {
- SearchCriteria sc = FWByIPSearch.create();
- sc.setParameters("publicIpAddress", publicIPAddress);
- return listBy(sc, null);
- }
-
- @Override
- public List listIPForwardingForUpdate(String publicIp, boolean fwding) {
- SearchCriteria sc = FWByIPAndForwardingSearch.create();
- sc.setParameters("publicIpAddress", publicIp);
- sc.setParameters("forwarding", fwding);
- return search(sc, null);
- }
-
- @Override
- public List listIPForwardingForUpdate(String publicIp,
- String publicPort, String proto) {
- SearchCriteria sc = FWByIPPortProtoSearch.create();
- sc.setParameters("publicIpAddress", publicIp);
- sc.setParameters("publicPort", publicPort);
- sc.setParameters("protocol", proto);
- return search(sc, null);
- }
-
- @Override
- public List listLoadBalanceRulesForUpdate(String publicIp,
- String publicPort, String algo) {
- SearchCriteria sc = FWByIPPortAlgoSearch.create();
- sc.setParameters("publicIpAddress", publicIp);
- sc.setParameters("publicPort", publicPort);
- sc.setParameters("algorithm", algo);
- return listBy(sc, null);
- }
-
- @Override
- public List listIPForwarding(String publicIPAddress,
- String port, boolean forwarding) {
- SearchCriteria 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 listRulesExcludingPubIpPort(String publicIpAddress, long securityGroupId) {
- SearchCriteria sc = RulesExcludingPubIpPort.create();
- sc.setParameters("publicIpAddress", publicIpAddress);
- sc.setParameters("groupId", securityGroupId);
- sc.setParameters("forwarding", false);
- return listBy(sc);
- }
-
- @Override
- public List listBySecurityGroupId(long securityGroupId) {
- SearchCriteria sc = FWByGroupId.create();
- sc.setParameters("groupId", securityGroupId);
- sc.setParameters("forwarding", Boolean.TRUE);
- return listBy(sc);
- }
-
- @Override
- public List listForwardingByPubAndPrivIp(boolean forwarding, String publicIPAddress, String privateIp) {
- SearchCriteria sc = FWByIPAndForwardingSearch.create();
- sc.setParameters("publicIpAddress", publicIPAddress);
- sc.setParameters("forwarding", forwarding);
- sc.addAnd("privateIpAddress", SearchCriteria.Op.EQ, privateIp);
- return listBy(sc);
- }
-
- @Override
- public List listByLoadBalancerId(long loadBalancerId) {
- SearchCriteria 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 sc = FWByGroupAndPrivateIp.create();
- sc.setParameters("groupId", groupId);
- sc.setParameters("privateIpAddress", privateIp);
- sc.setParameters("forwarding", forwarding);
- return findOneBy(sc);
-
- }
-
- @Override
- public List findRuleByPublicIp(String publicIp){
- SearchCriteria sc = FWByPublicIpSearch.create();
- sc.setParameters("publicIpAddress", publicIp);
- return listBy(sc);
- }
-
- @Override
- public List listByPrivateIp(String privateIp) {
- SearchCriteria sc = FWByPrivateIPSearch.create();
- sc.setParameters("privateIpAddress", privateIp);
+ public List