diff --git a/agent/bindir/cloud-setup-agent.in b/agent/bindir/cloud-setup-agent.in
index 26bf1a0f0ac..6e9b448370b 100755
--- a/agent/bindir/cloud-setup-agent.in
+++ b/agent/bindir/cloud-setup-agent.in
@@ -40,12 +40,14 @@ backupdir = "@SHAREDSTATEDIR@/@AGENTPATH@/etcbackup"
try:
# parse cmd line
- opts, args = getopt.getopt(sys.argv[1:], "a", ["host=", "zone=", "pod=", "cluster=", "no-kvm", "guid="])
+ opts, args = getopt.getopt(sys.argv[1:], "a", ["host=", "zone=", "pod=", "cluster=", "no-kvm", "guid=", "pubNic=", "prvNic="])
host=None
zone=None
pod=None
cluster=None
guid=None
+ pubNic=None
+ prvNic=None
autoMode=False
do_check_kvm = True
for opt, arg in opts:
@@ -64,6 +66,10 @@ try:
elif opt == "--guid":
if arg != "":
guid = arg
+ elif opt == "--pubNic":
+ pubNic = arg
+ elif opt == "--prvNic":
+ prvNic = arg
elif opt == "--no-kvm":
do_check_kvm = False
elif opt == "-a":
@@ -89,7 +95,7 @@ try:
# system configuration tasks that our Cloud Agent setup performs
try:
- tasks = cloud_utils.config_tasks(brname)
+ tasks = cloud_utils.config_tasks(brname, pubNic, prvNic)
for t in tasks:
t.setAutoMode(autoMode)
if all( [ t.done() for t in tasks ] ):
@@ -116,7 +122,7 @@ try:
stderr(str(e))
bail(cloud_utils.E_SETUPFAILED,"Cloud Agent setup failed")
- setup_agent_config(configfile, host, zone, pod, cluster, guid)
+ setup_agent_config(configfile, host, zone, pod, cluster, guid, pubNic, prvNic)
stderr("Enabling and starting the Cloud Agent")
stop_service(servicename)
enable_service(servicename)
diff --git a/agent/src/com/cloud/agent/resource/computing/LibvirtComputingResource.java b/agent/src/com/cloud/agent/resource/computing/LibvirtComputingResource.java
index e803bff99e8..dfff26ca6c5 100644
--- a/agent/src/com/cloud/agent/resource/computing/LibvirtComputingResource.java
+++ b/agent/src/com/cloud/agent/resource/computing/LibvirtComputingResource.java
@@ -1338,7 +1338,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
vol = primaryPool.storageVolCreateXML(volDef.toString(), 0);
}
- VolumeTO volume = new VolumeTO(cmd.getVolumeId(), dskch.getType(), getStorageResourceType(), pool.getType(), pool.getPath(), vol.getName(),vol.getKey(), disksize);
+ VolumeTO volume = new VolumeTO(cmd.getVolumeId(), dskch.getType(), getStorageResourceType(), pool.getType(), pool.getPath(), vol.getName(),vol.getKey(), disksize, null);
return new CreateAnswer(cmd, volume);
} catch (LibvirtException e) {
diff --git a/agent/wscript_build b/agent/wscript_build
deleted file mode 100644
index 583f4ac8963..00000000000
--- a/agent/wscript_build
+++ /dev/null
@@ -1,7 +0,0 @@
-import Options
-
-bld.install_files("${AGENTLIBDIR}",
- bld.path.ant_glob("storagepatch/**",src=True,bld=False,dir=False,flat=True),
- cwd=bld.path,relative_trick=True)
-if not Options.options.PRESERVECONFIG:
- bld.install_files_filtered("${AGENTSYSCONFDIR}","conf/*")
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/agent/api/to/VolumeTO.java b/api/src/com/cloud/agent/api/to/VolumeTO.java
index 60dfe9eaf2b..3785fc96f9a 100644
--- a/api/src/com/cloud/agent/api/to/VolumeTO.java
+++ b/api/src/com/cloud/agent/api/to/VolumeTO.java
@@ -37,8 +37,10 @@ public class VolumeTO {
private StoragePoolType storagePoolType;
private long poolId;
private int deviceId;
+ private String chainInfo;
- public VolumeTO(long id, Volume.VolumeType type, Storage.StorageResourceType resourceType, StoragePoolType poolType, String name, String mountPoint, String path, long size) {
+ public VolumeTO(long id, Volume.VolumeType type, Storage.StorageResourceType resourceType, StoragePoolType poolType,
+ String name, String mountPoint, String path, long size, String chainInfo) {
this.id = id;
this.name= name;
this.path = path;
@@ -47,6 +49,7 @@ public class VolumeTO {
this.resourceType = resourceType;
this.storagePoolType = poolType;
this.mountPoint = mountPoint;
+ this.chainInfo = chainInfo;
}
public VolumeTO(Volume volume, StoragePool pool) {
@@ -58,6 +61,7 @@ public class VolumeTO {
this.resourceType = volume.getStorageResourceType();
this.storagePoolType = pool.getPoolType();
this.mountPoint = volume.getFolder();
+ this.chainInfo = volume.getChainInfo();
}
@@ -97,6 +101,10 @@ public class VolumeTO {
return storagePoolType;
}
+ public String getChainInfo() {
+ return chainInfo;
+ }
+
@Override
public String toString() {
return new StringBuilder("Vol[").append(id).append("|").append(type).append("|").append(path).append("|").append(size).append("]").toString();
diff --git a/api/src/com/cloud/api/ApiConstants.java b/api/src/com/cloud/api/ApiConstants.java
index f132b53fb07..0d6b2f039bd 100755
--- a/api/src/com/cloud/api/ApiConstants.java
+++ b/api/src/com/cloud/api/ApiConstants.java
@@ -170,6 +170,7 @@ public class ApiConstants {
public static final String MAX_CONNECTIONS = "maxconnections";
public static final String NETWORK_OFFERING_ID = "networkofferingid";
public static final String NETWORK_IDS = "networkids";
+ public static final String NETWORK_ID = "networkid";
public static final String SPECIFY_VLAN = "specifyvlan";
public static final String IS_DEFAULT = "isdefault";
}
diff --git a/api/src/com/cloud/api/BaseAsyncCmd.java b/api/src/com/cloud/api/BaseAsyncCmd.java
index 2354ead5345..3502700ffc9 100644
--- a/api/src/com/cloud/api/BaseAsyncCmd.java
+++ b/api/src/com/cloud/api/BaseAsyncCmd.java
@@ -37,7 +37,7 @@ public abstract class BaseAsyncCmd extends BaseCmd {
* used to determine that information.
* @return the id of the account that owns the object being acted upon
*/
- public abstract long getAccountId();
+ public abstract long getEntityOwnerId();
/**
* For proper tracking of async commands through the system, events must be generated when the command is
diff --git a/api/src/com/cloud/api/BaseAsyncCreateCmd.java b/api/src/com/cloud/api/BaseAsyncCreateCmd.java
index 4da990ba930..d6f6a75ddb1 100644
--- a/api/src/com/cloud/api/BaseAsyncCreateCmd.java
+++ b/api/src/com/cloud/api/BaseAsyncCreateCmd.java
@@ -6,13 +6,13 @@ public abstract class BaseAsyncCreateCmd extends BaseAsyncCmd {
@Parameter(name="id", type=CommandType.LONG)
private Long id;
- public abstract void callCreate();
+ public abstract void create();
- public Long getId() {
+ public Long getEntityId() {
return id;
}
- public void setId(Long id) {
+ public void setEntityId(Long id) {
this.id = id;
}
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/AddVpnUserCmd.java b/api/src/com/cloud/api/commands/AddVpnUserCmd.java
index 2d24473cefc..ca7a326e426 100644
--- a/api/src/com/cloud/api/commands/AddVpnUserCmd.java
+++ b/api/src/com/cloud/api/commands/AddVpnUserCmd.java
@@ -93,7 +93,7 @@ public class AddVpnUserCmd extends BaseAsyncCmd {
}
@Override
- public long getAccountId() {
+ public long getEntityOwnerId() {
Account account = UserContext.current().getAccount();
if ((account == null) || isAdmin(account.getType())) {
if ((domainId != null) && (accountName != null)) {
@@ -113,7 +113,7 @@ public class AddVpnUserCmd extends BaseAsyncCmd {
@Override
public String getEventDescription() {
- return "Add Remote Access VPN user for account " + getAccountId() + " username= " + getUserName();
+ return "Add Remote Access VPN user for account " + getEntityOwnerId() + " username= " + getUserName();
}
diff --git a/api/src/com/cloud/api/commands/AssignToLoadBalancerRuleCmd.java b/api/src/com/cloud/api/commands/AssignToLoadBalancerRuleCmd.java
index 4bc5494b85c..9a002104536 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)
@@ -78,7 +79,7 @@ public class AssignToLoadBalancerRuleCmd extends BaseAsyncCmd {
}
@Override
- public long getAccountId() {
+ public long getEntityOwnerId() {
LoadBalancer lb = _entityMgr.findById(LoadBalancer.class, getLoadBalancerId());
if (lb == null) {
return Account.ACCOUNT_ID_SYSTEM; // bad id given, parent this command to SYSTEM so ERROR events are tracked
@@ -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/AttachIsoCmd.java b/api/src/com/cloud/api/commands/AttachIsoCmd.java
index 919f027910c..d2b58e4feeb 100755
--- a/api/src/com/cloud/api/commands/AttachIsoCmd.java
+++ b/api/src/com/cloud/api/commands/AttachIsoCmd.java
@@ -71,7 +71,7 @@ public class AttachIsoCmd extends BaseAsyncCmd {
}
@Override
- public long getAccountId() {
+ public long getEntityOwnerId() {
VirtualMachineTemplate iso = _responseGenerator.findTemplateById(getId());
if (iso == null) {
return Account.ACCOUNT_ID_SYSTEM; // bad id given, parent this command to SYSTEM so ERROR events are tracked
diff --git a/api/src/com/cloud/api/commands/AttachVolumeCmd.java b/api/src/com/cloud/api/commands/AttachVolumeCmd.java
index 3639e33cdad..a753a8e455f 100755
--- a/api/src/com/cloud/api/commands/AttachVolumeCmd.java
+++ b/api/src/com/cloud/api/commands/AttachVolumeCmd.java
@@ -96,7 +96,7 @@ public class AttachVolumeCmd extends BaseAsyncCmd {
}
@Override
- public long getAccountId() {
+ public long getEntityOwnerId() {
Volume volume = _responseGenerator.findVolumeById(getId());
if (volume == null) {
return Account.ACCOUNT_ID_SYSTEM; // bad id given, parent this command to SYSTEM so ERROR events are tracked
diff --git a/api/src/com/cloud/api/commands/AuthorizeNetworkGroupIngressCmd.java b/api/src/com/cloud/api/commands/AuthorizeNetworkGroupIngressCmd.java
index b0ca0389c4f..2f29bffdccc 100644
--- a/api/src/com/cloud/api/commands/AuthorizeNetworkGroupIngressCmd.java
+++ b/api/src/com/cloud/api/commands/AuthorizeNetworkGroupIngressCmd.java
@@ -153,7 +153,7 @@ public class AuthorizeNetworkGroupIngressCmd extends BaseAsyncCmd {
}
@Override
- public long getAccountId() {
+ public long getEntityOwnerId() {
Account account = UserContext.current().getAccount();
if ((account == null) || isAdmin(account.getType())) {
if ((domainId != null) && (accountName != null)) {
diff --git a/api/src/com/cloud/api/commands/CancelMaintenanceCmd.java b/api/src/com/cloud/api/commands/CancelMaintenanceCmd.java
index 7603756d331..cd38eb3bd94 100644
--- a/api/src/com/cloud/api/commands/CancelMaintenanceCmd.java
+++ b/api/src/com/cloud/api/commands/CancelMaintenanceCmd.java
@@ -70,7 +70,7 @@ public class CancelMaintenanceCmd extends BaseAsyncCmd {
}
@Override
- public long getAccountId() {
+ public long getEntityOwnerId() {
Account account = UserContext.current().getAccount();
if (account != null) {
return account.getId();
diff --git a/api/src/com/cloud/api/commands/CancelPrimaryStorageMaintenanceCmd.java b/api/src/com/cloud/api/commands/CancelPrimaryStorageMaintenanceCmd.java
index 4e409bcfc31..8f6fa8ba033 100644
--- a/api/src/com/cloud/api/commands/CancelPrimaryStorageMaintenanceCmd.java
+++ b/api/src/com/cloud/api/commands/CancelPrimaryStorageMaintenanceCmd.java
@@ -27,6 +27,7 @@ import com.cloud.api.Implementation;
import com.cloud.api.Parameter;
import com.cloud.api.ServerApiException;
import com.cloud.api.response.StoragePoolResponse;
+import com.cloud.async.AsyncJob;
import com.cloud.event.EventTypes;
import com.cloud.storage.StoragePool;
import com.cloud.user.Account;
@@ -67,9 +68,17 @@ public class CancelPrimaryStorageMaintenanceCmd extends BaseAsyncCmd {
public static String getResultObjectName() {
return "primarystorage";
}
+
+ public AsyncJob.Type getInstanceType() {
+ return AsyncJob.Type.Host;
+ }
+
+ public Long getInstanceId() {
+ return getId();
+ }
@Override
- public long getAccountId() {
+ public long getEntityOwnerId() {
Account account = UserContext.current().getAccount();
if (account != null) {
return account.getId();
diff --git a/api/src/com/cloud/api/commands/CopyIsoCmd.java b/api/src/com/cloud/api/commands/CopyIsoCmd.java
index 3b5f3b747e7..68a28934dd8 100644
--- a/api/src/com/cloud/api/commands/CopyIsoCmd.java
+++ b/api/src/com/cloud/api/commands/CopyIsoCmd.java
@@ -81,7 +81,7 @@ public class CopyIsoCmd extends BaseAsyncCmd {
}
@Override
- public long getAccountId() {
+ public long getEntityOwnerId() {
VirtualMachineTemplate iso = _entityMgr.findById(VirtualMachineTemplate.class, getId());
if (iso != null) {
return iso.getAccountId();
diff --git a/api/src/com/cloud/api/commands/CopyTemplateCmd.java b/api/src/com/cloud/api/commands/CopyTemplateCmd.java
index 451a2e0a9c2..d347ce01a87 100644
--- a/api/src/com/cloud/api/commands/CopyTemplateCmd.java
+++ b/api/src/com/cloud/api/commands/CopyTemplateCmd.java
@@ -82,7 +82,7 @@ public class CopyTemplateCmd extends BaseAsyncCmd {
}
@Override
- public long getAccountId() {
+ public long getEntityOwnerId() {
VirtualMachineTemplate template = _entityMgr.findById(VirtualMachineTemplate.class, getId());
if (template != null) {
return template.getAccountId();
diff --git a/api/src/com/cloud/api/commands/CreateDiskOfferingCmd.java b/api/src/com/cloud/api/commands/CreateDiskOfferingCmd.java
index 1fa54340879..d7cb6279b04 100755
--- a/api/src/com/cloud/api/commands/CreateDiskOfferingCmd.java
+++ b/api/src/com/cloud/api/commands/CreateDiskOfferingCmd.java
@@ -24,6 +24,7 @@ import com.cloud.api.BaseCmd;
import com.cloud.api.Implementation;
import com.cloud.api.Parameter;
import com.cloud.api.ServerApiException;
+import com.cloud.api.BaseCmd.CommandType;
import com.cloud.api.response.DiskOfferingResponse;
import com.cloud.offering.DiskOffering;
@@ -51,6 +52,10 @@ public class CreateDiskOfferingCmd extends BaseCmd {
@Parameter(name=ApiConstants.CUSTOMIZED, type=CommandType.BOOLEAN, description="whether disk offering is custom or not")
private Boolean customized;
+
+ @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="the ID of the containing domain, null for public offerings")
+ private Long domainId;
+
/////////////////////////////////////////////////////
/////////////////// Accessors ///////////////////////
/////////////////////////////////////////////////////
@@ -75,6 +80,9 @@ public class CreateDiskOfferingCmd extends BaseCmd {
return customized;
}
+ public Long getDomainId(){
+ return domainId;
+ }
/////////////////////////////////////////////////////
/////////////// API Implementation///////////////////
/////////////////////////////////////////////////////
diff --git a/api/src/com/cloud/api/commands/CreateIpForwardingRuleCmd.java b/api/src/com/cloud/api/commands/CreateIpForwardingRuleCmd.java
index bbff4bf0343..00d5c97e8e3 100644
--- a/api/src/com/cloud/api/commands/CreateIpForwardingRuleCmd.java
+++ b/api/src/com/cloud/api/commands/CreateIpForwardingRuleCmd.java
@@ -28,11 +28,14 @@ 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.user.Account;
+import com.cloud.exception.NetworkRuleConflictException;
+import com.cloud.network.rules.PortForwardingRule;
+import com.cloud.user.UserContext;
+import com.cloud.utils.net.Ip;
+import com.cloud.utils.net.NetUtils;
@Implementation(description="Creates an ip forwarding rule", responseObject=FirewallRuleResponse.class)
-public class CreateIpForwardingRuleCmd extends BaseAsyncCreateCmd {
+public class CreateIpForwardingRuleCmd extends BaseAsyncCreateCmd implements PortForwardingRule {
public static final Logger s_logger = Logger.getLogger(CreateIpForwardingRuleCmd.class.getName());
private static final String s_name = "createipforwardingruleresponse";
@@ -72,9 +75,17 @@ public class CreateIpForwardingRuleCmd extends BaseAsyncCreateCmd {
@Override
public void execute(){
- FirewallRule result = _networkService.createIpForwardingRuleOnDomr(this.getId());
- if (result != null) {
- FirewallRuleResponse fwResponse = _responseGenerator.createFirewallRuleResponse(result);
+ boolean result;
+ try {
+ result = _rulesService.applyPortForwardingRules(new Ip(ipAddress), UserContext.current().getAccount());
+ } catch (Exception e) {
+ s_logger.error("Unable to apply port forwarding rules", e);
+ _rulesService.revokePortForwardingRule(getEntityId(), true);
+ result = false;
+ }
+ if (result) {
+ PortForwardingRule rule = _entityMgr.findById(PortForwardingRule.class, getEntityId());
+ FirewallRuleResponse fwResponse = _responseGenerator.createFirewallRuleResponse(rule);
fwResponse.setResponseName(getName());
this.setResponseObject(fwResponse);
} else {
@@ -84,18 +95,21 @@ public class CreateIpForwardingRuleCmd extends BaseAsyncCreateCmd {
}
@Override
- public void callCreate(){
- FirewallRule rule = _networkService.createIpForwardingRuleInDb(ipAddress,virtualMachineId);
- if (rule != null){
- this.setId(rule.getId());
- } else {
- throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create ip forwarding rule");
+ public void create() {
+ PortForwardingRule rule;
+ try {
+ rule = _rulesService.createPortForwardingRule(this, virtualMachineId);
+ } catch (NetworkRuleConflictException e) {
+ s_logger.info("Unable to create Port Forwarding Rule due to " + e.getMessage());
+ throw new ServerApiException(BaseCmd.NETWORK_RULE_CONFLICT_ERROR, e.getMessage());
}
+
+ this.setEntityId(rule.getId());
}
@Override
- public long getAccountId() {
- return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked
+ public long getEntityOwnerId() {
+ return _entityMgr.findById(PortForwardingRule.class, getEntityId()).getAccountId();
}
@Override
@@ -108,4 +122,74 @@ public class CreateIpForwardingRuleCmd extends BaseAsyncCreateCmd {
return ("Creating an ipforwarding 1:1 NAT rule for "+ipAddress+" with virtual machine:"+virtualMachineId);
}
+ @Override
+ public long getId() {
+ throw new UnsupportedOperationException("Don't call me");
+ }
+
+ @Override
+ public String getXid() {
+ return null;
+ }
+
+ @Override
+ public Ip getSourceIpAddress() {
+ return new Ip(ipAddress);
+ }
+
+ @Override
+ public int getSourcePortStart() {
+ return -1;
+ }
+
+ @Override
+ public int getSourcePortEnd() {
+ return -1;
+ }
+
+ @Override
+ public String getProtocol() {
+ return NetUtils.NAT_PROTO;
+ }
+
+ @Override
+ public Purpose getPurpose() {
+ return Purpose.PortForwarding;
+ }
+
+ @Override
+ public State getState() {
+ throw new UnsupportedOperationException("Don't call me");
+ }
+
+ @Override
+ public long getNetworkId() {
+ return -1;
+ }
+
+ @Override
+ public long getDomainId() {
+ throw new UnsupportedOperationException("Don't call me");
+ }
+
+ @Override
+ public Ip getDestinationIpAddress() {
+ return null;
+ }
+
+ @Override
+ public int getDestinationPortStart() {
+ return -1;
+ }
+
+ @Override
+ public int getDestinationPortEnd() {
+ return -1;
+ }
+
+ @Override
+ public long getAccountId() {
+ throw new UnsupportedOperationException("Get the account id from network");
+ }
+
}
diff --git a/api/src/com/cloud/api/commands/CreateLoadBalancerRuleCmd.java b/api/src/com/cloud/api/commands/CreateLoadBalancerRuleCmd.java
index 61c585fb1f4..345530e6d7d 100644
--- a/api/src/com/cloud/api/commands/CreateLoadBalancerRuleCmd.java
+++ b/api/src/com/cloud/api/commands/CreateLoadBalancerRuleCmd.java
@@ -18,18 +18,25 @@
package com.cloud.api.commands;
+import java.util.List;
+
import org.apache.log4j.Logger;
import com.cloud.api.ApiConstants;
+import com.cloud.api.BaseAsyncCreateCmd;
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.LoadBalancerResponse;
-import com.cloud.network.LoadBalancer;
+import com.cloud.event.EventTypes;
+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 BaseAsyncCreateCmd implements LoadBalancer {
public static final Logger s_logger = Logger.getLogger(CreateLoadBalancerRuleCmd.class.getName());
private static final String s_name = "createloadbalancerruleresponse";
@@ -61,10 +68,12 @@ public class CreateLoadBalancerRuleCmd extends BaseCmd {
/////////////////// Accessors ///////////////////////
/////////////////////////////////////////////////////
+ @Override
public String getAlgorithm() {
return algorithm;
}
+ @Override
public String getDescription() {
return description;
}
@@ -96,14 +105,107 @@ 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");
+ }
+
+ @Override
+ public void create() {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public long getEntityOwnerId() {
+ return _entityMgr.findById(LoadBalancer.class, getEntityId()).getAccountId();
+ }
+
+ @Override
+ public String getEventType() {
+ return EventTypes.EVENT_LOAD_BALANCER_CREATE;
+ }
+
+ @Override
+ public String getEventDescription() {
+ return "Create load balancer";
}
}
diff --git a/api/src/com/cloud/api/commands/CreateNetworkCmd.java b/api/src/com/cloud/api/commands/CreateNetworkCmd.java
index 161605aea57..cb957694d76 100644
--- a/api/src/com/cloud/api/commands/CreateNetworkCmd.java
+++ b/api/src/com/cloud/api/commands/CreateNetworkCmd.java
@@ -76,6 +76,9 @@ public class CreateNetworkCmd extends BaseCmd {
@Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="domain ID of the account owning a VLAN")
private Long domainId;
+
+ @Parameter(name=ApiConstants.IS_SHARED, type=CommandType.BOOLEAN, description="true is network offering supports vlans")
+ private Boolean isShared;
/////////////////////////////////////////////////////
/////////////////// Accessors ///////////////////////
@@ -131,6 +134,10 @@ public class CreateNetworkCmd extends BaseCmd {
public String getDisplayText() {
return displayText;
}
+
+ public boolean getIsShared() {
+ return isShared == null ? false : isShared;
+ }
/////////////////////////////////////////////////////
/////////////// API Implementation///////////////////
diff --git a/api/src/com/cloud/api/commands/CreateNetworkOfferingCmd.java b/api/src/com/cloud/api/commands/CreateNetworkOfferingCmd.java
index 64f9d59276b..9c30aff5c06 100644
--- a/api/src/com/cloud/api/commands/CreateNetworkOfferingCmd.java
+++ b/api/src/com/cloud/api/commands/CreateNetworkOfferingCmd.java
@@ -57,9 +57,6 @@ public class CreateNetworkOfferingCmd extends BaseCmd {
@Parameter(name=ApiConstants.SPECIFY_VLAN, type=CommandType.BOOLEAN, description="true is network offering supports vlans")
private Boolean specifyVlan;
-
- @Parameter(name=ApiConstants.IS_SHARED, type=CommandType.BOOLEAN, description="true is network offering supports vlans")
- private Boolean isShared;
/////////////////////////////////////////////////////
/////////////////// Accessors ///////////////////////
@@ -92,10 +89,6 @@ public class CreateNetworkOfferingCmd extends BaseCmd {
public Boolean getSpecifyVlan() {
return specifyVlan;
}
-
- public Boolean getIsShared() {
- return isShared;
- }
/////////////////////////////////////////////////////
/////////////// API Implementation///////////////////
diff --git a/api/src/com/cloud/api/commands/CreatePortForwardingRuleCmd.java b/api/src/com/cloud/api/commands/CreatePortForwardingRuleCmd.java
index aa58fd14a7b..bc3e2063da6 100644
--- a/api/src/com/cloud/api/commands/CreatePortForwardingRuleCmd.java
+++ b/api/src/com/cloud/api/commands/CreatePortForwardingRuleCmd.java
@@ -21,16 +21,21 @@ package com.cloud.api.commands;
import org.apache.log4j.Logger;
import com.cloud.api.ApiConstants;
+import com.cloud.api.BaseAsyncCreateCmd;
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.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 BaseAsyncCreateCmd implements PortForwardingRule {
public static final Logger s_logger = Logger.getLogger(CreatePortForwardingRuleCmd.class.getName());
private static final String s_name = "createportforwardingruleresponse";
@@ -67,6 +72,7 @@ public class CreatePortForwardingRuleCmd extends BaseCmd {
return privatePort;
}
+ @Override
public String getProtocol() {
return protocol;
}
@@ -90,19 +96,120 @@ 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);
+ 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);
+ }
+ }
+ 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 getEntityOwnerId() {
+ return _entityMgr.findById(PortForwardingRule.class, getEntityId()).getAccountId();
+ }
+
+ @Override
+ public long getDomainId() {
+ throw new UnsupportedOperationException("Get the domain id from network");
+ }
+
+ @Override
+ public Ip getDestinationIpAddress() {
+ return null;
+ }
+
+ @Override
+ public int getDestinationPortStart() {
+ return Integer.parseInt(privatePort);
+ }
+
+ @Override
+ public int getDestinationPortEnd() {
+ return Integer.parseInt(privatePort);
+ }
+
+ @Override
+ public void create() {
+ try {
+ PortForwardingRule result = _rulesService.createPortForwardingRule(this, virtualMachineId);
+ setEntityId(result.getId());
+ } catch (NetworkRuleConflictException ex) {
+ s_logger.info("Network rule conflict: " + ex.getMessage());
+ throw new ServerApiException(BaseCmd.NETWORK_RULE_CONFLICT_ERROR, ex.getMessage());
+ }
+ }
+
+ @Override
+ public String getEventType() {
+ return EventTypes.EVENT_NET_RULE_ADD;
+ }
+
+ @Override
+ public String getEventDescription() {
+ return ("Creating an port forwarding rule for "+ipAddress+" with virtual machine:"+virtualMachineId);
+ }
+
+ @Override
+ public long getAccountId() {
+ throw new UnsupportedOperationException("Get the account id from network");
+ }
+
}
diff --git a/api/src/com/cloud/api/commands/CreateRemoteAccessVpnCmd.java b/api/src/com/cloud/api/commands/CreateRemoteAccessVpnCmd.java
index ddc1944737f..cebffef0aba 100644
--- a/api/src/com/cloud/api/commands/CreateRemoteAccessVpnCmd.java
+++ b/api/src/com/cloud/api/commands/CreateRemoteAccessVpnCmd.java
@@ -105,7 +105,7 @@ public class CreateRemoteAccessVpnCmd extends BaseAsyncCreateCmd {
}
@Override
- public long getAccountId() {
+ public long getEntityOwnerId() {
Account account = UserContext.current().getAccount();
if ((account == null) || isAdmin(account.getType())) {
if ((domainId != null) && (accountName != null)) {
@@ -125,7 +125,7 @@ public class CreateRemoteAccessVpnCmd extends BaseAsyncCreateCmd {
@Override
public String getEventDescription() {
- return "Create Remote Access VPN for account " + getAccountId() + " in zone " + getZoneId();
+ return "Create Remote Access VPN for account " + getEntityOwnerId() + " in zone " + getZoneId();
}
@Override
@@ -134,11 +134,11 @@ public class CreateRemoteAccessVpnCmd extends BaseAsyncCreateCmd {
}
@Override
- public void callCreate(){
+ public void create(){
try {
RemoteAccessVpn vpn = _networkService.createRemoteAccessVpn(this);
if (vpn != null) {
- this.setId(vpn.getId());
+ this.setEntityId(vpn.getId());
} else {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create remote access vpn");
}
diff --git a/api/src/com/cloud/api/commands/CreateSnapshotCmd.java b/api/src/com/cloud/api/commands/CreateSnapshotCmd.java
index 5e54db27421..abb1e4ef800 100644
--- a/api/src/com/cloud/api/commands/CreateSnapshotCmd.java
+++ b/api/src/com/cloud/api/commands/CreateSnapshotCmd.java
@@ -26,7 +26,6 @@ import com.cloud.api.BaseCmd;
import com.cloud.api.Implementation;
import com.cloud.api.Parameter;
import com.cloud.api.ServerApiException;
-import com.cloud.api.BaseCmd.CommandType;
import com.cloud.api.response.SnapshotResponse;
import com.cloud.async.AsyncJob;
import com.cloud.event.EventTypes;
@@ -94,7 +93,7 @@ public class CreateSnapshotCmd extends BaseAsyncCreateCmd {
}
@Override
- public long getAccountId() {
+ public long getEntityOwnerId() {
Volume volume = _entityMgr.findById(Volume.class, getVolumeId());
if (volume != null) {
return volume.getAccountId();
@@ -114,14 +113,15 @@ public class CreateSnapshotCmd extends BaseAsyncCreateCmd {
return "creating snapshot for volume: " + getVolumeId();
}
+ @Override
public AsyncJob.Type getInstanceType() {
return AsyncJob.Type.Snapshot;
}
@Override
- public void callCreate(){
+ public void create(){
long id = _snapshotMgr.getNextInSequence(this);
- this.setId(id);
+ this.setEntityId(id);
}
@Override
diff --git a/api/src/com/cloud/api/commands/CreateTemplateCmd.java b/api/src/com/cloud/api/commands/CreateTemplateCmd.java
index f4d5ad76448..b4706e8f94f 100644
--- a/api/src/com/cloud/api/commands/CreateTemplateCmd.java
+++ b/api/src/com/cloud/api/commands/CreateTemplateCmd.java
@@ -134,7 +134,7 @@ public class CreateTemplateCmd extends BaseAsyncCreateCmd {
}
@Override
- public long getAccountId() {
+ public long getEntityOwnerId() {
Long volumeId = getVolumeId();
Long snapshotId = getSnapshotId();
if (volumeId != null) {
@@ -168,10 +168,10 @@ public class CreateTemplateCmd extends BaseAsyncCreateCmd {
}
@Override
- public void callCreate(){
+ public void create(){
VirtualMachineTemplate template = _userVmService.createPrivateTemplateRecord(this);
if (template != null){
- this.setId(template.getId());
+ this.setEntityId(template.getId());
} else {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create a template");
}
diff --git a/api/src/com/cloud/api/commands/CreateVolumeCmd.java b/api/src/com/cloud/api/commands/CreateVolumeCmd.java
index fd921467060..c01d8851c5e 100644
--- a/api/src/com/cloud/api/commands/CreateVolumeCmd.java
+++ b/api/src/com/cloud/api/commands/CreateVolumeCmd.java
@@ -115,7 +115,7 @@ public class CreateVolumeCmd extends BaseAsyncCreateCmd {
}
@Override
- public long getAccountId() {
+ public long getEntityOwnerId() {
Account account = UserContext.current().getAccount();
if ((account == null) || isAdmin(account.getType())) {
if ((domainId != null) && (accountName != null)) {
@@ -144,11 +144,11 @@ public class CreateVolumeCmd extends BaseAsyncCreateCmd {
}
@Override
- public void callCreate(){
+ public void create(){
try {
Volume volume = _storageMgr.allocVolume(this);
if (volume != null) {
- this.setId(volume.getId());
+ this.setEntityId(volume.getId());
} else {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create volume");
}
diff --git a/api/src/com/cloud/api/commands/DeleteDomainCmd.java b/api/src/com/cloud/api/commands/DeleteDomainCmd.java
index 93a5ef82d97..335de83503c 100644
--- a/api/src/com/cloud/api/commands/DeleteDomainCmd.java
+++ b/api/src/com/cloud/api/commands/DeleteDomainCmd.java
@@ -68,7 +68,7 @@ public class DeleteDomainCmd extends BaseAsyncCmd {
}
@Override
- public long getAccountId() {
+ public long getEntityOwnerId() {
Domain domain = _entityMgr.findById(Domain.class, getId());
if (domain != null) {
return domain.getAccountId();
diff --git a/api/src/com/cloud/api/commands/DeleteIpForwardingRuleCmd.java b/api/src/com/cloud/api/commands/DeleteIpForwardingRuleCmd.java
index 916c78151ab..8ecadb467b1 100644
--- a/api/src/com/cloud/api/commands/DeleteIpForwardingRuleCmd.java
+++ b/api/src/com/cloud/api/commands/DeleteIpForwardingRuleCmd.java
@@ -28,6 +28,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.rules.PortForwardingRule;
import com.cloud.user.Account;
@Implementation(description="Deletes an ip forwarding rule", responseObject=SuccessResponse.class)
@@ -62,9 +63,8 @@ public class DeleteIpForwardingRuleCmd extends BaseAsyncCmd {
@Override
public void execute(){
- boolean result = false;
- result = _networkService.deleteIpForwardingRule(id);
- if (result) {
+ PortForwardingRule rule = _rulesService.revokePortForwardingRule(id, true);
+ if (rule != null) {
SuccessResponse response = new SuccessResponse(getName());
this.setResponseObject(response);
} else {
@@ -73,7 +73,7 @@ public class DeleteIpForwardingRuleCmd extends BaseAsyncCmd {
}
@Override
- public long getAccountId() {
+ public long getEntityOwnerId() {
return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked
}
diff --git a/api/src/com/cloud/api/commands/DeleteIsoCmd.java b/api/src/com/cloud/api/commands/DeleteIsoCmd.java
index d73c1c0aa8d..01d746d3b2d 100644
--- a/api/src/com/cloud/api/commands/DeleteIsoCmd.java
+++ b/api/src/com/cloud/api/commands/DeleteIsoCmd.java
@@ -73,7 +73,7 @@ public class DeleteIsoCmd extends BaseAsyncCmd {
}
@Override
- public long getAccountId() {
+ public long getEntityOwnerId() {
VirtualMachineTemplate iso = _entityMgr.findById(VirtualMachineTemplate.class, getId());
if (iso != null) {
return iso.getAccountId();
diff --git a/api/src/com/cloud/api/commands/DeleteLoadBalancerRuleCmd.java b/api/src/com/cloud/api/commands/DeleteLoadBalancerRuleCmd.java
index 9bb6255d167..8f3b583596b 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)
@@ -60,7 +60,7 @@ public class DeleteLoadBalancerRuleCmd extends BaseAsyncCmd {
}
@Override
- public long getAccountId() {
+ public long getEntityOwnerId() {
LoadBalancer lb = _entityMgr.findById(LoadBalancer.class, getId());
if (lb != null) {
return lb.getAccountId();
@@ -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..ad379fe5269 100644
--- a/api/src/com/cloud/api/commands/DeletePortForwardingRuleCmd.java
+++ b/api/src/com/cloud/api/commands/DeletePortForwardingRuleCmd.java
@@ -25,6 +25,8 @@ 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;
@Implementation(description="Deletes a port forwarding rule", responseObject=SuccessResponse.class)
public class DeletePortForwardingRuleCmd extends BaseCmd {
@@ -57,9 +59,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);
+ if (result != null) {
SuccessResponse response = new SuccessResponse(getName());
this.setResponseObject(response);
} else {
diff --git a/api/src/com/cloud/api/commands/DeleteRemoteAccessVpnCmd.java b/api/src/com/cloud/api/commands/DeleteRemoteAccessVpnCmd.java
index c57a8010855..dd3ded9a509 100644
--- a/api/src/com/cloud/api/commands/DeleteRemoteAccessVpnCmd.java
+++ b/api/src/com/cloud/api/commands/DeleteRemoteAccessVpnCmd.java
@@ -79,7 +79,7 @@ public class DeleteRemoteAccessVpnCmd extends BaseAsyncCmd {
}
@Override
- public long getAccountId() {
+ public long getEntityOwnerId() {
Account account = UserContext.current().getAccount();
if ((account == null) || isAdmin(account.getType())) {
if ((domainId != null) && (accountName != null)) {
@@ -99,7 +99,7 @@ public class DeleteRemoteAccessVpnCmd extends BaseAsyncCmd {
@Override
public String getEventDescription() {
- return "Delete Remote Access VPN for account " + getAccountId() + " in zone " + getZoneId();
+ return "Delete Remote Access VPN for account " + getEntityOwnerId() + " in zone " + getZoneId();
}
@Override
diff --git a/api/src/com/cloud/api/commands/DeleteSnapshotCmd.java b/api/src/com/cloud/api/commands/DeleteSnapshotCmd.java
index ad1b9d0f7aa..5f43f588199 100644
--- a/api/src/com/cloud/api/commands/DeleteSnapshotCmd.java
+++ b/api/src/com/cloud/api/commands/DeleteSnapshotCmd.java
@@ -63,7 +63,7 @@ public class DeleteSnapshotCmd extends BaseAsyncCmd {
}
@Override
- public long getAccountId() {
+ public long getEntityOwnerId() {
Snapshot snapshot = _entityMgr.findById(Snapshot.class, getId());
if (snapshot != null) {
return snapshot.getAccountId();
diff --git a/api/src/com/cloud/api/commands/DeleteTemplateCmd.java b/api/src/com/cloud/api/commands/DeleteTemplateCmd.java
index 7b9c25e565c..e913a7ffc6c 100644
--- a/api/src/com/cloud/api/commands/DeleteTemplateCmd.java
+++ b/api/src/com/cloud/api/commands/DeleteTemplateCmd.java
@@ -75,7 +75,7 @@ public class DeleteTemplateCmd extends BaseAsyncCmd {
}
@Override
- public long getAccountId() {
+ public long getEntityOwnerId() {
VirtualMachineTemplate template = _entityMgr.findById(VirtualMachineTemplate.class, getId());
if (template != null) {
return template.getAccountId();
diff --git a/api/src/com/cloud/api/commands/DeleteUserCmd.java b/api/src/com/cloud/api/commands/DeleteUserCmd.java
index 31f43c9cb72..22a95a284fc 100644
--- a/api/src/com/cloud/api/commands/DeleteUserCmd.java
+++ b/api/src/com/cloud/api/commands/DeleteUserCmd.java
@@ -68,7 +68,7 @@ public class DeleteUserCmd extends BaseAsyncCmd {
}
@Override
- public long getAccountId() {
+ public long getEntityOwnerId() {
Account account = UserContext.current().getAccount();
if (account != null) {
return account.getId();
diff --git a/api/src/com/cloud/api/commands/DeployVMCmd.java b/api/src/com/cloud/api/commands/DeployVMCmd.java
index c1b4221c664..ac644975b9a 100644
--- a/api/src/com/cloud/api/commands/DeployVMCmd.java
+++ b/api/src/com/cloud/api/commands/DeployVMCmd.java
@@ -23,7 +23,7 @@ import java.util.List;
import org.apache.log4j.Logger;
import com.cloud.api.ApiConstants;
-import com.cloud.api.BaseAsyncCmd;
+import com.cloud.api.BaseAsyncCreateCmd;
import com.cloud.api.BaseCmd;
import com.cloud.api.Implementation;
import com.cloud.api.Parameter;
@@ -31,16 +31,15 @@ import com.cloud.api.ServerApiException;
import com.cloud.api.response.UserVmResponse;
import com.cloud.async.AsyncJob;
import com.cloud.event.EventTypes;
-import com.cloud.exception.InsufficientStorageCapacityException;
-import com.cloud.exception.ResourceAllocationException;
-import com.cloud.exception.StorageUnavailableException;
-import com.cloud.template.VirtualMachineTemplate;
+import com.cloud.exception.ConcurrentOperationException;
+import com.cloud.exception.InsufficientCapacityException;
+import com.cloud.exception.ResourceUnavailableException;
import com.cloud.user.Account;
import com.cloud.user.UserContext;
import com.cloud.uservm.UserVm;
@Implementation(description="Creates and automatically starts a virtual machine based on a service offering, disk offering, and template.", responseObject=UserVmResponse.class)
-public class DeployVMCmd extends BaseAsyncCmd {
+public class DeployVMCmd extends BaseAsyncCreateCmd {
public static final Logger s_logger = Logger.getLogger(DeployVMCmd.class.getName());
private static final String s_name = "deployvirtualmachineresponse";
@@ -175,7 +174,7 @@ public class DeployVMCmd extends BaseAsyncCmd {
}
@Override
- public long getAccountId() {
+ public long getEntityOwnerId() {
Account account = UserContext.current().getAccount();
if ((account == null) || isAdmin(account.getType())) {
if ((domainId != null) && (accountName != null)) {
@@ -203,41 +202,52 @@ public class DeployVMCmd extends BaseAsyncCmd {
return "deploying Vm";
}
+ @Override
public AsyncJob.Type getInstanceType() {
return AsyncJob.Type.VirtualMachine;
}
@Override
public void execute(){
+ UserVm result;
try {
- String password = null;
- if (templateId != null ) {
- VirtualMachineTemplate template = _responseGenerator.findTemplateById(templateId);
- if (template.getEnablePassword()) {
- password = _mgr.generateRandomPassword();
- }
- }
- UserVm result = _mgr.deployVirtualMachine(this, password);
- if (result != null){
- UserVmResponse response = _responseGenerator.createUserVmResponse(result);
+ result = _userVmService.startVirtualMachine(this);
+ if (result != null) {
+ UserVmResponse response = _responseGenerator.createUserVm2Response(result);
response.setPassword(password);
response.setResponseName(getName());
this.setResponseObject(response);
} else {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to deploy vm");
}
- } catch (ResourceAllocationException ex) {
- s_logger.warn("Exception: ", ex);
- throw new ServerApiException(BaseCmd.RESOURCE_ALLOCATION_ERROR, ex.getMessage());
- } catch (InsufficientStorageCapacityException ex) {
- s_logger.warn("Exception: ", ex);
+ } catch (ResourceUnavailableException ex) {
+ throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage());
+ } catch (ConcurrentOperationException ex) {
+ throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage());
+ } catch (InsufficientCapacityException ex) {
throw new ServerApiException(BaseCmd.INSUFFICIENT_CAPACITY_ERROR, ex.getMessage());
- } catch (StorageUnavailableException ex) {
+ }
+ }
+
+ @Override
+ public void create() {
+ try {
+ UserVm result = _userVmService.createVirtualMachine(this);
+ if (result != null){
+ setEntityId(result.getId());
+ } else {
+ throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to deploy vm");
+ }
+ } catch (InsufficientCapacityException ex) {
+ s_logger.info(ex);
+ s_logger.trace(ex);
+ throw new ServerApiException(BaseCmd.INSUFFICIENT_CAPACITY_ERROR, ex.getMessage());
+ } catch (ResourceUnavailableException ex) {
s_logger.warn("Exception: ", ex);
throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage());
- } catch (Exception ex) {
+ } catch (ConcurrentOperationException ex) {
s_logger.warn("Exception: ", ex);
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage());
- }
+ }
}
}
diff --git a/api/src/com/cloud/api/commands/DeployVm2Cmd.java b/api/src/com/cloud/api/commands/DeployVm2Cmd.java
deleted file mode 100644
index 91f3de0c93c..00000000000
--- a/api/src/com/cloud/api/commands/DeployVm2Cmd.java
+++ /dev/null
@@ -1,232 +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.api.commands;
-
-import java.util.List;
-
-import org.apache.log4j.Logger;
-
-import com.cloud.api.ApiConstants;
-import com.cloud.api.BaseAsyncCreateCmd;
-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.UserVmResponse;
-import com.cloud.event.EventTypes;
-import com.cloud.exception.ConcurrentOperationException;
-import com.cloud.exception.InsufficientCapacityException;
-import com.cloud.exception.ResourceUnavailableException;
-import com.cloud.user.Account;
-import com.cloud.user.UserContext;
-import com.cloud.uservm.UserVm;
-
-@Implementation(description="Creates and automatically starts a virtual machine based on a service offering, disk offering, and template.", responseObject=UserVmResponse.class)
-public class DeployVm2Cmd extends BaseAsyncCreateCmd {
- public static final Logger s_logger = Logger.getLogger(DeployVMCmd.class.getName());
-
- private static final String s_name = "deployvirtualmachineresponse";
-
- /////////////////////////////////////////////////////
- //////////////// API parameters /////////////////////
- /////////////////////////////////////////////////////
-
- @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="an optional account for the virtual machine. Must be used with domainId.")
- private String accountName;
-
- @Parameter(name=ApiConstants.DISK_OFFERING_ID, type=CommandType.LONG, description="the ID of the disk offering for the virtual machine. If the template is of ISO format, the diskOfferingId is for the root disk volume. Otherwise this parameter is used to dinidcate the offering for the data disk volume. If the templateId parameter passed is from a Template object, the diskOfferingId refers to a DATA Disk Volume created. If the templateId parameter passed is from an ISO object, the diskOfferingId refers to a ROOT Disk Volume created.")
- private Long diskOfferingId;
-
- @Parameter(name=ApiConstants.DISPLAY_NAME, type=CommandType.STRING, description="an optional user generated name for the virtual machine")
- private String displayName;
-
- @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="an optional domainId for the virtual machine. If the account parameter is used, domainId must also be used.")
- private Long domainId;
-
- @Parameter(name=ApiConstants.GROUP, type=CommandType.STRING, description="an optional group for the virtual machine")
- private String group;
-
- @Parameter(name=ApiConstants.HYPERVISOR, type=CommandType.STRING, description="the hypervisor on which to deploy the virtual machine")
- private String hypervisor;
-
- @Parameter(name=ApiConstants.NETWORK_GROUP_LIST, type=CommandType.LIST, collectionType=CommandType.STRING, description="comma separated list of network groups that going to be applied to the virtual machine. Should be passed only when vm is created from service offering with Direct Attach Network support")
- private List networkGroupList;
-
- @Parameter(name=ApiConstants.SERVICE_OFFERING_ID, type=CommandType.LONG, required=true, description="the ID of the service offering for the virtual machine")
- private Long serviceOfferingId;
-
- @Parameter(name=ApiConstants.SIZE, type=CommandType.LONG, description="the arbitrary size for the DATADISK volume. Mutually exclusive with diskOfferingId")
- private Long size;
-
- @Parameter(name=ApiConstants.TEMPLATE_ID, type=CommandType.LONG, required=true, description="the ID of the template for the virtual machine")
- private Long templateId;
-
- @Parameter(name=ApiConstants.USER_DATA, type=CommandType.STRING, description="an optional binary data that can be sent to the virtual machine upon a successful deployment. This binary data must be base64 encoded before adding it to the request. Currently only HTTP GET is supported. Using HTTP GET (via querystring), you can send up to 2KB of data after base64 encoding.")
- private String userData;
-
- @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required=true, description="availability zone for the virtual machine")
- private Long zoneId;
-
- // unexposed parameter needed for serializing/deserializing the command
- @Parameter(name=ApiConstants.PASSWORD, type=CommandType.STRING, expose=false)
- private String password;
-
- /////////////////////////////////////////////////////
- /////////////////// Accessors ///////////////////////
- /////////////////////////////////////////////////////
-
- public String getAccountName() {
- return accountName;
- }
-
- public Long getDiskOfferingId() {
- return diskOfferingId;
- }
-
- public String getDisplayName() {
- return displayName;
- }
-
- public Long getDomainId() {
- return domainId;
- }
-
- public String getGroup() {
- return group;
- }
-
- public String getHypervisor() {
- return hypervisor;
- }
-
- public List getNetworkGroupList() {
- return networkGroupList;
- }
-
- public Long getServiceOfferingId() {
- return serviceOfferingId;
- }
-
- public Long getSize() {
- return size;
- }
-
- public Long getTemplateId() {
- return templateId;
- }
-
- public String getUserData() {
- return userData;
- }
-
- public Long getZoneId() {
- return zoneId;
- }
-
- // not exposed parameter
- public String getPassword() {
- return password;
- }
-
- public void setPassword(String password) {
- this.password = password;
- }
-
- /////////////////////////////////////////////////////
- /////////////// API Implementation///////////////////
- /////////////////////////////////////////////////////
- @Override
- public void execute(){
- UserVm result;
- try {
- result = _userVmService.startVirtualMachine(this);
- if (result != null) {
- UserVmResponse response = _responseGenerator.createUserVm2Response(result);
- response.setPassword(password);
- response.setResponseName(getName());
- this.setResponseObject(response);
- } else {
- throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to deploy vm");
- }
- } catch (ResourceUnavailableException ex) {
- throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage());
- } catch (ConcurrentOperationException ex) {
- throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage());
- } catch (InsufficientCapacityException ex) {
- throw new ServerApiException(BaseCmd.INSUFFICIENT_CAPACITY_ERROR, ex.getMessage());
- }
- }
-
- @Override
- public void callCreate() {
-// try {
-// UserVm vm = _userVmService.createVirtualMachine(this);
-// if (vm != null) {
-// this.setId(vm.getId());
-// } else {
-// throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to deploy vm");
-// }
-// } catch (ResourceUnavailableException ex) {
-// throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage());
-// } catch (ConcurrentOperationException ex) {
-// throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage());
-// } catch (InsufficientCapacityException ex) {
-// throw new ServerApiException(BaseCmd.INSUFFICIENT_CAPACITY_ERROR, ex.getMessage());
-// }
- }
-
-
- @Override
- public String getName() {
- return s_name;
- }
-
- public static String getResultObjectName() {
- return "virtualmachine";
- }
-
- @Override
- public long getAccountId() {
- Account account = UserContext.current().getAccount();
- if ((account == null) || isAdmin(account.getType())) {
- if ((domainId != null) && (accountName != null)) {
- Account userAccount = _responseGenerator.findAccountByNameDomain(accountName, domainId);
- if (userAccount != null) {
- return userAccount.getId();
- }
- }
- }
-
- if (account != null) {
- return account.getId();
- }
-
- return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked
- }
-
- @Override
- public String getEventType() {
- return EventTypes.EVENT_VM_CREATE;
- }
-
- @Override
- public String getEventDescription() {
- return "deploying Vm";
- }
-}
diff --git a/api/src/com/cloud/api/commands/DestroyConsoleProxyCmd.java b/api/src/com/cloud/api/commands/DestroyConsoleProxyCmd.java
index beec58f76fa..a325c5d5082 100644
--- a/api/src/com/cloud/api/commands/DestroyConsoleProxyCmd.java
+++ b/api/src/com/cloud/api/commands/DestroyConsoleProxyCmd.java
@@ -64,7 +64,7 @@ public class DestroyConsoleProxyCmd extends BaseAsyncCmd {
}
@Override
- public long getAccountId() {
+ public long getEntityOwnerId() {
Account account = (Account)UserContext.current().getAccount();
if (account != null) {
return account.getId();
diff --git a/api/src/com/cloud/api/commands/DestroyVMCmd.java b/api/src/com/cloud/api/commands/DestroyVMCmd.java
index 08de8039a1e..2a877d0317b 100644
--- a/api/src/com/cloud/api/commands/DestroyVMCmd.java
+++ b/api/src/com/cloud/api/commands/DestroyVMCmd.java
@@ -64,7 +64,7 @@ public class DestroyVMCmd extends BaseAsyncCmd {
}
@Override
- public long getAccountId() {
+ public long getEntityOwnerId() {
UserVm vm = _responseGenerator.findUserVmById(getId());
if (vm != null) {
return vm.getAccountId();
diff --git a/api/src/com/cloud/api/commands/DetachIsoCmd.java b/api/src/com/cloud/api/commands/DetachIsoCmd.java
index 44b78ff4e8e..4e1bf6a9454 100755
--- a/api/src/com/cloud/api/commands/DetachIsoCmd.java
+++ b/api/src/com/cloud/api/commands/DetachIsoCmd.java
@@ -61,7 +61,7 @@ public class DetachIsoCmd extends BaseAsyncCmd {
}
@Override
- public long getAccountId() {
+ public long getEntityOwnerId() {
UserVm vm = _entityMgr.findById(UserVm.class, getVirtualMachineId());
if (vm != null) {
return vm.getAccountId();
diff --git a/api/src/com/cloud/api/commands/DetachVolumeCmd.java b/api/src/com/cloud/api/commands/DetachVolumeCmd.java
index 2509bc5ad27..0460dcfd82c 100755
--- a/api/src/com/cloud/api/commands/DetachVolumeCmd.java
+++ b/api/src/com/cloud/api/commands/DetachVolumeCmd.java
@@ -88,7 +88,7 @@ public class DetachVolumeCmd extends BaseAsyncCmd {
}
@Override
- public long getAccountId() {
+ public long getEntityOwnerId() {
Long volumeId = getId();
if (volumeId != null) {
Volume volume = _responseGenerator.findVolumeById(volumeId);
diff --git a/api/src/com/cloud/api/commands/DisableAccountCmd.java b/api/src/com/cloud/api/commands/DisableAccountCmd.java
index 2c2d669774b..6c4dca88a59 100644
--- a/api/src/com/cloud/api/commands/DisableAccountCmd.java
+++ b/api/src/com/cloud/api/commands/DisableAccountCmd.java
@@ -72,7 +72,7 @@ public class DisableAccountCmd extends BaseAsyncCmd {
}
@Override
- public long getAccountId() {
+ public long getEntityOwnerId() {
Account account = UserContext.current().getAccount();
if (account != null) {
return account.getId();
diff --git a/api/src/com/cloud/api/commands/DisableUserCmd.java b/api/src/com/cloud/api/commands/DisableUserCmd.java
index 5139250af69..9e76f6f085c 100644
--- a/api/src/com/cloud/api/commands/DisableUserCmd.java
+++ b/api/src/com/cloud/api/commands/DisableUserCmd.java
@@ -66,7 +66,7 @@ public class DisableUserCmd extends BaseAsyncCmd {
}
@Override
- public long getAccountId() {
+ public long getEntityOwnerId() {
Account account = UserContext.current().getAccount();
if (account != null) {
return account.getId();
diff --git a/api/src/com/cloud/api/commands/ExtractIsoCmd.java b/api/src/com/cloud/api/commands/ExtractIsoCmd.java
index 7e335357002..9c82c801e99 100755
--- a/api/src/com/cloud/api/commands/ExtractIsoCmd.java
+++ b/api/src/com/cloud/api/commands/ExtractIsoCmd.java
@@ -88,7 +88,7 @@ public class ExtractIsoCmd extends BaseAsyncCmd {
}
@Override
- public long getAccountId() {
+ public long getEntityOwnerId() {
VirtualMachineTemplate iso = _entityMgr.findById(VirtualMachineTemplate.class, getId());
if (iso != null) {
return iso.getAccountId();
@@ -120,7 +120,7 @@ public class ExtractIsoCmd extends BaseAsyncCmd {
try {
Long uploadId = _templateService.extract(this);
if (uploadId != null){
- ExtractResponse response = _responseGenerator.createExtractResponse(uploadId, id, zoneId, getAccountId(), mode);
+ ExtractResponse response = _responseGenerator.createExtractResponse(uploadId, id, zoneId, getEntityOwnerId(), mode);
response.setResponseName(getName());
response.setObjectName("iso");
this.setResponseObject(response);
diff --git a/api/src/com/cloud/api/commands/ExtractTemplateCmd.java b/api/src/com/cloud/api/commands/ExtractTemplateCmd.java
index 0c3f14ae143..211faba1abf 100755
--- a/api/src/com/cloud/api/commands/ExtractTemplateCmd.java
+++ b/api/src/com/cloud/api/commands/ExtractTemplateCmd.java
@@ -88,7 +88,7 @@ public class ExtractTemplateCmd extends BaseAsyncCmd {
}
@Override
- public long getAccountId() {
+ public long getEntityOwnerId() {
VirtualMachineTemplate template = _entityMgr.findById(VirtualMachineTemplate.class, getId());
if (template != null) {
return template.getAccountId();
@@ -121,7 +121,7 @@ public class ExtractTemplateCmd extends BaseAsyncCmd {
try {
Long uploadId = _templateService.extract(this);
if (uploadId != null){
- ExtractResponse response = _responseGenerator.createExtractResponse(uploadId, id, zoneId, getAccountId(), mode);
+ ExtractResponse response = _responseGenerator.createExtractResponse(uploadId, id, zoneId, getEntityOwnerId(), mode);
response.setResponseName(getName());
this.setResponseObject(response);
} else {
diff --git a/api/src/com/cloud/api/commands/ExtractVolumeCmd.java b/api/src/com/cloud/api/commands/ExtractVolumeCmd.java
index 7d116f6964a..6fc46176cb1 100755
--- a/api/src/com/cloud/api/commands/ExtractVolumeCmd.java
+++ b/api/src/com/cloud/api/commands/ExtractVolumeCmd.java
@@ -102,7 +102,7 @@ public class ExtractVolumeCmd extends BaseAsyncCmd {
}
@Override
- public long getAccountId() {
+ public long getEntityOwnerId() {
Volume volume = _entityMgr.findById(Volume.class, getId());
if (volume != null) {
return volume.getAccountId();
@@ -138,7 +138,7 @@ public class ExtractVolumeCmd extends BaseAsyncCmd {
response.setMode(mode);
response.setUploadId(uploadId);
response.setState(uploadInfo.getUploadState().toString());
- response.setAccountId(getAccountId());
+ response.setAccountId(getEntityOwnerId());
//FIX ME - Need to set the url once the gson jar is upgraded since it is throwing an error right now.
response.setUrl(uploadInfo.getUploadUrl().replaceAll("/", "%2F"));
this.setResponseObject(response);
diff --git a/api/src/com/cloud/api/commands/ListIpForwardingRulesCmd.java b/api/src/com/cloud/api/commands/ListIpForwardingRulesCmd.java
index a371a48c822..e481813be97 100644
--- a/api/src/com/cloud/api/commands/ListIpForwardingRulesCmd.java
+++ b/api/src/com/cloud/api/commands/ListIpForwardingRulesCmd.java
@@ -30,7 +30,8 @@ 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;
+import com.cloud.utils.net.Ip;
@Implementation(description="List the ip forwarding rules", responseObject=FirewallRuleResponse.class)
public class ListIpForwardingRulesCmd extends BaseListCmd {
@@ -82,10 +83,10 @@ public class ListIpForwardingRulesCmd extends BaseListCmd {
@Override
public void execute(){
- List extends FirewallRule> result = _mgr.searchForIpForwardingRules(this);
+ List extends PortForwardingRule> result = _rulesService.searchForIpForwardingRules(new Ip(publicIpAddress), this.getStartIndex(), this.getPageSizeVal());
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/ListNetworksCmd.java b/api/src/com/cloud/api/commands/ListNetworksCmd.java
index 4cb95e9516f..26d6927158b 100644
--- a/api/src/com/cloud/api/commands/ListNetworksCmd.java
+++ b/api/src/com/cloud/api/commands/ListNetworksCmd.java
@@ -27,6 +27,7 @@ import com.cloud.api.ApiConstants;
import com.cloud.api.BaseListCmd;
import com.cloud.api.Implementation;
import com.cloud.api.Parameter;
+import com.cloud.api.BaseCmd.CommandType;
import com.cloud.api.response.ListResponse;
import com.cloud.api.response.NetworkResponse;
import com.cloud.network.Network;
@@ -48,6 +49,9 @@ public class ListNetworksCmd extends BaseListCmd {
@Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="domain ID of the account owning a VLAN")
private Long domainId;
+
+ @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="the Zone ID of the network")
+ private Long zoneId;
/////////////////////////////////////////////////////
/////////////////// Accessors ///////////////////////
@@ -64,6 +68,11 @@ public class ListNetworksCmd extends BaseListCmd {
public Long getDomainId() {
return domainId;
}
+
+ public Long getZoneId() {
+ return zoneId;
+ }
+
/////////////////////////////////////////////////////
/////////////// API Implementation///////////////////
/////////////////////////////////////////////////////
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/ListStoragePoolsCmd.java b/api/src/com/cloud/api/commands/ListStoragePoolsCmd.java
index fc2375b8ac6..d52b1569a15 100644
--- a/api/src/com/cloud/api/commands/ListStoragePoolsCmd.java
+++ b/api/src/com/cloud/api/commands/ListStoragePoolsCmd.java
@@ -29,6 +29,7 @@ import com.cloud.api.Implementation;
import com.cloud.api.Parameter;
import com.cloud.api.response.ListResponse;
import com.cloud.api.response.StoragePoolResponse;
+import com.cloud.async.AsyncJob;
import com.cloud.storage.StoragePool;
@Implementation(description="Lists storage pools.", responseObject=StoragePoolResponse.class)
@@ -94,6 +95,10 @@ public class ListStoragePoolsCmd extends BaseListCmd {
@Override
public String getName() {
return s_name;
+ }
+
+ public AsyncJob.Type getInstanceType() {
+ return AsyncJob.Type.Host;
}
@Override
diff --git a/api/src/com/cloud/api/commands/ListVMsCmd.java b/api/src/com/cloud/api/commands/ListVMsCmd.java
index fcfab3b0f46..a40bf3802a1 100644
--- a/api/src/com/cloud/api/commands/ListVMsCmd.java
+++ b/api/src/com/cloud/api/commands/ListVMsCmd.java
@@ -70,6 +70,9 @@ public class ListVMsCmd extends BaseListCmd {
@Parameter(name=ApiConstants.FOR_VIRTUAL_NETWORK, type=CommandType.BOOLEAN, description="list by network type; true if need to list vms using Virtual Network, false otherwise")
private Boolean forVirtualNetwork;
+
+ @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.LONG, description="list by network id")
+ private Long networkId;
/////////////////////////////////////////////////////
/////////////////// Accessors ///////////////////////
@@ -118,6 +121,10 @@ public class ListVMsCmd extends BaseListCmd {
public void setForVirtualNetwork(Boolean forVirtualNetwork) {
this.forVirtualNetwork = forVirtualNetwork;
}
+
+ public Long getNetworkId() {
+ return networkId;
+ }
/////////////////////////////////////////////////////
/////////////// API Implementation///////////////////
diff --git a/api/src/com/cloud/api/commands/PrepareForMaintenanceCmd.java b/api/src/com/cloud/api/commands/PrepareForMaintenanceCmd.java
index 01a3d472b5c..36626f0a310 100644
--- a/api/src/com/cloud/api/commands/PrepareForMaintenanceCmd.java
+++ b/api/src/com/cloud/api/commands/PrepareForMaintenanceCmd.java
@@ -67,7 +67,7 @@ public class PrepareForMaintenanceCmd extends BaseAsyncCmd {
}
@Override
- public long getAccountId() {
+ public long getEntityOwnerId() {
Account account = UserContext.current().getAccount();
if (account != null) {
return account.getId();
diff --git a/api/src/com/cloud/api/commands/PreparePrimaryStorageForMaintenanceCmd.java b/api/src/com/cloud/api/commands/PreparePrimaryStorageForMaintenanceCmd.java
index 04e040e4d40..50c832aba13 100644
--- a/api/src/com/cloud/api/commands/PreparePrimaryStorageForMaintenanceCmd.java
+++ b/api/src/com/cloud/api/commands/PreparePrimaryStorageForMaintenanceCmd.java
@@ -26,6 +26,7 @@ import com.cloud.api.Implementation;
import com.cloud.api.Parameter;
import com.cloud.api.ServerApiException;
import com.cloud.api.response.StoragePoolResponse;
+import com.cloud.async.AsyncJob;
import com.cloud.event.EventTypes;
import com.cloud.storage.StoragePool;
import com.cloud.user.Account;
@@ -63,9 +64,17 @@ public class PreparePrimaryStorageForMaintenanceCmd extends BaseAsyncCmd {
public static String getResultObjectName() {
return "primarystorage";
}
+
+ public AsyncJob.Type getInstanceType() {
+ return AsyncJob.Type.Host;
+ }
+
+ public Long getInstanceId() {
+ return getId();
+ }
@Override
- public long getAccountId() {
+ public long getEntityOwnerId() {
Account account = UserContext.current().getAccount();
if (account != null) {
return account.getId();
diff --git a/api/src/com/cloud/api/commands/RebootRouterCmd.java b/api/src/com/cloud/api/commands/RebootRouterCmd.java
index ba74ae086a7..8d3230993db 100644
--- a/api/src/com/cloud/api/commands/RebootRouterCmd.java
+++ b/api/src/com/cloud/api/commands/RebootRouterCmd.java
@@ -62,7 +62,7 @@ public class RebootRouterCmd extends BaseAsyncCmd {
}
@Override
- public long getAccountId() {
+ public long getEntityOwnerId() {
VirtualRouter router = _entityMgr.findById(VirtualRouter.class, getId());
if (router != null) {
return router.getAccountId();
diff --git a/api/src/com/cloud/api/commands/RebootSystemVmCmd.java b/api/src/com/cloud/api/commands/RebootSystemVmCmd.java
index 815fdd024bf..b4ba6667a16 100644
--- a/api/src/com/cloud/api/commands/RebootSystemVmCmd.java
+++ b/api/src/com/cloud/api/commands/RebootSystemVmCmd.java
@@ -64,7 +64,7 @@ public class RebootSystemVmCmd extends BaseAsyncCmd {
}
@Override
- public long getAccountId() {
+ public long getEntityOwnerId() {
Account account = UserContext.current().getAccount();
if (account != null) {
return account.getId();
diff --git a/api/src/com/cloud/api/commands/RebootVMCmd.java b/api/src/com/cloud/api/commands/RebootVMCmd.java
index 1a08cb92047..1205634ed1d 100644
--- a/api/src/com/cloud/api/commands/RebootVMCmd.java
+++ b/api/src/com/cloud/api/commands/RebootVMCmd.java
@@ -61,7 +61,7 @@ public class RebootVMCmd extends BaseAsyncCmd {
}
@Override
- public long getAccountId() {
+ public long getEntityOwnerId() {
UserVm vm = _responseGenerator.findUserVmById(getId());
if (vm != null) {
return vm.getAccountId();
diff --git a/api/src/com/cloud/api/commands/ReconnectHostCmd.java b/api/src/com/cloud/api/commands/ReconnectHostCmd.java
index b6189d7286d..124670e6b09 100644
--- a/api/src/com/cloud/api/commands/ReconnectHostCmd.java
+++ b/api/src/com/cloud/api/commands/ReconnectHostCmd.java
@@ -69,7 +69,7 @@ public class ReconnectHostCmd extends BaseAsyncCmd {
}
@Override
- public long getAccountId() {
+ public long getEntityOwnerId() {
Account account = UserContext.current().getAccount();
if (account != null) {
return account.getId();
diff --git a/api/src/com/cloud/api/commands/RemoveFromLoadBalancerRuleCmd.java b/api/src/com/cloud/api/commands/RemoveFromLoadBalancerRuleCmd.java
index b5ab094b8ca..7fc4dd8a890 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;
@@ -79,7 +80,7 @@ public class RemoveFromLoadBalancerRuleCmd extends BaseAsyncCmd {
}
@Override
- public long getAccountId() {
+ public long getEntityOwnerId() {
LoadBalancer lb = _entityMgr.findById(LoadBalancer.class, getId());
if (lb == null) {
return Account.ACCOUNT_ID_SYSTEM; // bad id given, parent this command to SYSTEM so ERROR events are tracked
@@ -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/RemoveVpnUserCmd.java b/api/src/com/cloud/api/commands/RemoveVpnUserCmd.java
index b9c71639e76..125ce75ff8f 100644
--- a/api/src/com/cloud/api/commands/RemoveVpnUserCmd.java
+++ b/api/src/com/cloud/api/commands/RemoveVpnUserCmd.java
@@ -81,7 +81,7 @@ public class RemoveVpnUserCmd extends BaseAsyncCmd {
}
@Override
- public long getAccountId() {
+ public long getEntityOwnerId() {
Account account = UserContext.current().getAccount();
if ((account == null) || isAdmin(account.getType())) {
if ((domainId != null) && (accountName != null)) {
@@ -101,7 +101,7 @@ public class RemoveVpnUserCmd extends BaseAsyncCmd {
@Override
public String getEventDescription() {
- return "Remove Remote Access VPN user for account " + getAccountId() + " username= " + getUserName();
+ return "Remove Remote Access VPN user for account " + getEntityOwnerId() + " username= " + getUserName();
}
diff --git a/api/src/com/cloud/api/commands/ResetVMPasswordCmd.java b/api/src/com/cloud/api/commands/ResetVMPasswordCmd.java
index c84e045b658..32e73d726e0 100644
--- a/api/src/com/cloud/api/commands/ResetVMPasswordCmd.java
+++ b/api/src/com/cloud/api/commands/ResetVMPasswordCmd.java
@@ -78,7 +78,7 @@ public class ResetVMPasswordCmd extends BaseAsyncCmd {
}
@Override
- public long getAccountId() {
+ public long getEntityOwnerId() {
UserVm vm = _responseGenerator.findUserVmById(getId());
if (vm != null) {
return vm.getAccountId();
diff --git a/api/src/com/cloud/api/commands/RevokeNetworkGroupIngressCmd.java b/api/src/com/cloud/api/commands/RevokeNetworkGroupIngressCmd.java
index 28def4b8c33..c105f3ade59 100644
--- a/api/src/com/cloud/api/commands/RevokeNetworkGroupIngressCmd.java
+++ b/api/src/com/cloud/api/commands/RevokeNetworkGroupIngressCmd.java
@@ -127,7 +127,7 @@ public class RevokeNetworkGroupIngressCmd extends BaseAsyncCmd {
}
@Override
- public long getAccountId() {
+ public long getEntityOwnerId() {
Account account = UserContext.current().getAccount();
if ((account == null) || isAdmin(account.getType())) {
if ((domainId != null) && (accountName != null)) {
diff --git a/api/src/com/cloud/api/commands/StartRouterCmd.java b/api/src/com/cloud/api/commands/StartRouterCmd.java
index e30d6d16a2a..0d09f76c6ed 100644
--- a/api/src/com/cloud/api/commands/StartRouterCmd.java
+++ b/api/src/com/cloud/api/commands/StartRouterCmd.java
@@ -72,7 +72,7 @@ public class StartRouterCmd extends BaseAsyncCmd {
}
@Override
- public long getAccountId() {
+ public long getEntityOwnerId() {
UserVm vm = _entityMgr.findById(UserVm.class, getId());
if (vm != null) {
return vm.getAccountId();
diff --git a/api/src/com/cloud/api/commands/StartSystemVMCmd.java b/api/src/com/cloud/api/commands/StartSystemVMCmd.java
index 11b5fb5f8f7..456db974442 100644
--- a/api/src/com/cloud/api/commands/StartSystemVMCmd.java
+++ b/api/src/com/cloud/api/commands/StartSystemVMCmd.java
@@ -68,7 +68,7 @@ public class StartSystemVMCmd extends BaseAsyncCmd {
}
@Override
- public long getAccountId() {
+ public long getEntityOwnerId() {
Account account = UserContext.current().getAccount();
if (account != null) {
return account.getId();
diff --git a/api/src/com/cloud/api/commands/StartVMCmd.java b/api/src/com/cloud/api/commands/StartVMCmd.java
index e1ea9c54649..cacef59582f 100644
--- a/api/src/com/cloud/api/commands/StartVMCmd.java
+++ b/api/src/com/cloud/api/commands/StartVMCmd.java
@@ -71,7 +71,7 @@ public class StartVMCmd extends BaseAsyncCmd {
}
@Override
- public long getAccountId() {
+ public long getEntityOwnerId() {
UserVm vm = _responseGenerator.findUserVmById(getId());
if (vm != null) {
return vm.getAccountId();
diff --git a/api/src/com/cloud/api/commands/StopRouterCmd.java b/api/src/com/cloud/api/commands/StopRouterCmd.java
index cba1afa0166..ade73cd4607 100644
--- a/api/src/com/cloud/api/commands/StopRouterCmd.java
+++ b/api/src/com/cloud/api/commands/StopRouterCmd.java
@@ -66,7 +66,7 @@ public class StopRouterCmd extends BaseAsyncCmd {
}
@Override
- public long getAccountId() {
+ public long getEntityOwnerId() {
UserVm vm = _entityMgr.findById(UserVm.class, getId());
if (vm != null) {
return vm.getAccountId();
diff --git a/api/src/com/cloud/api/commands/StopSystemVmCmd.java b/api/src/com/cloud/api/commands/StopSystemVmCmd.java
index d7544a9e847..b2869b538ad 100644
--- a/api/src/com/cloud/api/commands/StopSystemVmCmd.java
+++ b/api/src/com/cloud/api/commands/StopSystemVmCmd.java
@@ -64,7 +64,7 @@ public class StopSystemVmCmd extends BaseAsyncCmd {
}
@Override
- public long getAccountId() {
+ public long getEntityOwnerId() {
Account account = UserContext.current().getAccount();
if (account != null) {
return account.getId();
diff --git a/api/src/com/cloud/api/commands/StopVMCmd.java b/api/src/com/cloud/api/commands/StopVMCmd.java
index 58ea501311f..7493384d815 100644
--- a/api/src/com/cloud/api/commands/StopVMCmd.java
+++ b/api/src/com/cloud/api/commands/StopVMCmd.java
@@ -67,7 +67,7 @@ public class StopVMCmd extends BaseAsyncCmd {
}
@Override
- public long getAccountId() {
+ public long getEntityOwnerId() {
UserVm vm = _responseGenerator.findUserVmById(getId());
if (vm != null) {
return vm.getAccountId();
diff --git a/api/src/com/cloud/api/commands/UpdateLoadBalancerRuleCmd.java b/api/src/com/cloud/api/commands/UpdateLoadBalancerRuleCmd.java
index 35c0b3c4799..ef8575095a7 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)
@@ -88,7 +88,7 @@ public class UpdateLoadBalancerRuleCmd extends BaseAsyncCmd {
}
@Override
- public long getAccountId() {
+ public long getEntityOwnerId() {
LoadBalancer lb = _entityMgr.findById(LoadBalancer.class, getId());
if (lb == null) {
return Account.ACCOUNT_ID_SYSTEM; // bad id given, parent this command to SYSTEM so ERROR events are tracked
@@ -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..610f34d4e62 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.")
@@ -79,10 +76,10 @@ public class UpdatePortForwardingRuleCmd extends BaseAsyncCmd {
}
@Override
- public long getAccountId() {
+ public long getEntityOwnerId() {
IpAddress addr = _entityMgr.findById(IpAddress.class, getPublicIp());
if (addr != null) {
- return addr.getAccountId();
+ return addr.getAllocatedToAccountId();
}
// bad address given, parent this command to SYSTEM so ERROR events are tracked
@@ -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/api/commands/UploadCustomCertificateCmd.java b/api/src/com/cloud/api/commands/UploadCustomCertificateCmd.java
index a968f6735cd..37cf90186e2 100644
--- a/api/src/com/cloud/api/commands/UploadCustomCertificateCmd.java
+++ b/api/src/com/cloud/api/commands/UploadCustomCertificateCmd.java
@@ -62,7 +62,7 @@ public class UploadCustomCertificateCmd extends BaseAsyncCmd {
}
@Override
- public long getAccountId() {
+ public long getEntityOwnerId() {
return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked
}
diff --git a/api/src/com/cloud/api/response/NetworkOfferingResponse.java b/api/src/com/cloud/api/response/NetworkOfferingResponse.java
index ded3bc6775f..05eef83820d 100644
--- a/api/src/com/cloud/api/response/NetworkOfferingResponse.java
+++ b/api/src/com/cloud/api/response/NetworkOfferingResponse.java
@@ -32,10 +32,7 @@ public class NetworkOfferingResponse extends BaseResponse{
@SerializedName("isdefault") @Param(description="true if network offering is default, false otherwise")
private Boolean isDefault;
-
- @SerializedName("isshared") @Param(description="true if network offering is shared, false otherwise")
- private Boolean isShared;
-
+
@SerializedName("specifyvlan") @Param(description="true if network offering supports vlans, false otherwise")
private Boolean specifyVlan;
@@ -126,12 +123,4 @@ public class NetworkOfferingResponse extends BaseResponse{
public void setSpecifyVlan(Boolean specifyVlan) {
this.specifyVlan = specifyVlan;
}
-
- public Boolean getIsShared() {
- return isShared;
- }
-
- public void setIsShared(Boolean isShared) {
- this.isShared = isShared;
- }
}
diff --git a/api/src/com/cloud/api/response/NetworkResponse.java b/api/src/com/cloud/api/response/NetworkResponse.java
index 8da95663ac0..753fa16ccd7 100644
--- a/api/src/com/cloud/api/response/NetworkResponse.java
+++ b/api/src/com/cloud/api/response/NetworkResponse.java
@@ -47,6 +47,13 @@ public class NetworkResponse extends BaseResponse{
@SerializedName("networkofferingdisplaytext")
private String networkOfferingDisplayText;
+ //TODO - add description
+ @SerializedName("isshared")
+ private Boolean isShared;
+
+ @SerializedName("isdefault") @Param(description="true if network offering is default, false otherwise")
+ private Boolean isDefault;
+
//TODO - add description
@SerializedName("state")
private String state;
@@ -228,4 +235,12 @@ public class NetworkResponse extends BaseResponse{
public void setDisplaytext(String displaytext) {
this.displaytext = displaytext;
}
+
+ public Boolean getIsShared() {
+ return isShared;
+ }
+
+ public void setIsShared(Boolean isShared) {
+ this.isShared = isShared;
+ }
}
diff --git a/api/src/com/cloud/api/response/ServiceOfferingResponse.java b/api/src/com/cloud/api/response/ServiceOfferingResponse.java
index 5eb505f6708..cb3e9da7c10 100644
--- a/api/src/com/cloud/api/response/ServiceOfferingResponse.java
+++ b/api/src/com/cloud/api/response/ServiceOfferingResponse.java
@@ -57,7 +57,7 @@ public class ServiceOfferingResponse extends BaseResponse {
@SerializedName("tags") @Param(description="the tags for the service offering")
private String tags;
- @SerializedName("domainId") @Param(description="the domain id of the service offering")
+ @SerializedName("domainid") @Param(description="the domain id of the service offering")
private Long domainId;
@SerializedName(ApiConstants.DOMAIN) @Param(description="Domain name for the offering")
diff --git a/api/src/com/cloud/capacity/Capacity.java b/api/src/com/cloud/capacity/Capacity.java
index a9df7342ab1..e821a71a5fe 100644
--- a/api/src/com/cloud/capacity/Capacity.java
+++ b/api/src/com/cloud/capacity/Capacity.java
@@ -39,5 +39,7 @@ public interface Capacity {
public long getTotalCapacity();
public short getCapacityType();
+ long getReservedCapacity();
+
}
diff --git a/api/src/com/cloud/deploy/DeploymentPlanner.java b/api/src/com/cloud/deploy/DeploymentPlanner.java
index 915e56b97f1..668b6952f6a 100644
--- a/api/src/com/cloud/deploy/DeploymentPlanner.java
+++ b/api/src/com/cloud/deploy/DeploymentPlanner.java
@@ -121,5 +121,32 @@ public interface DeploymentPlanner extends Adapter {
return false;
}
+
+ public boolean shouldAvoid(Cluster cluster) {
+ if (_dcIds != null && _dcIds.contains(cluster.getDataCenterId())) {
+ return true;
+ }
+
+ if (_podIds != null && _podIds.contains(cluster.getPodId())) {
+ return true;
+ }
+
+ if (_clusterIds != null && _clusterIds.contains(cluster.getId())) {
+ return true;
+ }
+ return false;
+ }
+
+ public boolean shouldAvoid(Pod pod) {
+ if (_dcIds != null && _dcIds.contains(pod.getDataCenterId())) {
+ return true;
+ }
+
+ if (_podIds != null && _podIds.contains(pod.getId())) {
+ return true;
+ }
+
+ return false;
+ }
}
}
diff --git a/api/src/com/cloud/network/IpAddress.java b/api/src/com/cloud/network/IpAddress.java
index c352a273af0..8cb87a00862 100644
--- a/api/src/com/cloud/network/IpAddress.java
+++ b/api/src/com/cloud/network/IpAddress.java
@@ -19,30 +19,48 @@ package com.cloud.network;
import java.util.Date;
-public interface IpAddress {
+import com.cloud.acl.ControlledEntity;
+
+/**
+ * IpAddress represents the public ip address to be allocated in the CloudStack.
+ *
+ * When it is not allocated, it should have
+ * - State = Free
+ * - Allocated = null
+ * - AccountId = null
+ * - DomainId = null
+ *
+ * When it is allocated, it should have
+ * - State = Allocated
+ * - AccountId = account owner.
+ * - DomainId = domain of the account owner.
+ * - Allocated = time it was allocated.
+ */
+public interface IpAddress extends ControlledEntity {
+ enum State {
+ Allocating, // The IP Address is being propagated to other network elements and is not ready for use yet.
+ Allocated, // The IP address is in used.
+ Releasing, // The IP address is being released for other network elements and is not ready for allocation.
+ Free // The IP address is ready to be allocated.
+ }
+
long getDataCenterId();
String getAddress();
- Long getAccountId();
- Long getDomainId();
- Date getAllocated();
+
+ Long getAllocatedToAccountId();
+
+ Long getAllocatedInDomainId();
+
+ Date getAllocatedTime();
+
boolean isSourceNat();
- void setAccountId(Long accountId);
-
- void setDomainId(Long domainId);
-
- void setSourceNat(boolean sourceNat);
-
- boolean getSourceNat();
-
- void setAllocated(Date allocated);
-
- long getVlanDbId();
-
- void setVlanDbId(long vlanDbId);
+ long getVlanId();
boolean isOneToOneNat();
-
- void setOneToOneNat(boolean oneToOneNat);
+
+ State getState();
+
+ boolean readyToUse();
}
diff --git a/api/src/com/cloud/network/Network.java b/api/src/com/cloud/network/Network.java
index d00f4d616d3..a27843358a2 100644
--- a/api/src/com/cloud/network/Network.java
+++ b/api/src/com/cloud/network/Network.java
@@ -110,4 +110,6 @@ public interface Network extends ControlledEntity {
GuestIpType getGuestType();
String getDisplayText();
+
+ boolean isShared();
}
diff --git a/api/src/com/cloud/network/NetworkService.java b/api/src/com/cloud/network/NetworkService.java
index 04ad345671f..4d7357b4b69 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,35 +47,26 @@ 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);
+ boolean disassociateIpAddress(DisassociateIPAddrCmd cmd);
/**
- * Create a remote access vpn from the given public ip address and client ip range
+ * Create a remote access vpn from the given ip address and client ip range
* @param cmd the command specifying the ip address, ip range
* @return the newly created RemoteAccessVpnVO if successful, null otherwise
* @throws InvalidParameterValueException
* @throws PermissionDeniedException
* @throws ConcurrentOperationException
*/
- public RemoteAccessVpn createRemoteAccessVpn(CreateRemoteAccessVpnCmd cmd) throws ConcurrentOperationException, InvalidParameterValueException, PermissionDeniedException;
+ RemoteAccessVpn createRemoteAccessVpn(CreateRemoteAccessVpnCmd cmd) throws ConcurrentOperationException, InvalidParameterValueException, PermissionDeniedException;
/**
- * Start a remote access vpn for the given public ip address and client ip range
+ * Start a remote access vpn for the given ip address and client ip range
* @param cmd the command specifying the ip address, ip range
* @return the RemoteAccessVpnVO if successful, null otherwise
* @throws ConcurrentOperationException
* @throws ResourceUnavailableException
*/
- public RemoteAccessVpn startRemoteAccessVpn(CreateRemoteAccessVpnCmd cmd) throws ConcurrentOperationException, ResourceUnavailableException;
+ RemoteAccessVpn startRemoteAccessVpn(CreateRemoteAccessVpnCmd cmd) throws ConcurrentOperationException, ResourceUnavailableException;
/**
* Destroy a previously created remote access VPN
@@ -92,40 +74,12 @@ public interface NetworkService {
* @return success if successful, false otherwise
* @throws ConcurrentOperationException
*/
- public boolean destroyRemoteAccessVpn(DeleteRemoteAccessVpnCmd cmd) throws ConcurrentOperationException;
+ boolean destroyRemoteAccessVpn(DeleteRemoteAccessVpnCmd cmd) throws ConcurrentOperationException;
VpnUser addVpnUser(AddVpnUserCmd cmd) throws ConcurrentOperationException, AccountLimitException;
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..fb620a7babf 100644
--- a/api/src/com/cloud/network/element/NetworkElement.java
+++ b/api/src/com/cloud/network/element/NetworkElement.java
@@ -3,14 +3,18 @@
*/
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.utils.net.Ip;
import com.cloud.vm.NicProfile;
import com.cloud.vm.ReservationContext;
import com.cloud.vm.VirtualMachine;
@@ -26,15 +30,68 @@ 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;
+ /**
+ * Prepare for a nic to be added into this network.
+ * @param network
+ * @param nic
+ * @param vm
+ * @param dest
+ * @param context
+ * @return
+ * @throws ConcurrentOperationException
+ * @throws ResourceUnavailableException
+ * @throws 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;
+ /**
+ * A nic is released from this network.
+ * @param network
+ * @param nic
+ * @param vm
+ * @param context
+ * @return
+ * @throws ConcurrentOperationException
+ * @throws 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;
+ /**
+ * The network is being shutdown.
+ * @param network
+ * @param context
+ * @return
+ * @throws ConcurrentOperationException
+ * @throws ResourceUnavailableException
+ */
+ boolean shutdown(Network network, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException;
+
+ /**
+ * Associate a new ip address to this network
+ * @param network
+ * @param ipAddress
+ * @return
+ * @throws ResourceUnavailableException
+ */
+ boolean associate(Network network, Ip ipAddress) throws ResourceUnavailableException;
+
+ /**
+ * Disassociate the ip address from this network
+ * @param network
+ * @param ipAddress
+ * @return
+ * @throws ResourceUnavailableException
+ */
+ boolean disassociate(Network network, Ip ipAddress) throws ResourceUnavailableException;
- boolean addRule();
-
- boolean revokeRule();
+ /**
+ * Apply rules
+ * @param network
+ * @param rules
+ * @return
+ * @throws ResourceUnavailableException
+ */
+ 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..71420ff9235 100644
--- a/api/src/com/cloud/network/rules/FirewallRule.java
+++ b/api/src/com/cloud/network/rules/FirewallRule.java
@@ -17,10 +17,23 @@
*/
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 {
+ Firewall,
+ 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 +47,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..f9d48bf618e
--- /dev/null
+++ b/api/src/com/cloud/network/rules/RulesService.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.network.rules;
+
+import java.util.List;
+
+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(Ip ip, Long start, Long size);
+
+ /**
+ * 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.
+ * @return PortForwardingRule if created.
+ * @throws NetworkRuleConflictException if conflicts in the network rules are detected.
+ */
+ PortForwardingRule createPortForwardingRule(PortForwardingRule rule, Long vmId) 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);
+ /**
+ * 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);
+
+ boolean applyPortForwardingRules(Ip ip, Account caller) throws ResourceUnavailableException;
+}
diff --git a/api/src/com/cloud/offering/NetworkOffering.java b/api/src/com/cloud/offering/NetworkOffering.java
index 10ce22ad873..3e937dad2e9 100644
--- a/api/src/com/cloud/offering/NetworkOffering.java
+++ b/api/src/com/cloud/offering/NetworkOffering.java
@@ -26,9 +26,8 @@ import com.cloud.network.Networks.TrafficType;
public interface NetworkOffering {
public enum GuestIpType {
- Virtualized,
- DirectSingle,
- DirectDual
+ Virtual,
+ Direct,
}
public final String DefaultVirtualizedNetworkOffering = "DefaultVirtualizedNetworkOffering";
@@ -73,7 +72,5 @@ public interface NetworkOffering {
String getTags();
- boolean isShared();
-
boolean isDefault();
}
diff --git a/api/src/com/cloud/server/ManagementService.java b/api/src/com/cloud/server/ManagementService.java
index 4ebb4769926..ebb3cdc97a0 100644
--- a/api/src/com/cloud/server/ManagementService.java
+++ b/api/src/com/cloud/server/ManagementService.java
@@ -27,7 +27,6 @@ import com.cloud.api.ServerApiException;
import com.cloud.api.commands.CreateDomainCmd;
import com.cloud.api.commands.DeleteDomainCmd;
import com.cloud.api.commands.DeletePreallocatedLunCmd;
-import com.cloud.api.commands.DeployVMCmd;
import com.cloud.api.commands.ExtractVolumeCmd;
import com.cloud.api.commands.GetCloudIdentifierCmd;
import com.cloud.api.commands.ListAccountsCmd;
@@ -45,17 +44,13 @@ 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;
import com.cloud.api.commands.ListRemoteAccessVpnsCmd;
import com.cloud.api.commands.ListRoutersCmd;
import com.cloud.api.commands.ListServiceOfferingsCmd;
-import com.cloud.api.commands.ListSnapshotsCmd;
import com.cloud.api.commands.ListStoragePoolsCmd;
import com.cloud.api.commands.ListSystemVMsCmd;
import com.cloud.api.commands.ListTemplateOrIsoPermissionsCmd;
@@ -75,7 +70,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;
@@ -88,35 +82,25 @@ import com.cloud.dc.Pod;
import com.cloud.dc.Vlan;
import com.cloud.domain.Domain;
import com.cloud.event.Event;
-import com.cloud.exception.ConcurrentOperationException;
-import com.cloud.exception.InsufficientCapacityException;
-import com.cloud.exception.InsufficientStorageCapacityException;
import com.cloud.exception.InternalErrorException;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.PermissionDeniedException;
-import com.cloud.exception.ResourceAllocationException;
-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;
import com.cloud.storage.GuestOS;
import com.cloud.storage.GuestOsCategory;
-import com.cloud.storage.Snapshot;
import com.cloud.storage.StoragePool;
import com.cloud.storage.Volume;
import com.cloud.template.VirtualMachineTemplate;
import com.cloud.user.Account;
import com.cloud.user.UserAccount;
import com.cloud.uservm.UserVm;
-import com.cloud.utils.exception.ExecutionException;
import com.cloud.vm.InstanceGroup;
import com.cloud.vm.VirtualMachine;
@@ -127,30 +111,6 @@ import com.cloud.vm.VirtualMachine;
public interface ManagementService {
static final String Name = "management-server";
- /**
- * Creates and starts a new Virtual Machine.
- *
- * @param cmd the command with the deployment parameters
- * - userId
- * - accountId
- * - zoneId
- * - serviceOfferingId
- * - templateId: the id of the template (or ISO) to use for creating the virtual machine
- * - diskOfferingId: ID of the disk offering to use when creating the root disk (if deploying from an ISO) or the data disk (if deploying from a template). If deploying from a template and a disk offering ID is not passed in, the VM will have only a root disk.
- * - displayName: user-supplied name to be shown in the UI or returned in the API
- * - groupName: user-supplied groupname to be shown in the UI or returned in the API
- * - userData: user-supplied base64-encoded data that can be retrieved by the instance from the virtual router
- * - size: size to be used for volume creation in case the disk offering is private (i.e. size=0)
- * @return VirtualMachine if successfully deployed, null otherwise
- * @throws InvalidParameterValueException if the parameter values are incorrect.
- * @throws ExecutionException
- * @throws StorageUnavailableException
- * @throws ConcurrentOperationException
- * @throws ResourceUnavailableException
- * @throws InsufficientCapacityException
- */
- UserVm deployVirtualMachine(DeployVMCmd cmd, String password) throws ResourceAllocationException, InsufficientStorageCapacityException, ExecutionException, StorageUnavailableException, ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException;
-
/**
* Retrieves the list of data centers with search criteria.
* Currently the only search criteria is "available" zones for the account that invokes the API. By specifying
@@ -222,13 +182,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 +325,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 +387,6 @@ public interface ManagementService {
public List extends VpnUser> searchForVpnUsers(ListVpnUsersCmd cmd);
- List extends FirewallRule> searchForIpForwardingRules(ListIpForwardingRulesCmd cmd);
-
String getVersion();
/**
@@ -480,6 +416,4 @@ public interface ManagementService {
*/
boolean unregisterPreallocatedLun(DeletePreallocatedLunCmd cmd) throws IllegalArgumentException;
-
-
}
diff --git a/api/src/com/cloud/storage/Volume.java b/api/src/com/cloud/storage/Volume.java
index 330b2820bb4..49447543832 100755
--- a/api/src/com/cloud/storage/Volume.java
+++ b/api/src/com/cloud/storage/Volume.java
@@ -161,4 +161,6 @@ public interface Volume extends ControlledEntity, BasedOn {
boolean getDestroyed();
long getDiskOfferingId();
+
+ String getChainInfo();
}
diff --git a/api/src/com/cloud/vm/State.java b/api/src/com/cloud/vm/State.java
index c024ff270b9..00bcb8e2863 100644
--- a/api/src/com/cloud/vm/State.java
+++ b/api/src/com/cloud/vm/State.java
@@ -99,6 +99,8 @@ public enum State implements FiniteState {
s_fsm.addTransition(State.Migrating, VirtualMachine.Event.MigrationRequested, State.Migrating);
s_fsm.addTransition(State.Migrating, VirtualMachine.Event.OperationSucceeded, State.Running);
s_fsm.addTransition(State.Migrating, VirtualMachine.Event.OperationFailed, State.Running);
+ s_fsm.addTransition(State.Migrating, VirtualMachine.Event.MigrationFailedOnSource, State.Running);
+ s_fsm.addTransition(State.Migrating, VirtualMachine.Event.MigrationFailedOnDest, State.Running);
s_fsm.addTransition(State.Migrating, VirtualMachine.Event.AgentReportRunning, State.Running);
s_fsm.addTransition(State.Migrating, VirtualMachine.Event.AgentReportStopped, State.Stopped);
s_fsm.addTransition(State.Stopping, VirtualMachine.Event.OperationSucceeded, State.Stopped);
diff --git a/api/src/com/cloud/vm/UserVmService.java b/api/src/com/cloud/vm/UserVmService.java
index 1d32258c9d2..bc73f6a4d3f 100755
--- a/api/src/com/cloud/vm/UserVmService.java
+++ b/api/src/com/cloud/vm/UserVmService.java
@@ -23,7 +23,6 @@ import com.cloud.api.commands.CreateTemplateCmd;
import com.cloud.api.commands.CreateVMGroupCmd;
import com.cloud.api.commands.DeleteVMGroupCmd;
import com.cloud.api.commands.DeployVMCmd;
-import com.cloud.api.commands.DeployVm2Cmd;
import com.cloud.api.commands.DestroyVMCmd;
import com.cloud.api.commands.DetachVolumeCmd;
import com.cloud.api.commands.RebootVMCmd;
@@ -133,7 +132,7 @@ public interface UserVmService {
* @throws ConcurrentOperationException if there are multiple users working on the same VM.
* @throws ResourceUnavailableException if the resources required the deploy the VM is not currently available.
*/
- UserVm startVirtualMachine(DeployVm2Cmd cmd) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException;
+ UserVm startVirtualMachine(DeployVMCmd cmd) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException;
/**
* Creates a vm group.
diff --git a/api/src/com/cloud/vm/VirtualMachine.java b/api/src/com/cloud/vm/VirtualMachine.java
index 4e1f23f985a..538a6fb5db5 100755
--- a/api/src/com/cloud/vm/VirtualMachine.java
+++ b/api/src/com/cloud/vm/VirtualMachine.java
@@ -38,6 +38,8 @@ public interface VirtualMachine extends RunningOn, ControlledEntity {
ExpungeOperation,
OperationSucceeded,
OperationFailed,
+ MigrationFailedOnSource,
+ MigrationFailedOnDest,
OperationRetry,
OperationCancelled
};
diff --git a/client/tomcatconf/commands.properties.in b/client/tomcatconf/commands.properties.in
index 709d78b795b..9ba071ca1ef 100755
--- a/client/tomcatconf/commands.properties.in
+++ b/client/tomcatconf/commands.properties.in
@@ -237,6 +237,6 @@ deleteNetworkOffering=com.cloud.api.commands.DeleteNetworkOfferingCmd;1
listNetworkOfferings=com.cloud.api.commands.ListNetworkOfferingsCmd;15
#### network commands
-createNetwork=com.cloud.api.commands.CreateNetworkCmd;1
-deleteNetwork=com.cloud.api.commands.DeleteNetworkCmd;1
+createNetwork=com.cloud.api.commands.CreateNetworkCmd;15
+deleteNetwork=com.cloud.api.commands.DeleteNetworkCmd;15
listNetworks=com.cloud.api.commands.ListNetworksCmd;15
\ No newline at end of file
diff --git a/client/tomcatconf/components.xml.in b/client/tomcatconf/components.xml.in
index 71461e0e30f..b539293635f 100755
--- a/client/tomcatconf/components.xml.in
+++ b/client/tomcatconf/components.xml.in
@@ -72,7 +72,7 @@
-
+
diff --git a/client/wscript_build b/client/wscript_build
deleted file mode 100644
index 2cc94177383..00000000000
--- a/client/wscript_build
+++ /dev/null
@@ -1,13 +0,0 @@
-import Options
-
-start_path = bld.path.find_dir("WEB-INF")
-bld.install_files('${MSENVIRON}/webapps/client/WEB-INF',
- start_path.ant_glob("**",src=True,bld=False,dir=False,flat=True),
- cwd=start_path,relative_trick=True)
-
-bld.install_files("${MSCONF}/resources",'WEB-INF/classes/resources/*.properties',chmod=0640)
-
-if not Options.options.PRESERVECONFIG:
- bld.install_files_filtered("${MSCONF}","tomcatconf/*")
- bld.install_files("${MSCONF}",'tomcatconf/db.properties',chmod=0640)
- bld.setownership("${MSCONF}/db.properties","root",bld.env.MSUSER)
diff --git a/cloud.spec b/cloud.spec
index 8a2afd21e86..62f4a08ac72 100644
--- a/cloud.spec
+++ b/cloud.spec
@@ -347,7 +347,7 @@ echo Doing open source build
%clean
-[ ${RPM_BUILD_ROOT} != "/" ] && rm -rf ${RPM_BUILD_ROOT}
+#[ ${RPM_BUILD_ROOT} != "/" ] && rm -rf ${RPM_BUILD_ROOT}
%preun client
@@ -451,16 +451,6 @@ fi
%defattr(-,root,root,-)
%{_libdir}/%{name}/agent/scripts/*
# maintain the following list in sync with files agent-scripts
-%if %{_premium}
-%exclude %{_libdir}/%{name}/agent/scripts/vm/hypervisor/xenserver/check_heartbeat.sh
-%exclude %{_libdir}/%{name}/agent/scripts/vm/hypervisor/xenserver/find_bond.sh
-%exclude %{_libdir}/%{name}/agent/scripts/vm/hypervisor/xenserver/launch_hb.sh
-%exclude %{_libdir}/%{name}/agent/scripts/vm/hypervisor/xenserver/setup_heartbeat_sr.sh
-%exclude %{_libdir}/%{name}/agent/scripts/vm/hypervisor/xenserver/vmopspremium
-%exclude %{_libdir}/%{name}/agent/scripts/vm/hypervisor/xenserver/xenheartbeat.sh
-%exclude %{_libdir}/%{name}/agent/scripts/vm/hypervisor/xenserver/xenserver56/patch-premium
-%exclude %{_libdir}/%{name}/agent/scripts/vm/hypervisor/xenserver/xs_cleanup.sh
-%endif
%{_libdir}/%{name}/agent/vms/systemvm.zip
%{_libdir}/%{name}/agent/vms/systemvm.iso
@@ -504,53 +494,26 @@ fi
%attr(0755,root,root) %{_bindir}/%{name}-setup-databases
%attr(0755,root,root) %{_bindir}/%{name}-migrate-databases
%dir %{_datadir}/%{name}/setup
-%{_datadir}/%{name}/setup/create-database.sql
-%{_datadir}/%{name}/setup/create-index-fk.sql
-%{_datadir}/%{name}/setup/create-schema.sql
-%{_datadir}/%{name}/setup/server-setup.sql
-%{_datadir}/%{name}/setup/templates.*.sql
-%{_datadir}/%{name}/setup/templates.sql
+%{_datadir}/%{name}/setup/*.sql
%{_datadir}/%{name}/setup/deploy-db-dev.sh
%{_datadir}/%{name}/setup/server-setup.xml
-%{_datadir}/%{name}/setup/data-20to21.sql
-%{_datadir}/%{name}/setup/index-20to21.sql
-%{_datadir}/%{name}/setup/index-212to213.sql
-%{_datadir}/%{name}/setup/postprocess-20to21.sql
-%{_datadir}/%{name}/setup/schema-20to21.sql
-%{_datadir}/%{name}/setup/schema-level.sql
-%{_datadir}/%{name}/setup/schema-21to22.sql
-%{_datadir}/%{name}/setup/data-21to22.sql
-%{_datadir}/%{name}/setup/index-21to22.sql
%files client
%defattr(0644,root,root,0755)
-%{_sysconfdir}/%{name}/management/catalina.policy
-%{_sysconfdir}/%{name}/management/*.properties
-%{_sysconfdir}/%{name}/management/resources/*.properties
-%{_sysconfdir}/%{name}/management/components.xml
-%{_sysconfdir}/%{name}/management/context.xml
+%{_sysconfdir}/%{name}/management/*
+%if %{_premium}
+%exclude %{_sysconfdir}/%{name}/management/*premium*
+%endif
%config(noreplace) %attr(640,root,%{name}) %{_sysconfdir}/%{name}/management/db.properties
-%{_sysconfdir}/%{name}/management/environment.properties
-%{_sysconfdir}/%{name}/management/ehcache.xml
%config(noreplace) %{_sysconfdir}/%{name}/management/log4j-%{name}.xml
-%{_sysconfdir}/%{name}/management/logging.properties
-%{_sysconfdir}/%{name}/management/server.xml
%config(noreplace) %{_sysconfdir}/%{name}/management/tomcat6.conf
-%{_sysconfdir}/%{name}/management/classpath.conf
-%{_sysconfdir}/%{name}/management/tomcat-users.xml
-%{_sysconfdir}/%{name}/management/web.xml
%dir %attr(770,root,%{name}) %{_sysconfdir}/%{name}/management/Catalina
%dir %attr(770,root,%{name}) %{_sysconfdir}/%{name}/management/Catalina/localhost
%dir %attr(770,root,%{name}) %{_sysconfdir}/%{name}/management/Catalina/localhost/client
%config %{_sysconfdir}/sysconfig/%{name}-management
%attr(0755,root,root) %{_initrddir}/%{name}-management
%dir %{_datadir}/%{name}/management
-%{_datadir}/%{name}/management/bin
-%{_datadir}/%{name}/management/conf
-%{_datadir}/%{name}/management/lib
-%{_datadir}/%{name}/management/logs
-%{_datadir}/%{name}/management/temp
-%{_datadir}/%{name}/management/work
+%{_datadir}/%{name}/management/*
%attr(755,root,root) %{_bindir}/%{name}-setup-management
%attr(755,root,root) %{_bindir}/%{name}-update-xenserver-licenses
%dir %attr(770,root,%{name}) %{_sharedstatedir}/%{name}/mnt
@@ -584,9 +547,7 @@ fi
%files console-proxy
%defattr(0644,root,root,0755)
%{_javadir}/%{name}-console*.jar
-%config(noreplace) %{_sysconfdir}/%{name}/console-proxy/agent.properties
-%config(noreplace) %{_sysconfdir}/%{name}/console-proxy/consoleproxy.properties
-%config(noreplace) %{_sysconfdir}/%{name}/console-proxy/log4j-%{name}.xml
+%config(noreplace) %{_sysconfdir}/%{name}/console-proxy/*
%attr(0755,root,root) %{_initrddir}/%{name}-console-proxy
%attr(0755,root,root) %{_libexecdir}/console-proxy-runner
%{_libdir}/%{name}/console-proxy/*
@@ -624,14 +585,7 @@ fi
%{_datadir}/%{name}/setup/create-database-premium.sql
%{_datadir}/%{name}/setup/create-schema-premium.sql
# maintain the following list in sync with files agent-scripts
-%{_libdir}/%{name}/agent/scripts/vm/hypervisor/xenserver/check_heartbeat.sh
-%{_libdir}/%{name}/agent/scripts/vm/hypervisor/xenserver/find_bond.sh
-%{_libdir}/%{name}/agent/scripts/vm/hypervisor/xenserver/launch_hb.sh
-%{_libdir}/%{name}/agent/scripts/vm/hypervisor/xenserver/setup_heartbeat_sr.sh
-%{_libdir}/%{name}/agent/scripts/vm/hypervisor/xenserver/vmopspremium
-%{_libdir}/%{name}/agent/scripts/vm/hypervisor/xenserver/xenheartbeat.sh
-%{_libdir}/%{name}/agent/scripts/vm/hypervisor/xenserver/xenserver56/patch-premium
-%{_libdir}/%{name}/agent/scripts/vm/hypervisor/xenserver/xs_cleanup.sh
+%{_libdir}/%{name}/agent/premium-scripts/*
%files usage
%defattr(0644,root,root,0755)
diff --git a/console-proxy/.classpath b/console-proxy/.classpath
index 0b57db8ad5a..521b7a55fa9 100644
--- a/console-proxy/.classpath
+++ b/console-proxy/.classpath
@@ -1,9 +1,9 @@
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
diff --git a/console-proxy/wscript_build b/console-proxy/wscript_build
deleted file mode 100644
index d5221157768..00000000000
--- a/console-proxy/wscript_build
+++ /dev/null
@@ -1,10 +0,0 @@
-import Options
-
-# binary unsubstitutable files:
-bld.install_files("${CPLIBDIR}",bld.path.ant_glob("images/**",src=True,bld=False,dir=False,flat=True),cwd=bld.path,relative_trick=True)
-
-# text substitutable files (substitute with tokens from the environment bld.env):
-bld.substitute('css/** js/** ui/** scripts/**',install_to="${CPLIBDIR}")
-
-# config files (do not replace them if preserve config option is true)
-if not Options.options.PRESERVECONFIG: bld.install_files_filtered("${CPSYSCONFDIR}","conf.dom0/*")
diff --git a/console-viewer/.classpath b/console-viewer/.classpath
index 19542e73fc0..170f58a8bbb 100644
--- a/console-viewer/.classpath
+++ b/console-viewer/.classpath
@@ -1,7 +1,7 @@
-
-
-
-
-
-
-
+
+
+
+
+
+
+
diff --git a/core/.classpath b/core/.classpath
index f2fff92d833..4fbdcf5ff6e 100644
--- a/core/.classpath
+++ b/core/.classpath
@@ -1,43 +1,43 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/core/src/com/cloud/agent/api/AttachVolumeAnswer.java b/core/src/com/cloud/agent/api/AttachVolumeAnswer.java
index 22b84b268b2..999942bdd61 100644
--- a/core/src/com/cloud/agent/api/AttachVolumeAnswer.java
+++ b/core/src/com/cloud/agent/api/AttachVolumeAnswer.java
@@ -20,6 +20,7 @@ package com.cloud.agent.api;
public class AttachVolumeAnswer extends Answer {
private Long deviceId;
+ private String chainInfo;
protected AttachVolumeAnswer() {
@@ -40,10 +41,19 @@ public class AttachVolumeAnswer extends Answer {
super(cmd);
this.deviceId = null;
}
+
/**
* @return the deviceId
*/
public Long getDeviceId() {
return deviceId;
}
+
+ public void setChainInfo(String chainInfo) {
+ this.chainInfo = chainInfo;
+ }
+
+ public String getChainInfo() {
+ return chainInfo;
+ }
}
diff --git a/core/src/com/cloud/agent/api/AttachVolumeCommand.java b/core/src/com/cloud/agent/api/AttachVolumeCommand.java
index 0ac47dd7e2e..3029ed0fda2 100644
--- a/core/src/com/cloud/agent/api/AttachVolumeCommand.java
+++ b/core/src/com/cloud/agent/api/AttachVolumeCommand.java
@@ -30,11 +30,12 @@ public class AttachVolumeCommand extends Command {
String volumePath;
String volumeName;
Long deviceId;
+ String chainInfo;
protected AttachVolumeCommand() {
}
- public AttachVolumeCommand(boolean attach, String vmName, StoragePoolType pooltype, String volumeFolder, String volumePath, String volumeName, Long deviceId) {
+ public AttachVolumeCommand(boolean attach, String vmName, StoragePoolType pooltype, String volumeFolder, String volumePath, String volumeName, Long deviceId, String chainInfo) {
this.attach = attach;
this.vmName = vmName;
this.pooltype = pooltype;
@@ -42,6 +43,7 @@ public class AttachVolumeCommand extends Command {
this.volumePath = volumePath;
this.volumeName = volumeName;
this.deviceId = deviceId;
+ this.chainInfo = chainInfo;
}
@Override
@@ -92,4 +94,8 @@ public class AttachVolumeCommand extends Command {
public void setPoolUuid(String poolUuid) {
this.poolUuid = poolUuid;
}
+
+ public String getChainInfo() {
+ return chainInfo;
+ }
}
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/api/storage/DestroyCommand.java b/core/src/com/cloud/agent/api/storage/DestroyCommand.java
index e7cdaec433f..255eb6c7db9 100755
--- a/core/src/com/cloud/agent/api/storage/DestroyCommand.java
+++ b/core/src/com/cloud/agent/api/storage/DestroyCommand.java
@@ -37,7 +37,8 @@ public class DestroyCommand extends StorageCommand {
}
public DestroyCommand(StoragePoolVO pool, VMTemplateStoragePoolVO templatePoolRef) {
- volume = new VolumeTO(templatePoolRef.getId(), null, Storage.StorageResourceType.STORAGE_POOL, pool.getPoolType(), null, pool.getPath(), templatePoolRef.getInstallPath(), templatePoolRef.getTemplateSize());
+ volume = new VolumeTO(templatePoolRef.getId(), null, Storage.StorageResourceType.STORAGE_POOL, pool.getPoolType(), null, pool.getPath(),
+ templatePoolRef.getInstallPath(), templatePoolRef.getTemplateSize(), null);
}
public VolumeTO getVolume() {
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/capacity/CapacityVO.java b/core/src/com/cloud/capacity/CapacityVO.java
index eabf7a9bb6a..34d8ef06b52 100644
--- a/core/src/com/cloud/capacity/CapacityVO.java
+++ b/core/src/com/cloud/capacity/CapacityVO.java
@@ -44,7 +44,10 @@ public class CapacityVO implements Capacity {
@Column(name="used_capacity")
private long usedCapacity;
-
+
+ @Column(name="reserved_capacity")
+ private long reservedCapacity;
+
@Column(name="total_capacity")
private long totalCapacity;
@@ -96,6 +99,13 @@ public class CapacityVO implements Capacity {
}
public void setUsedCapacity(long usedCapacity) {
this.usedCapacity = usedCapacity;
+ }
+ @Override
+ public long getReservedCapacity() {
+ return reservedCapacity;
+ }
+ public void setReservedCapacity(long reservedCapacity) {
+ this.usedCapacity = reservedCapacity;
}
@Override
public long getTotalCapacity() {
diff --git a/core/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java b/core/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java
index 44f6c4d50e3..66559c24e45 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;
@@ -227,7 +229,6 @@ public abstract class CitrixResourceBase implements StoragePoolResource, ServerR
protected String _pod;
protected String _cluster;
protected HashMap _vms = new HashMap(71);
- protected String _patchPath;
protected String _privateNetworkName;
protected String _linkLocalPrivateNetworkName;
protected String _publicNetworkName;
@@ -463,8 +464,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 +532,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) {
@@ -746,7 +748,7 @@ public abstract class CitrixResourceBase implements StoragePoolResource, ServerR
}
protected VM createVmFromTemplate(Connection conn, VirtualMachineTO vmSpec, Host host) throws XenAPIException, XmlRpcException {
- String guestOsTypeName = getGuestOsType(vmSpec.getOs());
+ String guestOsTypeName = getGuestOsType(vmSpec.getOs(), vmSpec.getBootloader() == BootloaderType.CD);
Set templates = VM.getByNameLabel(conn, guestOsTypeName);
assert templates.size() == 1 : "Should only have 1 template but found " + templates.size();
VM template = templates.iterator().next();
@@ -1038,8 +1040,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 +1053,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 +1149,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 +1625,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 +1723,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 +1738,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 +2079,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 +2300,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")) {
@@ -2602,7 +2610,7 @@ public abstract class CitrixResourceBase implements StoragePoolResource, ServerR
Set templates;
VM vm = null;
String stdType = cmd.getGuestOSDescription();
- String guestOsTypeName = getGuestOsType(stdType);
+ String guestOsTypeName = getGuestOsType(stdType, cmd.getBootFromISO());
templates = VM.getByNameLabel(conn, guestOsTypeName);
assert templates.size() == 1 : "Should only have 1 template but found " + templates.size();
VM template = templates.iterator().next();
@@ -2612,7 +2620,9 @@ public abstract class CitrixResourceBase implements StoragePoolResource, ServerR
if (!(guestOsTypeName.startsWith("Windows") || guestOsTypeName.startsWith("Citrix") || guestOsTypeName.startsWith("Other"))) {
if (cmd.getBootFromISO()) {
vm.setPVBootloader(conn, "eliloader");
- vm.addToOtherConfig(conn, "install-repository", "cdrom");
+ Map otherConfig = vm.getOtherConfig(conn);
+ otherConfig.put( "install-repository", "cdrom");
+ vm.setOtherConfig(conn, otherConfig);
} else {
vm.setPVBootloader(conn, "pygrub");
}
@@ -2937,7 +2947,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 +2984,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 +3158,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) {
@@ -3213,9 +3229,9 @@ public abstract class CitrixResourceBase implements StoragePoolResource, ServerR
Ternary mount = mounts.get(0);
- Set templates = VM.getByNameLabel(conn, getGuestOsType(getGuestOSDescription));
+ Set templates = VM.getByNameLabel(conn, getGuestOsType(getGuestOSDescription, false));
if (templates.size() == 0) {
- String msg = " can not find systemvm template " + getGuestOsType(getGuestOSDescription) ;
+ String msg = " can not find systemvm template " + getGuestOsType(getGuestOSDescription, false) ;
s_logger.warn(msg);
return msg;
@@ -3288,8 +3304,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 +3330,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 +3341,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 +3421,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 +3477,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 +3834,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;
@@ -4196,12 +4218,12 @@ public abstract class CitrixResourceBase implements StoragePoolResource, ServerR
SCPClient scp = new SCPClient(sshConnection);
- String path = _patchPath.substring(0, _patchPath.lastIndexOf(File.separator) + 1);
List files = getPatchFiles();
if( files == null || files.isEmpty() ) {
throw new CloudRuntimeException("Can not find patch file");
}
for( File file :files) {
+ String path = file.getParentFile().getAbsolutePath() + "/";
Properties props = new Properties();
props.load(new FileInputStream(file));
@@ -4271,8 +4293,11 @@ public abstract class CitrixResourceBase implements StoragePoolResource, ServerR
}
protected List getPatchFiles() {
+
+ String patchPath = getPatchPath();
+ String patchfilePath = Script.findScript(patchPath, "patch");
+ File file = new File(patchfilePath);
List files = new ArrayList();
- File file = new File(_patchPath);
files.add(file);
return files;
}
@@ -4585,8 +4610,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) {
@@ -4620,13 +4646,6 @@ public abstract class CitrixResourceBase implements StoragePoolResource, ServerR
throw new ConfigurationException("Unable to get the uuid");
}
- String patchPath = getPatchPath();
-
- _patchPath = Script.findScript(patchPath, "patch");
- if (_patchPath == null) {
- throw new ConfigurationException("Unable to find all of patch files for xenserver");
- }
-
_storage = (StorageLayer) params.get(StorageLayer.InstanceConfigKey);
if (_storage == null) {
value = (String) params.get(StorageLayer.ClassConfigKey);
@@ -4688,7 +4707,7 @@ public abstract class CitrixResourceBase implements StoragePoolResource, ServerR
s_logger.debug("Succesfully created VDI for " + cmd + ". Uuid = " + vdir.uuid);
VolumeTO vol = new VolumeTO(cmd.getVolumeId(), dskch.getType(), Storage.StorageResourceType.STORAGE_POOL, pool.getType(), vdir.nameLabel, pool.getPath(), vdir.uuid,
- vdir.virtualSize);
+ vdir.virtualSize, null);
return new CreateAnswer(cmd, vol);
} catch (Exception e) {
s_logger.warn("Unable to create volume; Pool=" + pool + "; Disk: " + dskch, e);
@@ -4853,28 +4872,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 +4975,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 +5200,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 +5844,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 +5925,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 +5964,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;
@@ -6196,7 +6231,7 @@ public abstract class CitrixResourceBase implements StoragePoolResource, ServerR
}
/*Override by subclass*/
- protected String getGuestOsType(String stdType) {
+ protected String getGuestOsType(String stdType, boolean bootFromCD) {
return stdType;
}
}
diff --git a/core/src/com/cloud/hypervisor/xen/resource/XcpServerResource.java b/core/src/com/cloud/hypervisor/xen/resource/XcpServerResource.java
index 2d4da33ee23..57a8a343c5f 100644
--- a/core/src/com/cloud/hypervisor/xen/resource/XcpServerResource.java
+++ b/core/src/com/cloud/hypervisor/xen/resource/XcpServerResource.java
@@ -28,7 +28,7 @@ public class XcpServerResource extends CitrixResourceBase {
}
@Override
- protected String getGuestOsType(String stdType) {
+ protected String getGuestOsType(String stdType, boolean bootFromCD) {
return CitrixHelper.getXcpGuestOsType(stdType);
}
}
diff --git a/core/src/com/cloud/hypervisor/xen/resource/XenServerResource.java b/core/src/com/cloud/hypervisor/xen/resource/XenServerResource.java
index a0668f1a00c..9e70d104236 100644
--- a/core/src/com/cloud/hypervisor/xen/resource/XenServerResource.java
+++ b/core/src/com/cloud/hypervisor/xen/resource/XenServerResource.java
@@ -38,7 +38,7 @@ public class XenServerResource extends CitrixResourceBase {
}
@Override
- protected String getGuestOsType(String stdType) {
+ protected String getGuestOsType(String stdType, boolean bootFromCD) {
return CitrixHelper.getXenServerGuestOsType(stdType);
}
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/core/src/com/cloud/storage/VolumeVO.java b/core/src/com/cloud/storage/VolumeVO.java
index d3b02e0f95e..380dceaf119 100755
--- a/core/src/com/cloud/storage/VolumeVO.java
+++ b/core/src/com/cloud/storage/VolumeVO.java
@@ -160,6 +160,9 @@ public class VolumeVO implements Volume {
@Column(name="source_id")
Long sourceId;
+ @Column(name="chain_info")
+ String chainInfo;
+
/**
* Constructor for data disk.
* @param type
@@ -559,5 +562,13 @@ public class VolumeVO implements Volume {
public void setAttached(Date attached){
this.attached = attached;
}
-
+
+ @Override
+ public String getChainInfo() {
+ return this.chainInfo;
+ }
+
+ public void setChainInfo(String chainInfo) {
+ this.chainInfo = chainInfo;
+ }
}
diff --git a/core/src/com/cloud/vm/VMInstanceVO.java b/core/src/com/cloud/vm/VMInstanceVO.java
index 8bfa0906c36..a610ff3076e 100644
--- a/core/src/com/cloud/vm/VMInstanceVO.java
+++ b/core/src/com/cloud/vm/VMInstanceVO.java
@@ -38,12 +38,13 @@ import javax.persistence.TemporalType;
import com.cloud.utils.db.GenericDao;
import com.cloud.utils.db.StateMachine;
import com.cloud.utils.fsm.FiniteStateObject;
+import com.cloud.utils.fsm.StateObject;
@Entity
@Table(name="vm_instance")
@Inheritance(strategy=InheritanceType.JOINED)
@DiscriminatorColumn(name="type", discriminatorType=DiscriminatorType.STRING, length=32)
-public class VMInstanceVO implements VirtualMachine, FiniteStateObject {
+public class VMInstanceVO implements VirtualMachine, FiniteStateObject, StateObject {
@Id
@TableGenerator(name="vm_instance_sq", table="sequence", pkColumnName="name", valueColumnName="value", pkColumnValue="vm_instance_seq", allocationSize=1)
@Column(name="id", updatable=false, nullable = false)
diff --git a/daemonize/wscript_build b/daemonize/wscript_build
deleted file mode 100644
index ce5741a741a..00000000000
--- a/daemonize/wscript_build
+++ /dev/null
@@ -1,7 +0,0 @@
-if bld.env.DISTRO not in ['Windows','Mac']:
- # build / install declarations of the daemonization utility - except for Windows
- bld(
- name='daemonize',
- features='cc cprogram',
- source='daemonize.c',
- target='cloud-daemonize')
\ No newline at end of file
diff --git a/debian/cloud-agent-scripts.install b/debian/cloud-agent-scripts.install
index 155928a098d..414d09b4e90 100644
--- a/debian/cloud-agent-scripts.install
+++ b/debian/cloud-agent-scripts.install
@@ -7,21 +7,6 @@
/usr/lib/cloud/agent/scripts/vm/hypervisor/kvm/*
/usr/lib/cloud/agent/scripts/vm/hypervisor/versions.sh
/usr/lib/cloud/agent/scripts/vm/hypervisor/xen/*
-/usr/lib/cloud/agent/scripts/vm/hypervisor/xenserver/hostvmstats.py
-/usr/lib/cloud/agent/scripts/vm/hypervisor/xenserver/id_rsa.cloud
-/usr/lib/cloud/agent/scripts/vm/hypervisor/xenserver/make_migratable.sh
-/usr/lib/cloud/agent/scripts/vm/hypervisor/xenserver/network_info.sh
-/usr/lib/cloud/agent/scripts/vm/hypervisor/xenserver/setup_iscsi.sh
-/usr/lib/cloud/agent/scripts/vm/hypervisor/xenserver/setupxenserver.sh
-/usr/lib/cloud/agent/scripts/vm/hypervisor/xenserver/vmops
-/usr/lib/cloud/agent/scripts/vm/hypervisor/xenserver/vmopsSnapshot
-/usr/lib/cloud/agent/scripts/vm/hypervisor/xenserver/xcpserver/*
-/usr/lib/cloud/agent/scripts/vm/hypervisor/xenserver/xenserver56/cleanup.py
-/usr/lib/cloud/agent/scripts/vm/hypervisor/xenserver/xenserver56/ISCSISR.py
-/usr/lib/cloud/agent/scripts/vm/hypervisor/xenserver/xenserver56/LUNperVDI.py
-/usr/lib/cloud/agent/scripts/vm/hypervisor/xenserver/xenserver56/nfs.py
-/usr/lib/cloud/agent/scripts/vm/hypervisor/xenserver/xenserver56/NFSSR.py
-/usr/lib/cloud/agent/scripts/vm/hypervisor/xenserver/xenserver56/patch
-/usr/lib/cloud/agent/scripts/vm/hypervisor/xenserver/xenserver56/scsiutil.py
+/usr/lib/cloud/agent/scripts/vm/hypervisor/xenserver/*
/usr/lib/cloud/agent/vms/systemvm.zip
/usr/lib/cloud/agent/vms/systemvm.iso
diff --git a/debian/cloud-premium.install b/debian/cloud-premium.install
index db394b490fa..2c8a3cf6622 100644
--- a/debian/cloud-premium.install
+++ b/debian/cloud-premium.install
@@ -5,11 +5,4 @@
/usr/share/cloud/setup/create-database-premium.sql
/usr/share/cloud/setup/create-schema-premium.sql
/usr/lib/cloud/agent/vms/systemvm-premium.iso
-/usr/lib/cloud/agent/scripts/vm/hypervisor/xenserver/check_heartbeat.sh
-/usr/lib/cloud/agent/scripts/vm/hypervisor/xenserver/find_bond.sh
-/usr/lib/cloud/agent/scripts/vm/hypervisor/xenserver/launch_hb.sh
-/usr/lib/cloud/agent/scripts/vm/hypervisor/xenserver/setup_heartbeat_sr.sh
-/usr/lib/cloud/agent/scripts/vm/hypervisor/xenserver/vmopspremium
-/usr/lib/cloud/agent/scripts/vm/hypervisor/xenserver/xenheartbeat.sh
-/usr/lib/cloud/agent/scripts/vm/hypervisor/xenserver/xenserver56/patch-premium
-/usr/lib/cloud/agent/scripts/vm/hypervisor/xenserver/xs_cleanup.sh
+/usr/lib/cloud/agent/premium-scripts/*
diff --git a/debian/cloud-setup.install b/debian/cloud-setup.install
index ff795672cfe..a6d7c149ac5 100644
--- a/debian/cloud-setup.install
+++ b/debian/cloud-setup.install
@@ -1,18 +1,5 @@
/usr/bin/cloud-setup-databases
/usr/bin/cloud-migrate-databases
-/usr/share/cloud/setup/create-database.sql
-/usr/share/cloud/setup/create-index-fk.sql
-/usr/share/cloud/setup/create-schema.sql
-/usr/share/cloud/setup/server-setup.sql
-/usr/share/cloud/setup/templates.*.sql
+/usr/share/cloud/setup/*.sql
/usr/share/cloud/setup/deploy-db-dev.sh
/usr/share/cloud/setup/server-setup.xml
-/usr/share/cloud/setup/data-20to21.sql
-/usr/share/cloud/setup/index-20to21.sql
-/usr/share/cloud/setup/index-212to213.sql
-/usr/share/cloud/setup/postprocess-20to21.sql
-/usr/share/cloud/setup/schema-20to21.sql
-/usr/share/cloud/setup/schema-level.sql
-/usr/share/cloud/setup/schema-21to22.sql
-/usr/share/cloud/setup/data-21to22.sql
-/usr/share/cloud/setup/index-21to22.sql
diff --git a/deps/wscript_build b/deps/wscript_build
deleted file mode 100644
index 0167a5697cb..00000000000
--- a/deps/wscript_build
+++ /dev/null
@@ -1 +0,0 @@
-bld.install_files('${JAVADIR}',bld.path.ant_glob("*.jar", excl=["cloud-xstream-1.3.1.jar", "cloud-commons-dbcp-1.2.2.jar", "cloud-commons-httpclient-3.1.jar", "cloud-commons-pool-1.4.jar", "cloud-servlet-api.jar", "cloud-commons-logging-1.1.1.jar", "cloud-ws-commons-util-1.0.2.jar", "cloud-commons-collections-3.2.1.jar", "vmware*.jar"]))
diff --git a/patches/wscript_build b/patches/wscript_build
deleted file mode 100644
index 5abef720b8a..00000000000
--- a/patches/wscript_build
+++ /dev/null
@@ -1,15 +0,0 @@
-import os, Utils, glob, re
-
-bld.substitute("*/**",name="patchsubst")
-
-for virttech in Utils.to_list(bld.path.ant_glob("*",dir=True)):
- if virttech in ["shared","wscript_build"]: continue
- patchfiles = bld.path.ant_glob('shared/** %s/debian/config/**'%virttech,src=False,bld=True,dir=False,flat=True)
- tgen = bld(
- features = 'tar',#Utils.tar_up,
- source = patchfiles,
- target = 'cloud-scripts.tgz',
- name = 'cloud-scripts_tgz',
- root = os.path.join("patches", virttech + "/debian/config"),
- rename = lambda x: re.sub(".subst$","",x),
- )
diff --git a/python/lib/cloud_utils.py b/python/lib/cloud_utils.py
index 27fed1f86c6..3bfc62976a9 100644
--- a/python/lib/cloud_utils.py
+++ b/python/lib/cloud_utils.py
@@ -357,9 +357,11 @@ class ConfigTask:
class SetupNetworking(ConfigTask):
name = "network setup"
- def __init__(self,brname):
+ def __init__(self,brname, pubNic, prvNic):
ConfigTask.__init__(self)
self.brname = brname
+ self.pubNic = pubNic
+ self.prvNic = prvNic
self.runtime_state_changed = False
self.was_nm_service_running = None
self.was_net_service_running = None
@@ -373,10 +375,22 @@ class SetupNetworking(ConfigTask):
def done(self):
try:
+ alreadysetup = False
if distro in (Fedora,CentOS):
- alreadysetup = augtool._print("/files/etc/sysconfig/network-scripts/ifcfg-%s"%self.brname).stdout.strip()
+ if self.pubNic != None:
+ alreadysetup = alreadysetup or augtool._print("/files/etc/sysconfig/network-scripts/ifcfg-%s"%self.pubNic).stdout.strip()
+ if self.prvNic != None:
+ alreadysetup = alreadysetup or augtool._print("/files/etc/sysconfig/network-scripts/ifcfg-%s"%self.prvNic).stdout.strip()
+ if not alreadysetup:
+ alreadysetup = augtool._print("/files/etc/sysconfig/network-scripts/ifcfg-%s"%self.brname).stdout.strip()
+
else:
- alreadysetup = augtool.match("/files/etc/network/interfaces/iface",self.brname).stdout.strip()
+ if self.pubNic != None:
+ alreadysetup = alreadysetup or augtool._print("/files/etc/network/interfaces/iface",self.pubNic).stdout.strip()
+ if self.prvNic != None:
+ alreadysetup = alreadysetup or augtool._print("/files/etc/network/interfaces/iface",self.prvNic).stdout.strip()
+ if not alreadysetup:
+ alreadysetup = augtool.match("/files/etc/network/interfaces/iface",self.brname).stdout.strip()
return alreadysetup
except OSError,e:
if e.errno is 2: raise TaskFailed("augtool has not been properly installed on this system")
@@ -833,10 +847,10 @@ class SetupFirewall2(ConfigTask):
# Tasks according to distribution -- at some point we will split them in separate modules
-def config_tasks(brname):
+def config_tasks(brname, pubNic, prvNic):
if distro is CentOS:
config_tasks = (
- SetupNetworking(brname),
+ SetupNetworking(brname, pubNic, prvNic),
SetupLibvirt(),
SetupRequiredServices(),
SetupFirewall(),
@@ -844,7 +858,7 @@ def config_tasks(brname):
)
elif distro in (Ubuntu,Fedora):
config_tasks = (
- SetupNetworking(brname),
+ SetupNetworking(brname, pubNic, prvNic),
SetupCgConfig(),
SetupCgRules(),
SetupCgroupControllers(),
@@ -912,7 +926,18 @@ def prompt_for_hostpods(zonespods):
# this configures the agent
-def setup_agent_config(configfile, host, zone, pod, cluster, guid):
+def device_exist(devName):
+ try:
+ alreadysetup = False
+ if distro in (Fedora,CentOS):
+ alreadysetup = augtool._print("/files/etc/sysconfig/network-scripts/ifcfg-%s"%devName).stdout.strip()
+ else:
+ alreadysetup = augtool.match("/files/etc/network/interfaces/iface",devName).stdout.strip()
+ return alreadysetup
+ except OSError,e:
+ return False
+
+def setup_agent_config(configfile, host, zone, pod, cluster, guid, pubNic, prvNic):
stderr("Examining Agent configuration")
fn = configfile
text = file(fn).read(-1)
@@ -937,6 +962,16 @@ def setup_agent_config(configfile, host, zone, pod, cluster, guid):
confopts["host"] = host
+ if pubNic != None and device_exist(pubNic):
+ confopts["public.network.device"] = pubNic
+ if prvNic == None or not device_exist(prvNic):
+ confopts["private.network.device"] = pubNic
+
+ if prvNic != None and device_exits(prvNic):
+ confopts["private.network.device"] = prvNic
+ if pubNic == None or not device_exits(pubNic):
+ confopts["public.network.device"] = prvNic
+
stderr("Querying %s for zones and pods",host)
try:
diff --git a/python/wscript_build b/python/wscript_build
deleted file mode 100644
index d3a80e70d26..00000000000
--- a/python/wscript_build
+++ /dev/null
@@ -1,2 +0,0 @@
-obj = bld(features = 'py',name='pythonmodules')
-obj.find_sources_in_dirs('lib', exts=['.py'])
diff --git a/scripts/vm/hypervisor/kvm/setup_agent.sh b/scripts/vm/hypervisor/kvm/setup_agent.sh
index 89bcfb0dc10..2ac3d9ebdc1 100755
--- a/scripts/vm/hypervisor/kvm/setup_agent.sh
+++ b/scripts/vm/hypervisor/kvm/setup_agent.sh
@@ -151,7 +151,9 @@ pod=
cluster=
guid=
dflag=
-while getopts 'h:z:p:u:c:d' OPTION
+pubNic=
+prvNic=
+while getopts 'h:z:p:u:c:P:N:d' OPTION
do
case $OPTION in
h)
@@ -172,11 +174,35 @@ do
d)
dflag=1
;;
+ P)
+ pubNic="$OPTARG"
+ ;;
+ N)
+ prvNic="$OPTARG"
+ ;;
*) ;;
esac
done
#install_cloud_agent $dflag
#install_cloud_consoleP $dflag
-cloud_agent_setup $host $zone $pod $cluster $guid
+paramters=
+if [ -n "$pubNic" ]
+then
+ paramters=" --pubNic=$pubNic"
+fi
+
+if [ -n "$prvNic" ]
+then
+ paramters=" --prvNic=$prvNic $paramters"
+fi
+
+selenabled=`cat /selinux/enforce`
+if [ "$selenabled" == "1" ]
+then
+ sed -i 's/\(SELINUX\)\(.*\)/\1=permissive/' /etc/selinux/config
+ setenforce 0
+fi
+
+cloud-setup-agent --host=$host --zone=$zone --pod=$pod --cluster=$cluster --guid=$guid $paramters -a > /dev/null
#cloud_consoleP_setup $host $zone $pod
diff --git a/scripts/vm/hypervisor/xenserver/xenserver56/patch b/scripts/vm/hypervisor/xenserver/xenserver56/patch
index 0da0e8b93ef..469ab077319 100644
--- a/scripts/vm/hypervisor/xenserver/xenserver56/patch
+++ b/scripts/vm/hypervisor/xenserver/xenserver56/patch
@@ -17,7 +17,6 @@ LUNperVDI.py=/opt/xensource/sm
nfs.py=/opt/xensource/sm
vmops=..,0755,/etc/xapi.d/plugins
vmopsSnapshot=..,0755,/etc/xapi.d/plugins
-xs_cleanup.sh=..,0755,/opt/xensource/bin
systemvm.iso=../../../../../vms,0644,/opt/xensource/packages/iso
hostvmstats.py=..,0755,/opt/xensource/sm
id_rsa.cloud=..,0600,/root/.ssh
diff --git a/scripts/wscript_build b/scripts/wscript_build
deleted file mode 100644
index 6730263e22f..00000000000
--- a/scripts/wscript_build
+++ /dev/null
@@ -1 +0,0 @@
-bld.substitute('**',"${AGENTLIBDIR}/scripts",chmod=0755)
diff --git a/server/src/com/cloud/agent/AgentManager.java b/server/src/com/cloud/agent/AgentManager.java
index 71d06cb86aa..80179cb1af8 100755
--- a/server/src/com/cloud/agent/AgentManager.java
+++ b/server/src/com/cloud/agent/AgentManager.java
@@ -31,6 +31,7 @@ import com.cloud.exception.DiscoveryException;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.OperationTimedoutException;
import com.cloud.host.Host;
+import com.cloud.host.Host.Type;
import com.cloud.host.HostStats;
import com.cloud.host.HostVO;
import com.cloud.host.Status;
@@ -155,7 +156,7 @@ public interface AgentManager extends Manager {
* to deploy in, service offering, template, and list of host to avoid.
*/
- Host findHost(Host.Type type, DataCenterVO dc, HostPodVO pod, StoragePoolVO sp, ServiceOffering offering, VMTemplateVO template, VMInstanceVO vm, Host currentHost, Set avoid);
+ Host findHost(Host.Type type, DataCenterVO dc, HostPodVO pod, StoragePoolVO sp, ServiceOfferingVO offering, VMTemplateVO template, VMInstanceVO vm, Host currentHost, Set avoid);
List listByDataCenter(long dcId);
List listByPod(long podId);
@@ -212,4 +213,5 @@ public interface AgentManager extends Manager {
public List discoverHosts(Long dcId, Long podId, Long clusterId, String clusterName, String url, String username, String password) throws IllegalArgumentException, DiscoveryException, InvalidParameterValueException;
Answer easySend(Long hostId, Command cmd, int timeout);
+
}
diff --git a/server/src/com/cloud/agent/manager/AgentManagerImpl.java b/server/src/com/cloud/agent/manager/AgentManagerImpl.java
index 6c2e9288d85..b2c02dc0667 100755
--- a/server/src/com/cloud/agent/manager/AgentManagerImpl.java
+++ b/server/src/com/cloud/agent/manager/AgentManagerImpl.java
@@ -95,10 +95,15 @@ import com.cloud.dc.dao.DataCenterDao;
import com.cloud.dc.dao.DataCenterIpAddressDao;
import com.cloud.dc.dao.HostPodDao;
import com.cloud.dc.dao.VlanDao;
+import com.cloud.deploy.DataCenterDeployment;
+import com.cloud.deploy.DeployDestination;
+import com.cloud.deploy.DeploymentPlanner;
+import com.cloud.deploy.DeploymentPlanner.ExcludeList;
import com.cloud.event.dao.EventDao;
import com.cloud.exception.AgentUnavailableException;
import com.cloud.exception.ConnectionException;
import com.cloud.exception.DiscoveryException;
+import com.cloud.exception.InsufficientServerCapacityException;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.OperationTimedoutException;
import com.cloud.exception.UnsupportedVersionException;
@@ -218,6 +223,9 @@ public class AgentManagerImpl implements AgentManager, HandlerFactory, ResourceS
@Inject protected DetailsDao _hostDetailsDao = null;
@Inject protected ClusterDao _clusterDao;
+ @Inject(adapter=DeploymentPlanner.class)
+ private Adapters _planners;
+
protected Adapters _discoverers = null;
protected int _port;
@@ -253,6 +261,7 @@ public class AgentManagerImpl implements AgentManager, HandlerFactory, ResourceS
protected long _nodeId = -1;
protected int _overProvisioningFactor = 1;
protected float _cpuOverProvisioningFactor = 1;
+ private boolean _useNewNetworking;
protected Random _rand = new Random(System.currentTimeMillis());
@@ -348,6 +357,8 @@ public class AgentManagerImpl implements AgentManager, HandlerFactory, ResourceS
if(_cpuOverProvisioningFactor < 1){
_cpuOverProvisioningFactor = 1;
}
+
+ _useNewNetworking = Boolean.parseBoolean(configs.get("use.new.networking"));
_connection = new NioServer("AgentManager", _port, workers + 10, this);
@@ -434,24 +445,47 @@ public class AgentManagerImpl implements AgentManager, HandlerFactory, ResourceS
@Override
public Host findHost(final Host.Type type, final DataCenterVO dc, final HostPodVO pod, final StoragePoolVO sp,
- final ServiceOffering offering, final VMTemplateVO template, VMInstanceVO vm,
+ final ServiceOfferingVO offering, final VMTemplateVO template, VMInstanceVO vm,
Host currentHost, final Set avoid) {
- VirtualMachineProfile vmc = new VirtualMachineProfileImpl(vm.getType());
- Enumeration en = _hostAllocators.enumeration();
- while (en.hasMoreElements()) {
- final HostAllocator allocator = en.nextElement();
- final Host host = allocator.allocateTo(vmc, offering, type, dc, pod, sp.getClusterId(), template, avoid);
- if (host == null) {
- continue;
- } else {
- return host;
- }
- }
+ if (!_useNewNetworking) {
+ VirtualMachineProfile vmc = new VirtualMachineProfileImpl(vm.getType());
+ Enumeration en = _hostAllocators.enumeration();
+ while (en.hasMoreElements()) {
+ final HostAllocator allocator = en.nextElement();
+ final Host host = allocator.allocateTo(vmc, offering, type, dc, pod, sp.getClusterId(), template, avoid);
+ if (host == null) {
+ continue;
+ } else {
+ return host;
+ }
+ }
+ } else {
+ VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vm, template, offering, null, null);
+ DeployDestination dest = null;
+ DataCenterDeployment plan = new DataCenterDeployment(dc.getId(), pod.getId(), sp.getClusterId(), null);
+ ExcludeList avoids = new ExcludeList();
+ for (Host h : avoid) {
+ avoids.addHost(h.getId());
+ }
+
+ for (DeploymentPlanner planner : _planners) {
+ try {
+ dest = planner.plan(vmProfile, plan, avoids);
+ if (dest != null) {
+ return dest.getHost();
+ }
+ } catch (InsufficientServerCapacityException e) {
+
+ }
+
+ }
+ }
s_logger.warn("findHost() could not find a non-null host.");
return null;
}
+
@Override
public List listByDataCenter(long dcId) {
List pods = _podDao.listByDataCenterId(dcId);
@@ -2112,10 +2146,12 @@ public class AgentManagerImpl implements AgentManager, HandlerFactory, ResourceS
List capacities = _capacityDao.search(capacitySC, null);
// remove old entries, we'll recalculate them anyway
- if ((capacities != null) && !capacities.isEmpty()) {
- for (CapacityVO capacity : capacities) {
- _capacityDao.remove(capacity.getId());
- }
+ if (!_useNewNetworking || startup instanceof StartupStorageCommand) {
+ if ((capacities != null) && !capacities.isEmpty()) {
+ for (CapacityVO capacity : capacities) {
+ _capacityDao.remove(capacity.getId());
+ }
+ }
}
if (startup instanceof StartupStorageCommand) {
@@ -2130,14 +2166,67 @@ public class AgentManagerImpl implements AgentManager, HandlerFactory, ResourceS
_capacityDao.persist(capacity);
}
} else if (startup instanceof StartupRoutingCommand) {
+ if (!_useNewNetworking) {
+ CapacityVO capacity = new CapacityVO(server.getId(), server.getDataCenterId(), server.getPodId(), 0L, (long)(server.getCpus().longValue()
+ * server.getSpeed().longValue()*_cpuOverProvisioningFactor), CapacityVO.CAPACITY_TYPE_CPU);
+ _capacityDao.persist(capacity);
- CapacityVO capacity = new CapacityVO(server.getId(), server.getDataCenterId(), server.getPodId(), 0L,
- server.getTotalMemory(), CapacityVO.CAPACITY_TYPE_MEMORY);
- _capacityDao.persist(capacity);
+ capacity = new CapacityVO(server.getId(), server.getDataCenterId(), server.getPodId(), 0L,
+ server.getTotalMemory(), CapacityVO.CAPACITY_TYPE_MEMORY);
+ _capacityDao.persist(capacity);
+ } else {
+ SearchCriteria capacityCPU = _capacityDao.createSearchCriteria();
+ capacityCPU.addAnd("hostOrPoolId", SearchCriteria.Op.EQ, server.getId());
+ capacityCPU.addAnd("dataCenterId", SearchCriteria.Op.EQ, server.getDataCenterId());
+ capacityCPU.addAnd("podId", SearchCriteria.Op.EQ, server.getPodId());
+ capacityCPU.addAnd("capacityType", SearchCriteria.Op.EQ, CapacityVO.CAPACITY_TYPE_CPU);
+ List capacityVOCpus = _capacityDao.search(capacitySC, null);
- capacity = new CapacityVO(server.getId(), server.getDataCenterId(), server.getPodId(), 0L, (long)(server.getCpus().longValue()
- * server.getSpeed().longValue()*_cpuOverProvisioningFactor), CapacityVO.CAPACITY_TYPE_CPU);
- _capacityDao.persist(capacity);
+ if (capacityVOCpus != null && !capacityVOCpus.isEmpty()) {
+ CapacityVO CapacityVOCpu = capacityVOCpus.get(0);
+ long newTotalCpu = (long)(server.getCpus().longValue() * server.getSpeed().longValue()*_cpuOverProvisioningFactor);
+ if ((CapacityVOCpu.getTotalCapacity() <= newTotalCpu) || ((CapacityVOCpu.getUsedCapacity() + CapacityVOCpu.getReservedCapacity()) <= newTotalCpu)) {
+ CapacityVOCpu.setTotalCapacity(newTotalCpu);
+ } else if ((CapacityVOCpu.getUsedCapacity() + CapacityVOCpu.getReservedCapacity() > newTotalCpu) && (CapacityVOCpu.getUsedCapacity() < newTotalCpu)) {
+ CapacityVOCpu.setReservedCapacity(0);
+ CapacityVOCpu.setTotalCapacity(newTotalCpu);
+ } else {
+ s_logger.debug("What? new cpu is :" + newTotalCpu + ", old one is " + CapacityVOCpu.getUsedCapacity() + "," + CapacityVOCpu.getReservedCapacity() + "," +
+ CapacityVOCpu.getTotalCapacity());
+ }
+ _capacityDao.update(CapacityVOCpu.getId(), CapacityVOCpu);
+ } else {
+ CapacityVO capacity = new CapacityVO(server.getId(), server.getDataCenterId(), server.getPodId(), 0L, (long)(server.getCpus().longValue()
+ * server.getSpeed().longValue()*_cpuOverProvisioningFactor), CapacityVO.CAPACITY_TYPE_CPU);
+ _capacityDao.persist(capacity);
+ }
+
+ SearchCriteria capacityMem = _capacityDao.createSearchCriteria();
+ capacityMem.addAnd("hostOrPoolId", SearchCriteria.Op.EQ, server.getId());
+ capacityMem.addAnd("dataCenterId", SearchCriteria.Op.EQ, server.getDataCenterId());
+ capacityMem.addAnd("podId", SearchCriteria.Op.EQ, server.getPodId());
+ capacityMem.addAnd("capacityType", SearchCriteria.Op.EQ, CapacityVO.CAPACITY_TYPE_MEMORY);
+ List capacityVOMems = _capacityDao.search(capacityMem, null);
+
+ if (capacityVOMems != null && !capacityVOMems.isEmpty()) {
+ CapacityVO CapacityVOMem = capacityVOMems.get(0);
+ long newTotalMem = server.getTotalMemory();
+ if (CapacityVOMem.getTotalCapacity() <= newTotalMem || (CapacityVOMem.getUsedCapacity() + CapacityVOMem.getReservedCapacity() <= newTotalMem)) {
+ CapacityVOMem.setTotalCapacity(newTotalMem);
+ } else if (CapacityVOMem.getUsedCapacity() + CapacityVOMem.getReservedCapacity() > newTotalMem && CapacityVOMem.getUsedCapacity() < newTotalMem) {
+ CapacityVOMem.setReservedCapacity(0);
+ CapacityVOMem.setTotalCapacity(newTotalMem);
+ } else {
+ s_logger.debug("What? new cpu is :" + newTotalMem + ", old one is " + CapacityVOMem.getUsedCapacity() + "," + CapacityVOMem.getReservedCapacity() + "," +
+ CapacityVOMem.getTotalCapacity());
+ }
+ _capacityDao.update(CapacityVOMem.getId(), CapacityVOMem);
+ } else {
+ CapacityVO capacity = new CapacityVO(server.getId(), server.getDataCenterId(), server.getPodId(), 0L,
+ server.getTotalMemory(), CapacityVO.CAPACITY_TYPE_MEMORY);
+ _capacityDao.persist(capacity);
+ }
+ }
}
}
diff --git a/server/src/com/cloud/agent/manager/allocator/impl/UserConcentratedAllocator.java b/server/src/com/cloud/agent/manager/allocator/impl/UserConcentratedAllocator.java
index 48799318645..2a913e34ff0 100755
--- a/server/src/com/cloud/agent/manager/allocator/impl/UserConcentratedAllocator.java
+++ b/server/src/com/cloud/agent/manager/allocator/impl/UserConcentratedAllocator.java
@@ -244,14 +244,14 @@ public class UserConcentratedAllocator implements PodAllocator {
so = _offeringDao.findById(userVm.getServiceOfferingId());
} else if(vm.getType() == VirtualMachine.Type.ConsoleProxy) {
so = new ServiceOfferingVO("Fake Offering For DomP", 1,
- _proxyRamSize, 0, 0, 0, false, null, NetworkOffering.GuestIpType.Virtualized, false, true, null, true);
+ _proxyRamSize, 0, 0, 0, false, null, NetworkOffering.GuestIpType.Virtual, false, true, null, true);
} else if(vm.getType() == VirtualMachine.Type.SecondaryStorageVm) {
- so = new ServiceOfferingVO("Fake Offering For Secondary Storage VM", 1, _secStorageVmRamSize, 0, 0, 0, false, null, NetworkOffering.GuestIpType.Virtualized, false, true, null, true);
+ so = new ServiceOfferingVO("Fake Offering For Secondary Storage VM", 1, _secStorageVmRamSize, 0, 0, 0, false, null, NetworkOffering.GuestIpType.Virtual, false, true, null, true);
} else if(vm.getType() == VirtualMachine.Type.DomainRouter) {
- so = new ServiceOfferingVO("Fake Offering For DomR", 1, _routerRamSize, 0, 0, 0, false, null, NetworkOffering.GuestIpType.Virtualized, false, true, null, true);
+ so = new ServiceOfferingVO("Fake Offering For DomR", 1, _routerRamSize, 0, 0, 0, false, null, NetworkOffering.GuestIpType.Virtual, false, true, null, true);
} else {
assert(false) : "Unsupported system vm type";
- so = new ServiceOfferingVO("Fake Offering For unknow system VM", 1, 128, 0, 0, 0, false, null, NetworkOffering.GuestIpType.Virtualized, false, true, null, true);
+ so = new ServiceOfferingVO("Fake Offering For unknow system VM", 1, 128, 0, 0, 0, false, null, NetworkOffering.GuestIpType.Virtual, false, true, null, true);
}
if(capacityType == CapacityVO.CAPACITY_TYPE_MEMORY) {
diff --git a/server/src/com/cloud/alert/AlertManagerImpl.java b/server/src/com/cloud/alert/AlertManagerImpl.java
index 0261d12a9a9..65736c16e06 100644
--- a/server/src/com/cloud/alert/AlertManagerImpl.java
+++ b/server/src/com/cloud/alert/AlertManagerImpl.java
@@ -116,7 +116,8 @@ public class AlertManagerImpl implements AlertManager {
private double _storageCapacityThreshold = 0.75;
private double _storageAllocCapacityThreshold = 0.75;
private double _publicIPCapacityThreshold = 0.75;
- private double _privateIPCapacityThreshold = 0.75;
+ private double _privateIPCapacityThreshold = 0.75;
+ private boolean _useNewNetworking;
@Override
public boolean configure(String name, Map params) throws ConfigurationException {
@@ -190,7 +191,9 @@ public class AlertManagerImpl implements AlertManager {
if(_cpuOverProvisioningFactor < 1){
_cpuOverProvisioningFactor = 1;
}
- }
+ }
+
+ _useNewNetworking = Boolean.parseBoolean(configs.get("use.new.networking"));
_timer = new Timer("CapacityChecker");
@@ -262,55 +265,58 @@ public class AlertManagerImpl implements AlertManager {
Map offeringsMap = new HashMap();
for (ServiceOfferingVO offering : offerings) {
offeringsMap.put(offering.getId(), offering);
- }
- for (HostVO host : hosts) {
- if (host.getType() != Host.Type.Routing) {
- continue;
- }
+ }
+
+ if (!_useNewNetworking) {
+ for (HostVO host : hosts) {
+ if (host.getType() != Host.Type.Routing) {
+ continue;
+ }
- long cpu = 0;
- long usedMemory = 0;
- List domainRouters = _routerDao.listUpByHostId(host.getId());
- if (s_logger.isDebugEnabled()) {
- s_logger.debug("Found " + domainRouters.size() + " router domains on host " + host.getId());
- }
- for (DomainRouterVO router : domainRouters) {
- usedMemory += router.getRamSize() * 1024L * 1024L;
- }
+ long cpu = 0;
+ long usedMemory = 0;
+ List domainRouters = _routerDao.listUpByHostId(host.getId());
+ if (s_logger.isDebugEnabled()) {
+ s_logger.debug("Found " + domainRouters.size() + " router domains on host " + host.getId());
+ }
+ for (DomainRouterVO router : domainRouters) {
+ usedMemory += router.getRamSize() * 1024L * 1024L;
+ }
- List proxys = _consoleProxyDao.listUpByHostId(host.getId());
- if (s_logger.isDebugEnabled()) {
- s_logger.debug("Found " + proxys.size() + " console proxy on host " + host.getId());
- }
- for(ConsoleProxyVO proxy : proxys) {
- usedMemory += proxy.getRamSize() * 1024L * 1024L;
- }
+ List proxys = _consoleProxyDao.listUpByHostId(host.getId());
+ if (s_logger.isDebugEnabled()) {
+ s_logger.debug("Found " + proxys.size() + " console proxy on host " + host.getId());
+ }
+ for(ConsoleProxyVO proxy : proxys) {
+ usedMemory += proxy.getRamSize() * 1024L * 1024L;
+ }
- List secStorageVms = _secStorgaeVmDao.listUpByHostId(host.getId());
- if (s_logger.isDebugEnabled()) {
- s_logger.debug("Found " + secStorageVms.size() + " secondary storage VM on host " + host.getId());
- }
- for(SecondaryStorageVmVO secStorageVm : secStorageVms) {
- usedMemory += secStorageVm.getRamSize() * 1024L * 1024L;
- }
+ List secStorageVms = _secStorgaeVmDao.listUpByHostId(host.getId());
+ if (s_logger.isDebugEnabled()) {
+ s_logger.debug("Found " + secStorageVms.size() + " secondary storage VM on host " + host.getId());
+ }
+ for(SecondaryStorageVmVO secStorageVm : secStorageVms) {
+ usedMemory += secStorageVm.getRamSize() * 1024L * 1024L;
+ }
- List vms = _userVmDao.listUpByHostId(host.getId());
- if (s_logger.isDebugEnabled()) {
- s_logger.debug("Found " + vms.size() + " user VM on host " + host.getId());
- }
+ List vms = _userVmDao.listUpByHostId(host.getId());
+ if (s_logger.isDebugEnabled()) {
+ s_logger.debug("Found " + vms.size() + " user VM on host " + host.getId());
+ }
- for (UserVmVO vm : vms) {
- ServiceOffering so = offeringsMap.get(vm.getServiceOfferingId());
- usedMemory += so.getRamSize() * 1024L * 1024L;
- cpu += so.getCpu() * (so.getSpeed() * 0.99);
- }
+ for (UserVmVO vm : vms) {
+ ServiceOffering so = offeringsMap.get(vm.getServiceOfferingId());
+ usedMemory += so.getRamSize() * 1024L * 1024L;
+ cpu += so.getCpu() * (so.getSpeed() * 0.99);
+ }
- long totalMemory = host.getTotalMemory();
+ long totalMemory = host.getTotalMemory();
- CapacityVO newMemoryCapacity = new CapacityVO(host.getId(), host.getDataCenterId(), host.getPodId(), usedMemory, totalMemory, CapacityVO.CAPACITY_TYPE_MEMORY);
- CapacityVO newCPUCapacity = new CapacityVO(host.getId(), host.getDataCenterId(), host.getPodId(), cpu, (long)(host.getCpus()*host.getSpeed()* _cpuOverProvisioningFactor), CapacityVO.CAPACITY_TYPE_CPU);
- newCapacities.add(newMemoryCapacity);
- newCapacities.add(newCPUCapacity);
+ CapacityVO newMemoryCapacity = new CapacityVO(host.getId(), host.getDataCenterId(), host.getPodId(), usedMemory, totalMemory, CapacityVO.CAPACITY_TYPE_MEMORY);
+ CapacityVO newCPUCapacity = new CapacityVO(host.getId(), host.getDataCenterId(), host.getPodId(), cpu, (long)(host.getCpus()*host.getSpeed()* _cpuOverProvisioningFactor), CapacityVO.CAPACITY_TYPE_CPU);
+ newCapacities.add(newMemoryCapacity);
+ newCapacities.add(newCPUCapacity);
+ }
}
// Calculate storage pool capacity
@@ -351,8 +357,12 @@ public class AlertManagerImpl implements AlertManager {
try {
txn.start();
// delete the old records
- _capacityDao.clearNonStorageCapacities();
-
+ if (_useNewNetworking) {
+ _capacityDao.clearNonStorageCapacities2();
+ } else {
+ _capacityDao.clearNonStorageCapacities();
+ }
+
for (CapacityVO newCapacity : newCapacities) {
s_logger.trace("Executing capacity update");
_capacityDao.persist(newCapacity);
diff --git a/server/src/com/cloud/api/ApiDBUtils.java b/server/src/com/cloud/api/ApiDBUtils.java
index 02a3f4a2a11..dca5ba28918 100755
--- a/server/src/com/cloud/api/ApiDBUtils.java
+++ b/server/src/com/cloud/api/ApiDBUtils.java
@@ -411,7 +411,7 @@ public class ApiDBUtils {
List vms = _userVmDao.listVmsUsingGuestIpAddress(addr.getDataCenterId(), guestIp);
if (vms != null) {
for (UserVmVO vm : vms) {
- if (vm.getAccountId() == addr.getAccountId()) {
+ if (vm.getAccountId() == addr.getAllocatedToAccountId()) {
return vm;
}
}
@@ -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/ApiDispatcher.java b/server/src/com/cloud/api/ApiDispatcher.java
index faf15d31f3f..23059e1d703 100644
--- a/server/src/com/cloud/api/ApiDispatcher.java
+++ b/server/src/com/cloud/api/ApiDispatcher.java
@@ -65,22 +65,22 @@ public class ApiDispatcher {
setupParameters(cmd, params);
try {
- cmd.callCreate();
+ cmd.create();
} catch (Throwable t) {
if (t instanceof InvalidParameterValueException || t instanceof IllegalArgumentException) {
- s_logger.info("Exception: ", t);
+ s_logger.info(t.getMessage());
throw new ServerApiException(BaseCmd.PARAM_ERROR, t.getMessage());
}else if (t instanceof PermissionDeniedException) {
- s_logger.info("Exception: ", t);
+ s_logger.info(t.getMessage());
throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, t.getMessage());
}else if (t instanceof AccountLimitException) {
- s_logger.info("Exception: ", t);
+ s_logger.info(t.getMessage());
throw new ServerApiException(BaseCmd.ACCOUNT_RESOURCE_LIMIT_ERROR, t.getMessage());
}else if (t instanceof InsufficientCapacityException) {
- s_logger.info("Exception: ", t);
+ s_logger.info(t.getMessage());
throw new ServerApiException(BaseCmd.INSUFFICIENT_CAPACITY_ERROR, t.getMessage());
}else if (t instanceof ResourceAllocationException) {
- s_logger.info("Exception: ", t);
+ s_logger.info(t.getMessage());
throw new ServerApiException(BaseCmd.RESOURCE_ALLOCATION_ERROR, t.getMessage());
}else if (t instanceof ResourceUnavailableException) {
s_logger.warn("Exception: ", t);
@@ -106,16 +106,16 @@ public class ApiDispatcher {
cmd.execute();
} catch (Throwable t) {
if (t instanceof InvalidParameterValueException || t instanceof IllegalArgumentException) {
- s_logger.info("Exception: ", t);
+ s_logger.info(t.getMessage());
throw new ServerApiException(BaseCmd.PARAM_ERROR, t.getMessage());
}else if (t instanceof PermissionDeniedException) {
- s_logger.info("Exception: ", t);
+ s_logger.info(t.getMessage());
throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, t.getMessage());
}else if (t instanceof AccountLimitException) {
- s_logger.info("Exception: ", t);
+ s_logger.info(t.getMessage());
throw new ServerApiException(BaseCmd.ACCOUNT_RESOURCE_LIMIT_ERROR, t.getMessage());
}else if (t instanceof InsufficientCapacityException) {
- s_logger.info("Exception: ", t);
+ s_logger.info(t.getMessage());
throw new ServerApiException(BaseCmd.INSUFFICIENT_CAPACITY_ERROR, t.getMessage());
}else if (t instanceof ResourceAllocationException) {
s_logger.warn("Exception: ", t);
diff --git a/server/src/com/cloud/api/ApiResponseHelper.java b/server/src/com/cloud/api/ApiResponseHelper.java
index 9cf9bab0f60..67595f6ee02 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;
@@ -347,7 +346,7 @@ public class ApiResponseHelper implements ResponseGenerator {
offeringResponse.setCreated(offering.getCreated());
offeringResponse.setStorageType(offering.getUseLocalStorage() ? "local" : "shared");
offeringResponse.setOfferHa(offering.getOfferHA());
- offeringResponse.setUseVirtualNetwork(offering.getGuestIpType().equals(GuestIpType.Virtualized));
+ offeringResponse.setUseVirtualNetwork(offering.getGuestIpType().equals(GuestIpType.Virtual));
offeringResponse.setTags(offering.getTags());
if(offering.getDomainId() != null){
offeringResponse.setDomain(ApiDBUtils.findDomainById(offering.getDomainId()).getName());
@@ -498,7 +497,7 @@ public class ApiResponseHelper implements ResponseGenerator {
userVmResponse.setCpuNumber(offering.getCpu());
userVmResponse.setCpuSpeed(offering.getSpeed());
userVmResponse.setMemory(offering.getRamSize());
- userVmResponse.setForVirtualNetwork(offering.getGuestIpType().equals(GuestIpType.Virtualized));
+ userVmResponse.setForVirtualNetwork(offering.getGuestIpType().equals(GuestIpType.Virtual));
VolumeVO rootVolume = ApiDBUtils.findRootVolume(userVm.getId());
if (rootVolume != null) {
@@ -768,20 +767,20 @@ public class ApiResponseHelper implements ResponseGenerator {
@Override
public IPAddressResponse createIPAddressResponse(IpAddress ipAddress) {
- VlanVO vlan = ApiDBUtils.findVlanById(ipAddress.getVlanDbId());
+ VlanVO vlan = ApiDBUtils.findVlanById(ipAddress.getVlanId());
boolean forVirtualNetworks = vlan.getVlanType().equals(VlanType.VirtualNetwork);
IPAddressResponse ipResponse = new IPAddressResponse();
ipResponse.setIpAddress(ipAddress.getAddress());
- if (ipAddress.getAllocated() != null) {
- ipResponse.setAllocated(ipAddress.getAllocated());
+ if (ipAddress.getAllocatedTime() != null) {
+ ipResponse.setAllocated(ipAddress.getAllocatedTime());
}
ipResponse.setZoneId(ipAddress.getDataCenterId());
ipResponse.setZoneName(ApiDBUtils.findZoneById(ipAddress.getDataCenterId()).getName());
ipResponse.setSourceNat(ipAddress.isSourceNat());
// get account information
- Account accountTemp = ApiDBUtils.findAccountById(ipAddress.getAccountId());
+ Account accountTemp = ApiDBUtils.findAccountById(ipAddress.getAllocatedToAccountId());
if (accountTemp != null) {
ipResponse.setAccountName(accountTemp.getAccountName());
ipResponse.setDomainId(accountTemp.getDomainId());
@@ -794,8 +793,8 @@ public class ApiResponseHelper implements ResponseGenerator {
// show this info to admin only
Account account = UserContext.current().getAccount();
if ((account == null) || account.getType() == Account.ACCOUNT_TYPE_ADMIN) {
- ipResponse.setVlanId(ipAddress.getVlanDbId());
- ipResponse.setVlanName(ApiDBUtils.findVlanById(ipAddress.getVlanDbId()).getVlanId());
+ ipResponse.setVlanId(ipAddress.getVlanId());
+ ipResponse.setVlanName(ApiDBUtils.findVlanById(ipAddress.getVlanId()).getVlanId());
}
ipResponse.setObjectName("ipaddress");
return ipResponse;
@@ -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());
@@ -2308,7 +2307,6 @@ public class ApiResponseHelper implements ResponseGenerator {
response.setMaxconnections(offering.getConcurrentConnections());
response.setIsDefault(offering.isDefault());
response.setSpecifyVlan(offering.getSpecifyVlan());
- response.setIsShared(offering.isShared());
response.setObjectName("networkoffering");
return response;
}
@@ -2326,12 +2324,12 @@ public class ApiResponseHelper implements ResponseGenerator {
response.setBroadcastUri(network.getBroadcastUri().toString());
}
- if (response.getTrafficType() != null) {
- response.setTrafficType(network.getTrafficType().toString());
+ if (network.getTrafficType() != null) {
+ response.setTrafficType(network.getTrafficType().name());
}
- if (response.getType() != null) {
- response.setType(network.getGuestType().toString());
+ if (network.getGuestType() != null) {
+ response.setType(network.getGuestType().name());
}
response.setGateway(network.getGateway());
response.setCidr(network.getCidr());
@@ -2344,6 +2342,8 @@ public class ApiResponseHelper implements ResponseGenerator {
response.setNetworkOfferingName(networkOffering.getName());
response.setNetworkOfferingDisplayText(networkOffering.getDisplayText());
}
+
+ response.setIsShared(network.isShared());
response.setState(network.getState().toString());
response.setRelated(network.getRelated());
response.setDns1(network.getDns1());
diff --git a/server/src/com/cloud/api/ApiServer.java b/server/src/com/cloud/api/ApiServer.java
index 4a307839a64..b820290ee69 100755
--- a/server/src/com/cloud/api/ApiServer.java
+++ b/server/src/com/cloud/api/ApiServer.java
@@ -373,7 +373,7 @@ public class ApiServer implements HttpRequestHandler {
if (cmdObj instanceof BaseAsyncCreateCmd) {
BaseAsyncCreateCmd createCmd = (BaseAsyncCreateCmd)cmdObj;
_dispatcher.dispatchCreateCmd(createCmd, params);
- objectId = createCmd.getId();
+ objectId = createCmd.getEntityId();
params.put("id", objectId.toString());
} else {
ApiDispatcher.setupParameters(cmdObj, params);
@@ -389,7 +389,7 @@ public class ApiServer implements HttpRequestHandler {
}
// save the scheduled event
- Long eventId = EventUtils.saveScheduledEvent((userId == null) ? User.UID_SYSTEM : userId, asyncCmd.getAccountId(),
+ Long eventId = EventUtils.saveScheduledEvent((userId == null) ? User.UID_SYSTEM : userId, asyncCmd.getEntityOwnerId(),
asyncCmd.getEventType(), asyncCmd.getEventDescription());
if (eventId != null) {
diff --git a/server/src/com/cloud/async/AsyncJobExecutorContext.java b/server/src/com/cloud/async/AsyncJobExecutorContext.java
index 0a565dacb2b..47cab5bed85 100644
--- a/server/src/com/cloud/async/AsyncJobExecutorContext.java
+++ b/server/src/com/cloud/async/AsyncJobExecutorContext.java
@@ -32,6 +32,7 @@ import com.cloud.user.dao.AccountDao;
import com.cloud.user.dao.UserDao;
import com.cloud.utils.component.Manager;
import com.cloud.vm.UserVmManager;
+import com.cloud.vm.VmManager;
import com.cloud.vm.dao.DomainRouterDao;
import com.cloud.vm.dao.UserVmDao;
@@ -51,4 +52,5 @@ public interface AsyncJobExecutorContext extends Manager {
public IPAddressDao getIpAddressDao();
public AsyncJobDao getJobDao();
public UserDao getUserDao();
+ public VmManager getItMgr();
}
diff --git a/server/src/com/cloud/async/AsyncJobExecutorContextImpl.java b/server/src/com/cloud/async/AsyncJobExecutorContextImpl.java
index cf000e8566a..5f0f489b612 100644
--- a/server/src/com/cloud/async/AsyncJobExecutorContextImpl.java
+++ b/server/src/com/cloud/async/AsyncJobExecutorContextImpl.java
@@ -37,6 +37,7 @@ import com.cloud.user.dao.AccountDao;
import com.cloud.user.dao.UserDao;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.vm.UserVmManager;
+import com.cloud.vm.VmManager;
import com.cloud.vm.dao.DomainRouterDao;
import com.cloud.vm.dao.UserVmDao;
@@ -57,7 +58,8 @@ public class AsyncJobExecutorContextImpl implements AsyncJobExecutorContext {
private DomainRouterDao _routerDao;
private IPAddressDao _ipAddressDao;
private AsyncJobDao _jobDao;
- private UserDao _userDao;
+ private UserDao _userDao;
+ private VmManager _itMgr;
private ManagementServer _managementServer;
@@ -138,6 +140,11 @@ public class AsyncJobExecutorContextImpl implements AsyncJobExecutorContext {
public UserDao getUserDao() {
return _userDao;
}
+
+ @Override
+ public VmManager getItMgr() {
+ return _itMgr;
+ }
@Override
public boolean configure(String name, Map params) throws ConfigurationException {
@@ -218,7 +225,11 @@ public class AsyncJobExecutorContextImpl implements AsyncJobExecutorContext {
if(_userDao == null) {
throw new ConfigurationException("unable to get " + UserDao.class.getName());
}
-
+
+ _itMgr = locator.getManager(VmManager.class);
+ if (_itMgr == null) {
+ throw new ConfigurationException("unable to get " + VmManager.class.getName());
+ }
return true;
}
diff --git a/server/src/com/cloud/async/executor/DestroyVMExecutor.java b/server/src/com/cloud/async/executor/DestroyVMExecutor.java
index a2ab04a6139..17027ea8a20 100644
--- a/server/src/com/cloud/async/executor/DestroyVMExecutor.java
+++ b/server/src/com/cloud/async/executor/DestroyVMExecutor.java
@@ -100,7 +100,7 @@ public class DestroyVMExecutor extends VMOperationExecutor {
txn.start();
asyncMgr.getExecutorContext().getAccountMgr().decrementResourceCount(vm.getAccountId(), ResourceType.user_vm);
- if (!asyncMgr.getExecutorContext().getVmDao().updateIf(vm, VirtualMachine.Event.DestroyRequested, vm.getHostId())) {
+ if (!asyncMgr.getExecutorContext().getItMgr().stateTransitTo(vm, VirtualMachine.Event.DestroyRequested, vm.getHostId())) {
s_logger.debug("Unable to destroy the vm because it is not in the correct state: " + vm.toString());
txn.rollback();
@@ -130,7 +130,7 @@ public class DestroyVMExecutor extends VMOperationExecutor {
asyncMgr.completeAsyncJob(getJob().getId(), AsyncJobResult.STATUS_SUCCEEDED, 0, "success");
} else {
- asyncMgr.getExecutorContext().getVmDao().updateIf(vm, Event.OperationFailed, vm.getHostId());
+ asyncMgr.getExecutorContext().getItMgr().stateTransitTo(vm, Event.OperationFailed, vm.getHostId());
asyncMgr.completeAsyncJob(getJob().getId(),
AsyncJobResult.STATUS_FAILED, BaseCmd.INTERNAL_ERROR, "Agent failed to stop VM: " + vm.getHostName());
// managementServer.saveEvent(param.getUserId(), vm.getAccountId(), EventVO.LEVEL_ERROR, EventTypes.EVENT_VM_STOP,
diff --git a/server/src/com/cloud/async/executor/DisassociateIpAddressExecutor.java b/server/src/com/cloud/async/executor/DisassociateIpAddressExecutor.java
index 4021189b35e..fadc692ce81 100644
--- a/server/src/com/cloud/async/executor/DisassociateIpAddressExecutor.java
+++ b/server/src/com/cloud/async/executor/DisassociateIpAddressExecutor.java
@@ -98,7 +98,7 @@ public class DisassociateIpAddressExecutor extends BaseAsyncJobExecutor {
if (ip.isSourceNat()) {
router = routerDao.findByPublicIpAddress(param.getIpAddress());
} else {
- router = routerDao.findBy(ip.getAccountId(), ip.getDataCenterId());
+ router = routerDao.findBy(ip.getAllocatedToAccountId(), ip.getDataCenterId());
}
return router;
diff --git a/server/src/com/cloud/async/executor/StopVMExecutor.java b/server/src/com/cloud/async/executor/StopVMExecutor.java
index be09425fdd3..c2ab1d358b0 100644
--- a/server/src/com/cloud/async/executor/StopVMExecutor.java
+++ b/server/src/com/cloud/async/executor/StopVMExecutor.java
@@ -92,7 +92,7 @@ public class StopVMExecutor extends VMOperationExecutor {
AsyncJobResult.STATUS_SUCCEEDED, 0, VMExecutorHelper.composeResultObject(asyncMgr.getExecutorContext().getManagementServer(), vm, null));
jobStatusUpdated = true;
} else {
- asyncMgr.getExecutorContext().getVmDao().updateIf(vm, Event.OperationFailed, vm.getHostId());
+ asyncMgr.getExecutorContext().getItMgr().stateTransitTo(vm, Event.OperationFailed, vm.getHostId());
asyncMgr.completeAsyncJob(getJob().getId(),
AsyncJobResult.STATUS_FAILED, BaseCmd.INTERNAL_ERROR, "Agent failed to stop VM");
jobStatusUpdated = true;
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/capacity/dao/CapacityDao.java b/server/src/com/cloud/capacity/dao/CapacityDao.java
index 726544f4384..9d26287abce 100644
--- a/server/src/com/cloud/capacity/dao/CapacityDao.java
+++ b/server/src/com/cloud/capacity/dao/CapacityDao.java
@@ -20,8 +20,12 @@ package com.cloud.capacity.dao;
import com.cloud.capacity.CapacityVO;
import com.cloud.utils.db.GenericDao;
+import com.cloud.vm.VMInstanceVO;
public interface CapacityDao extends GenericDao {
void clearNonStorageCapacities();
- void clearStorageCapacities();
+ void clearStorageCapacities();
+ CapacityVO findByHostIdType(Long hostId, short capacityType);
+ void clearNonStorageCapacities2();
+
}
diff --git a/server/src/com/cloud/capacity/dao/CapacityDaoImpl.java b/server/src/com/cloud/capacity/dao/CapacityDaoImpl.java
index e6e8d4dba25..6a23621a2de 100644
--- a/server/src/com/cloud/capacity/dao/CapacityDaoImpl.java
+++ b/server/src/com/cloud/capacity/dao/CapacityDaoImpl.java
@@ -25,8 +25,13 @@ import javax.ejb.Local;
import org.apache.log4j.Logger;
import com.cloud.capacity.CapacityVO;
+import com.cloud.service.ServiceOfferingVO;
+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.vm.VMInstanceVO;
@Local(value = { CapacityDao.class })
public class CapacityDaoImpl extends GenericDaoBase implements CapacityDao {
@@ -35,8 +40,17 @@ public class CapacityDaoImpl extends GenericDaoBase implements
private static final String ADD_ALLOCATED_SQL = "UPDATE `cloud`.`op_host_capacity` SET used_capacity = used_capacity + ? WHERE host_id = ? AND capacity_type = ?";
private static final String SUBTRACT_ALLOCATED_SQL = "UPDATE `cloud`.`op_host_capacity` SET used_capacity = used_capacity - ? WHERE host_id = ? AND capacity_type = ?";
private static final String CLEAR_STORAGE_CAPACITIES = "DELETE FROM `cloud`.`op_host_capacity` WHERE capacity_type=2 OR capacity_type=3 OR capacity_type=6"; //clear storage and secondary_storage capacities
- private static final String CLEAR_NON_STORAGE_CAPACITIES = "DELETE FROM `cloud`.`op_host_capacity` WHERE capacity_type<>2 AND capacity_type<>3 AND capacity_type<>6"; //clear non-storage and non-secondary_storage capacities
-
+ private static final String CLEAR_NON_STORAGE_CAPACITIES = "DELETE FROM `cloud`.`op_host_capacity` WHERE capacity_type<>2 AND capacity_type<>3 AND capacity_type<>6"; //clear non-storage and non-secondary_storage capacities
+ private static final String CLEAR_NON_STORAGE_CAPACITIES2 = "DELETE FROM `cloud`.`op_host_capacity` WHERE capacity_type<>2 AND capacity_type<>3 AND capacity_type<>6 AND capacity_type<>0 AND capacity_type<>1"; //clear non-storage and non-secondary_storage capacities
+ private SearchBuilder _hostIdTypeSearch;
+
+ public CapacityDaoImpl() {
+ _hostIdTypeSearch = createSearchBuilder();
+ _hostIdTypeSearch.and("hostId", _hostIdTypeSearch.entity().getHostOrPoolId(), SearchCriteria.Op.EQ);
+ _hostIdTypeSearch.and("type", _hostIdTypeSearch.entity().getCapacityType(), SearchCriteria.Op.EQ);
+ _hostIdTypeSearch.done();
+ }
+
public void updateAllocated(Long hostId, long allocatedAmount, short capacityType, boolean add) {
Transaction txn = Transaction.currentTxn();
PreparedStatement pstmt = null;
@@ -75,6 +89,22 @@ public class CapacityDaoImpl extends GenericDaoBase implements
txn.rollback();
s_logger.warn("Exception clearing non storage capacities", e);
}
+ }
+
+ @Override
+ public void clearNonStorageCapacities2() {
+ Transaction txn = Transaction.currentTxn();
+ PreparedStatement pstmt = null;
+ try {
+ txn.start();
+ String sql = CLEAR_NON_STORAGE_CAPACITIES2;
+ pstmt = txn.prepareAutoCloseStatement(sql);
+ pstmt.executeUpdate();
+ txn.commit();
+ } catch (Exception e) {
+ txn.rollback();
+ s_logger.warn("Exception clearing non storage capacities", e);
+ }
}
@Override
@@ -91,5 +121,13 @@ public class CapacityDaoImpl extends GenericDaoBase implements
txn.rollback();
s_logger.warn("Exception clearing storage capacities", e);
}
+ }
+
+ @Override
+ public CapacityVO findByHostIdType(Long hostId, short capacityType) {
+ SearchCriteria sc = _hostIdTypeSearch.create();
+ sc.setParameters("hostId", hostId);
+ sc.setParameters("type", capacityType);
+ return findOneBy(sc);
}
}
diff --git a/server/src/com/cloud/configuration/Config.java b/server/src/com/cloud/configuration/Config.java
index 7c635d030a1..b0b82cbc4b3 100644
--- a/server/src/com/cloud/configuration/Config.java
+++ b/server/src/com/cloud/configuration/Config.java
@@ -129,7 +129,7 @@ public enum Config {
RouterCleanupInterval("Advanced", ManagementServer.class, Integer.class, "router.cleanup.interval", "3600", "Time in seconds identifies when to stop router when there are no user vms associated with it", null),
RouterStatsInterval("Advanced", NetworkManager.class, Integer.class, "router.stats.interval", "300", "Interval to report router statistics.", null),
RouterTemplateId("Advanced", NetworkManager.class, Long.class, "router.template.id", "1", "Default ID for template.", null),
- StartRetry("Advanced", AgentManager.class, Integer.class, "start.retry", "2", "Number of times to retry create and start commands", null),
+ StartRetry("Advanced", AgentManager.class, Integer.class, "start.retry", "10", "Number of times to retry create and start commands", null),
StopRetryInterval("Advanced", HighAvailabilityManager.class, Integer.class, "stop.retry.interval", "600", "Time in seconds between retries to stop or destroy a vm" , null),
StorageCleanupInterval("Advanced", StorageManager.class, Integer.class, "storage.cleanup.interval", "86400", "The interval to wait before running the storage cleanup thread.", null),
StorageCleanupEnabled("Advanced", StorageManager.class, Boolean.class, "storage.cleanup.enabled", "true", "Enables/disables the storage cleanup thread.", null),
@@ -184,6 +184,10 @@ public enum Config {
VmwarePublicNetworkVSwitch("Advanced", ManagementServer.class, String.class, "vmware.public.vswitch", null, "Specify the vSwitch on host for public network", null),
VmwareGuestNetworkVSwitch("Advanced", ManagementServer.class, String.class, "vmware.guest.vswitch", null, "Specify the vSwitch on host for guest network", null),
+ // KVM
+ KvmPublicNetwork("Advanced", ManagementServer.class, String.class, "kvm.public.network.device", null, "Specify the public bridge on host for public network", null),
+ KvmPrivateNetwork("Advanced", ManagementServer.class, String.class, "kvm.private.network.device", null, "Specify the private bridge on host for private network", null),
+
// Premium
UsageExecutionTimezone("Premium", ManagementServer.class, String.class, "usage.execution.timezone", null, "The timezone to use for usage job execution time", null),
@@ -199,7 +203,7 @@ public enum Config {
SSOAuthTolerance("Advanced", ManagementServer.class, Long.class, "security.singlesignon.tolerance.millis", "300000", "The allowable clock difference in milliseconds between when an SSO login request is made and when it is received.", null),
NetworkType("Hidden", ManagementServer.class, String.class, "network.type", "vlan", "The type of network that this deployment will use.", "vlan,direct"),
HashKey("Hidden", ManagementServer.class, String.class, "security.hash.key", null, "for generic key-ed hash", null),
- UseNewNetwork("Hidden", NetworkManager.class, Boolean.class, "use.new.networking", "false", null, null);
+ UseNewNetwork("Hidden", NetworkManager.class, Boolean.class, "use.new.networking", "true", null, null);
private final String _category;
private final Class> _componentClass;
diff --git a/server/src/com/cloud/configuration/ConfigurationManager.java b/server/src/com/cloud/configuration/ConfigurationManager.java
index 7af2974a5fc..53a87936bde 100644
--- a/server/src/com/cloud/configuration/ConfigurationManager.java
+++ b/server/src/com/cloud/configuration/ConfigurationManager.java
@@ -170,17 +170,17 @@ public interface ConfigurationManager extends Manager {
/**
* Creates a new network offering
- * @param id
- * @param name
- * @param displayText
- * @param type
- * @param trafficType
- * @param tags
- * @param maxConnections
+ * @param name
+ * @param displayText
+ * @param type
+ * @param trafficType
+ * @param tags
+ * @param maxConnections
+ * @param id
* @param specifyVlan;
* @return network offering object
*/
- NetworkOfferingVO createNetworkOffering(long userId, String name, String displayText, GuestIpType type, TrafficType trafficType, String tags, Integer maxConnections, boolean specifyVlan, boolean isShared);
+ NetworkOfferingVO createNetworkOffering(long userId, String name, String displayText, GuestIpType type, TrafficType trafficType, String tags, Integer maxConnections, boolean specifyVlan);
Vlan createVlanAndPublicIpRange(Long userId, Long zoneId, Long podId, String startIP, String endIP, String vlanGateway, String vlanNetmask, boolean forVirtualNetwork, String vlanId, Account account, Long networkId) throws InsufficientCapacityException, ConcurrentOperationException, InvalidParameterValueException;
diff --git a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java
index 22547a2b5a5..b34daa5cadb 100755
--- a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java
+++ b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java
@@ -1162,7 +1162,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura
String multicastRateStr = _configDao.getValue("multicast.throttling.rate");
int networkRate = ((networkRateStr == null) ? 200 : Integer.parseInt(networkRateStr));
int multicastRate = ((multicastRateStr == null) ? 10 : Integer.parseInt(multicastRateStr));
- NetworkOffering.GuestIpType guestIpType = useVirtualNetwork ? NetworkOffering.GuestIpType.Virtualized : NetworkOffering.GuestIpType.DirectSingle;
+ NetworkOffering.GuestIpType guestIpType = useVirtualNetwork ? NetworkOffering.GuestIpType.Virtual : NetworkOffering.GuestIpType.Direct;
tags = cleanupTags(tags);
ServiceOfferingVO offering = new ServiceOfferingVO(name, cpu, ramSize, speed, networkRate, multicastRate, offerHA, displayText, guestIpType, localStorageRequired, false, tags, false,domainId);
@@ -1216,7 +1216,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura
}
if (useVirtualNetwork != null) {
- NetworkOffering.GuestIpType guestIpType = useVirtualNetwork ? NetworkOffering.GuestIpType.Virtualized : NetworkOffering.GuestIpType.DirectSingle;
+ NetworkOffering.GuestIpType guestIpType = useVirtualNetwork ? NetworkOffering.GuestIpType.Virtual : NetworkOffering.GuestIpType.Direct;
offering.setGuestIpType(guestIpType);
}
@@ -1248,7 +1248,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura
if (_serviceOfferingDao.update(id, offering)) {
offering = _serviceOfferingDao.findById(id);
saveConfigurationEvent(userId, null, EventTypes.EVENT_SERVICE_OFFERING_EDIT, "Successfully updated service offering with name: " + offering.getName() + ".", "soId=" + offering.getId(), "name=" + offering.getName(),
- "displayText=" + offering.getDisplayText(), "offerHA=" + offering.getOfferHA(), "useVirtualNetwork=" + (offering.getGuestIpType() == NetworkOffering.GuestIpType.Virtualized), "tags=" + offering.getTags(), "domainId=" + offering.getDomainId());
+ "displayText=" + offering.getDisplayText(), "offerHA=" + offering.getOfferHA(), "useVirtualNetwork=" + (offering.getGuestIpType() == NetworkOffering.GuestIpType.Virtual), "tags=" + offering.getTags(), "domainId=" + offering.getDomainId());
return offering;
} else {
return null;
@@ -1284,7 +1284,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura
Long numGibibytes = cmd.getDiskSize();
Boolean isCustomized = cmd.isCustomized() != null ? cmd.isCustomized() : false; //false by default
String tags = cmd.getTags();
- Long domainId = Long.valueOf(DomainVO.ROOT_DOMAIN); // disk offering always gets created under the root domain.Bug # 6055
+ Long domainId = cmd.getDomainId() != null ? cmd.getDomainId() : Long.valueOf(DomainVO.ROOT_DOMAIN); // disk offering always gets created under the root domain.Bug # 6055 if not passed in cmd
if(!isCustomized && numGibibytes == null){
throw new InvalidParameterValueException("Disksize is required for non-customized disk offering");
@@ -1395,7 +1395,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura
if (_serviceOfferingDao.remove(offeringId)) {
saveConfigurationEvent(userId, null, EventTypes.EVENT_SERVICE_OFFERING_EDIT, "Successfully deleted service offering with name: " + offering.getName(), "soId=" + offeringId, "name=" + offering.getName(),
- "displayText=" + offering.getDisplayText(), "offerHA=" + offering.getOfferHA(), "useVirtualNetwork=" + (offering.getGuestIpType() == GuestIpType.Virtualized));
+ "displayText=" + offering.getDisplayText(), "offerHA=" + offering.getOfferHA(), "useVirtualNetwork=" + (offering.getGuestIpType() == GuestIpType.Virtual));
return true;
} else {
return false;
@@ -2391,7 +2391,6 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura
String typeString = cmd.getType();
String trafficTypeString = cmd.getTraffictype();
Boolean specifyVlan = cmd.getSpecifyVlan();
- Boolean isShared = cmd.getIsShared();
TrafficType trafficType = null;
GuestIpType type = null;
@@ -2418,23 +2417,19 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura
if (specifyVlan == null) {
specifyVlan = false;
}
-
- if (isShared == null) {
- isShared = false;
- }
Integer maxConnections = cmd.getMaxconnections();
- return createNetworkOffering(userId, name, displayText, type, trafficType, tags, maxConnections, specifyVlan, isShared);
+ return createNetworkOffering(userId, name, displayText, type, trafficType, tags, maxConnections, specifyVlan);
}
@Override
- public NetworkOfferingVO createNetworkOffering(long userId, String name, String displayText, GuestIpType type, TrafficType trafficType, String tags, Integer maxConnections, boolean specifyVlan, boolean isShared) {
+ public NetworkOfferingVO createNetworkOffering(long userId, String name, String displayText, GuestIpType type, TrafficType trafficType, String tags, Integer maxConnections, boolean specifyVlan) {
String networkRateStr = _configDao.getValue("network.throttling.rate");
String multicastRateStr = _configDao.getValue("multicast.throttling.rate");
int networkRate = ((networkRateStr == null) ? 200 : Integer.parseInt(networkRateStr));
int multicastRate = ((multicastRateStr == null) ? 10 : Integer.parseInt(multicastRateStr));
tags = cleanupTags(tags);
- NetworkOfferingVO offering = new NetworkOfferingVO(name, displayText, trafficType, type, false, specifyVlan, networkRate, multicastRate, maxConnections, isShared, false);
+ NetworkOfferingVO offering = new NetworkOfferingVO(name, displayText, trafficType, type, false, specifyVlan, networkRate, multicastRate, maxConnections, false);
if ((offering = _networkOfferingDao.persist(offering)) != null) {
saveConfigurationEvent(userId, null, EventTypes.EVENT_NETWORK_OFFERING_CREATE, "Successfully created new network offering with name: " + name + ".", "noId=" + offering.getId(), "name=" + name,
diff --git a/server/src/com/cloud/configuration/DefaultComponentLibrary.java b/server/src/com/cloud/configuration/DefaultComponentLibrary.java
index fe1c9f8cbdc..b1ba2a8b619 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;
@@ -68,7 +69,10 @@ 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.rules.RulesManagerImpl;
+import com.cloud.network.rules.dao.PortForwardingRulesDaoImpl;
import com.cloud.network.security.NetworkGroupManagerImpl;
import com.cloud.network.security.dao.IngressRuleDaoImpl;
import com.cloud.network.security.dao.NetworkGroupDaoImpl;
@@ -126,7 +130,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 +227,8 @@ public class DefaultComponentLibrary implements ComponentLibrary {
addDao("RemoteAccessVpnDao", RemoteAccessVpnDaoImpl.class);
addDao("VpnUserDao", VpnUserDaoImpl.class);
addDao("ItWorkDao", ItWorkDaoImpl.class);
+ addDao("FirewallRulesDao", FirewallRulesDaoImpl.class);
+ addDao("PortForwardingRulesDao", PortForwardingRulesDaoImpl.class);
}
Map> _managers = new HashMap>();
@@ -274,6 +280,8 @@ public class DefaultComponentLibrary implements ComponentLibrary {
addManager("VmManager", MauriceMoss.class);
addManager("DomainRouterManager", DomainRouterManagerImpl.class);
addManager("EntityManager", EntityManagerImpl.class);
+ addManager("LoadBalancingRulesManager", LoadBalancingRulesManagerImpl.class);
+ addManager("RulesManager", RulesManagerImpl.class);
}
protected List> addAdapterChain(Class interphace, List>> adapters) {
@@ -311,4 +319,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/consoleproxy/ConsoleProxyManagerImpl.java b/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java
index 6e299080619..ade8af45c69 100644
--- a/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java
+++ b/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java
@@ -136,7 +136,6 @@ import com.cloud.user.Account;
import com.cloud.user.AccountService;
import com.cloud.user.AccountVO;
import com.cloud.user.User;
-import com.cloud.user.UserVO;
import com.cloud.user.dao.AccountDao;
import com.cloud.utils.DateUtil;
import com.cloud.utils.NumbersUtil;
@@ -330,8 +329,9 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
}
ConsoleProxyVO proxy = result.second();
- if (proxy == null)
+ if (proxy == null) {
return null;
+ }
return new ConsoleProxyInfo(proxy.isSslEnabled(), proxy.getPublicIpAddress(), _consoleProxyPort, proxy.getPort(), _configDao.getValue("consoleproxy.url.domain"));
}
@@ -384,25 +384,29 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
// storage and computing
// resource may be allocated and assigned in another pod
//
- if (s_logger.isInfoEnabled())
+ if (s_logger.isInfoEnabled()) {
s_logger.info("Unable to start console proxy, proxy vm Id : " + proxyVmId + " will recycle it and restart a new one");
+ }
destroyProxy(proxyVmId, 0);
return null;
} else {
- if (s_logger.isTraceEnabled())
+ if (s_logger.isTraceEnabled()) {
s_logger.trace("Console proxy " + proxy.getHostName() + " is started");
+ }
// if it is a new assignment or a changed assignment,
// update the
// record
- if (vm.getProxyId() == null || vm.getProxyId().longValue() != proxy.getId())
+ if (vm.getProxyId() == null || vm.getProxyId().longValue() != proxy.getId()) {
_instanceDao.updateProxyId(vmId, proxy.getId(), DateUtil.currentGMTTime());
+ }
proxy.setSslEnabled(_sslEnabled);
- if (_sslEnabled)
+ if (_sslEnabled) {
proxy.setPort(443);
- else
+ } else {
proxy.setPort(80);
+ }
return proxy;
}
} finally {
@@ -424,8 +428,9 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
VMInstanceVO vm = this._instanceDao.findById(vmId);
if (vm != null && vm.getState() != State.Running) {
- if (s_logger.isInfoEnabled())
+ if (s_logger.isInfoEnabled()) {
s_logger.info("Detected that vm : " + vmId + " is not currently at running state, we will fail the proxy assignment for it");
+ }
return null;
}
@@ -434,16 +439,19 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
if (proxy != null) {
if (!isInAssignableState(proxy)) {
- if (s_logger.isInfoEnabled())
+ if (s_logger.isInfoEnabled()) {
s_logger.info("A previous assigned proxy is not assignable now, reassign console proxy for user vm : " + vmId);
+ }
proxy = null;
} else {
if (_consoleProxyDao.getProxyActiveLoad(proxy.getId()) < _capacityPerProxy || hasPreviousSession(proxy, vm)) {
- if (s_logger.isTraceEnabled())
+ if (s_logger.isTraceEnabled()) {
s_logger.trace("Assign previous allocated console proxy for user vm : " + vmId);
+ }
- if (proxy.getActiveSession() >= _capacityPerProxy)
+ if (proxy.getActiveSession() >= _capacityPerProxy) {
s_logger.warn("Assign overloaded proxy to user VM as previous session exists, user vm : " + vmId);
+ }
} else {
proxy = null;
}
@@ -451,24 +459,28 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
}
}
- if (proxy == null)
+ if (proxy == null) {
proxy = assignProxyFromRunningPool(dataCenterId);
+ }
if (proxy == null) {
- if (s_logger.isInfoEnabled())
+ if (s_logger.isInfoEnabled()) {
s_logger.info("No running console proxy is available, check to see if we can bring up a stopped one for data center : "
+ dataCenterId);
+ }
proxy = assignProxyFromStoppedPool(dataCenterId);
if (proxy == null) {
- if (s_logger.isInfoEnabled())
+ if (s_logger.isInfoEnabled()) {
s_logger.info("No stopped console proxy is available, need to allocate a new console proxy for data center : " + dataCenterId);
+ }
proxy = startNew(dataCenterId);
} else {
- if (s_logger.isInfoEnabled())
+ if (s_logger.isInfoEnabled()) {
s_logger.info("Found a stopped console proxy, bring it up to running pool. proxy vm id : " + proxy.getId() + ", data center : "
+ dataCenterId);
+ }
proxyFromStoppedPool[0] = new Boolean(true);
}
@@ -480,8 +492,9 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
private static boolean isInAssignableState(ConsoleProxyVO proxy) {
// console proxies that are in states of being able to serve user VM
State state = proxy.getState();
- if (state == State.Running || state == State.Starting || state == State.Creating || state == State.Migrating)
+ if (state == State.Running || state == State.Starting || state == State.Creating || state == State.Migrating) {
return true;
+ }
return false;
}
@@ -511,8 +524,9 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
s_logger.warn("Unable to parse console proxy connection info passed through tag: " + connections[i].tag, e);
}
}
- if (taggedVmId == vm.getId())
+ if (taggedVmId == vm.getId()) {
return true;
+ }
}
//
@@ -520,8 +534,9 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
// received load-update yet
// wait until session time
//
- if (DateUtil.currentGMTTime().getTime() - vm.getProxyAssignTime().getTime() < _proxySessionTimeoutValue)
+ if (DateUtil.currentGMTTime().getTime() - vm.getProxyAssignTime().getTime() < _proxySessionTimeoutValue) {
return true;
+ }
return false;
} else {
@@ -568,8 +583,9 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
if (asyncExecutor != null) {
AsyncJobVO job = asyncExecutor.getJob();
- if (s_logger.isInfoEnabled())
+ if (s_logger.isInfoEnabled()) {
s_logger.info("Start console proxy " + proxyId + ", update async job-" + job.getId());
+ }
_asyncMgr.updateAsyncJobAttachment(job.getId(), "console_proxy", proxyId);
}
@@ -594,14 +610,16 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
State state = proxy.getState();
if (state == State.Starting /* || state == State.Migrating */) {
- if (s_logger.isDebugEnabled())
+ if (s_logger.isDebugEnabled()) {
s_logger.debug("Waiting console proxy to be ready, proxy vm id : " + proxyId + " proxy VM state : " + state.toString());
+ }
if (proxy.getPrivateIpAddress() == null || connect(proxy.getPrivateIpAddress(), _proxyCmdPort) != null) {
- if (proxy.getPrivateIpAddress() == null)
+ if (proxy.getPrivateIpAddress() == null) {
s_logger.warn("Retruning a proxy that is being started but private IP has not been allocated yet, proxy vm id : " + proxyId);
- else
+ } else {
s_logger.warn("Waiting console proxy to be ready timed out, proxy vm id : " + proxyId);
+ }
// TODO, it is very tricky here, if the startup process
// takes too long and it timed out here,
@@ -612,8 +630,9 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
}
if (state == State.Running) {
- if (s_logger.isTraceEnabled())
+ if (s_logger.isTraceEnabled()) {
s_logger.trace("Console proxy is already started: " + proxy.getHostName());
+ }
return proxy;
}
@@ -632,7 +651,7 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
}
}
// to ensure atomic state transition to Starting state
- if (!_consoleProxyDao.updateIf(proxy, com.cloud.vm.VirtualMachine.Event.StartRequested, routingHost.getId())) {
+ if (!_itMgr.stateTransitTo(proxy, com.cloud.vm.VirtualMachine.Event.StartRequested, routingHost.getId())) {
if (s_logger.isDebugEnabled()) {
ConsoleProxyVO temp = _consoleProxyDao.findById(proxyId);
s_logger.debug("Unable to start console proxy " + proxy.getHostName() + " because it is not in a startable state : "
@@ -664,7 +683,7 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
String guestIpAddress = _dcDao.allocateLinkLocalIpAddress(proxy.getDataCenterId(), routingHost.getPodId(), proxy.getId(), null);
proxy.setGuestIpAddress(guestIpAddress);
- _consoleProxyDao.updateIf(proxy, VirtualMachine.Event.OperationRetry, routingHost.getId());
+ _itMgr.stateTransitTo(proxy, VirtualMachine.Event.OperationRetry, routingHost.getId());
proxy = _consoleProxyDao.findById(proxy.getId());
List vols = _storageMgr.prepare(proxy, routingHost);
@@ -692,15 +711,17 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
StartConsoleProxyCommand cmdStart = new StartConsoleProxyCommand(_networkRate, _multicastRate,
_proxyCmdPort, proxy, proxy.getHostName(), "", vols, Integer.toString(_consoleProxyPort),
Integer.toString(_consoleProxyUrlPort), _mgmt_host, _mgmt_port, _sslEnabled, guestOSDescription);
- if (s_logger.isDebugEnabled())
+ if (s_logger.isDebugEnabled()) {
s_logger.debug("Sending start command for console proxy " + proxy.getHostName() + " to " + routingHost.getName());
+ }
try {
answer = _agentMgr.send(routingHost.getId(), cmdStart);
s_logger.debug("StartConsoleProxy Answer: " + (answer != null ? answer : "null"));
- if (s_logger.isDebugEnabled())
+ if (s_logger.isDebugEnabled()) {
s_logger.debug("Received answer on starting console proxy " + proxy.getHostName() + " on " + routingHost.getName());
+ }
if (answer != null && answer.getResult()) {
if (s_logger.isDebugEnabled()) {
@@ -768,7 +789,7 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
throw new ExecutionException("Couldn't find a routingHost to run console proxy");
}
- _consoleProxyDao.updateIf(proxy, VirtualMachine.Event.OperationSucceeded, routingHost.getId());
+ _itMgr.stateTransitTo(proxy, VirtualMachine.Event.OperationSucceeded, routingHost.getId());
if (s_logger.isDebugEnabled()) {
s_logger.debug("Console proxy is now started, vm id : " + proxy.getId());
}
@@ -817,7 +838,7 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
freePrivateIpAddress(privateIpAddress, proxy.getDataCenterId(), proxy.getId());
}
- _consoleProxyDao.updateIf(proxy, VirtualMachine.Event.OperationFailed, null);
+ _itMgr.stateTransitTo(proxy, VirtualMachine.Event.OperationFailed, null);
txn.commit();
} catch (Exception e) {
s_logger.error("Caught exception during error recovery");
@@ -842,8 +863,9 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
public ConsoleProxyVO assignProxyFromRunningPool(long dataCenterId) {
- if (s_logger.isTraceEnabled())
+ if (s_logger.isTraceEnabled()) {
s_logger.trace("Assign console proxy from running pool for request from data center : " + dataCenterId);
+ }
ConsoleProxyAllocator allocator = getCurrentAllocator();
assert (allocator != null);
@@ -851,8 +873,9 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
if (runningList != null && runningList.size() > 0) {
if (s_logger.isTraceEnabled()) {
s_logger.trace("Running proxy pool size : " + runningList.size());
- for (ConsoleProxyVO proxy : runningList)
+ for (ConsoleProxyVO proxy : runningList) {
s_logger.trace("Running proxy instance : " + proxy.getHostName());
+ }
}
List> l = _consoleProxyDao.getProxyLoadMatrix();
@@ -868,34 +891,39 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
}
return allocator.allocProxy(runningList, loadInfo, dataCenterId);
} else {
- if (s_logger.isTraceEnabled())
+ if (s_logger.isTraceEnabled()) {
s_logger.trace("Empty running proxy pool for now in data center : " + dataCenterId);
+ }
}
return null;
}
public ConsoleProxyVO assignProxyFromStoppedPool(long dataCenterId) {
List l = _consoleProxyDao.getProxyListInStates(dataCenterId, State.Creating, State.Starting, State.Stopped, State.Migrating);
- if (l != null && l.size() > 0)
+ if (l != null && l.size() > 0) {
return l.get(0);
+ }
return null;
}
public ConsoleProxyVO startNewConsoleProxy(long dataCenterId) {
- if (s_logger.isDebugEnabled())
+ if (s_logger.isDebugEnabled()) {
s_logger.debug("Assign console proxy from a newly started instance for request from data center : " + dataCenterId);
+ }
Map context = _useNewNetworking ? createProxyInstance2(dataCenterId) : createProxyInstance(dataCenterId);
long proxyVmId = (Long) context.get("proxyVmId");
if (proxyVmId == 0) {
- if (s_logger.isTraceEnabled())
+ if (s_logger.isTraceEnabled()) {
s_logger.trace("Creating proxy instance failed, data center id : " + dataCenterId);
+ }
// release critical system resource on failure
- if (context.get("publicIpAddress") != null)
+ if (context.get("publicIpAddress") != null) {
freePublicIpAddress((String) context.get("publicIpAddress"), dataCenterId, 0);
+ }
return null;
}
@@ -907,8 +935,9 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
new ConsoleProxyAlertEventArgs(ConsoleProxyAlertEventArgs.PROXY_CREATED, dataCenterId, proxy.getId(), proxy, null));
return proxy;
} else {
- if (s_logger.isDebugEnabled())
+ if (s_logger.isDebugEnabled()) {
s_logger.debug("Unable to allocate console proxy storage, remove the console proxy record from DB, proxy id: " + proxyVmId);
+ }
SubscriptionMgr.getInstance().notifySubscribers(
ConsoleProxyManager.ALERT_SUBJECT,
@@ -923,19 +952,22 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
public ConsoleProxyVO startNew(long dataCenterId) {
- if (s_logger.isDebugEnabled())
+ if (s_logger.isDebugEnabled()) {
s_logger.debug("Assign console proxy from a newly started instance for request from data center : " + dataCenterId);
+ }
Map context = _useNewNetworking ? createProxyInstance2(dataCenterId) : createProxyInstance(dataCenterId);
long proxyVmId = (Long) context.get("proxyVmId");
if (proxyVmId == 0) {
- if (s_logger.isTraceEnabled())
+ if (s_logger.isTraceEnabled()) {
s_logger.trace("Creating proxy instance failed, data center id : " + dataCenterId);
+ }
// release critical system resource on failure
- if (context.get("publicIpAddress") != null)
+ if (context.get("publicIpAddress") != null) {
freePublicIpAddress((String) context.get("publicIpAddress"), dataCenterId, 0);
+ }
return null;
}
@@ -947,8 +979,9 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
new ConsoleProxyAlertEventArgs(ConsoleProxyAlertEventArgs.PROXY_CREATED, dataCenterId, proxy.getId(), proxy, null));
return proxy;
} else {
- if (s_logger.isDebugEnabled())
+ if (s_logger.isDebugEnabled()) {
s_logger.debug("Unable to allocate console proxy storage, remove the console proxy record from DB, proxy id: " + proxyVmId);
+ }
SubscriptionMgr.getInstance().notifySubscribers(
ConsoleProxyManager.ALERT_SUBJECT,
@@ -1071,9 +1104,9 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
NicProfile defaultNic = new NicProfile();
defaultNic.setDefaultNic(true);
defaultNic.setDeviceId(2);
- networks.add(new Pair(_networkMgr.setupNetworkConfiguration(systemAcct, defaultOffering.get(0), plan, null, null).get(0), defaultNic));
+ networks.add(new Pair(_networkMgr.setupNetworkConfiguration(systemAcct, defaultOffering.get(0), plan, null, null, false).get(0), defaultNic));
for (NetworkOfferingVO offering : offerings) {
- networks.add(new Pair(_networkMgr.setupNetworkConfiguration(systemAcct, offering, plan, null, null).get(0), null));
+ networks.add(new Pair(_networkMgr.setupNetworkConfiguration(systemAcct, offering, plan, null, null, false).get(0), null));
}
ConsoleProxyVO proxy = new ConsoleProxyVO(id, _serviceOffering.getId(), name, _template.getId(), _template.getGuestOSId(), dataCenterId, systemAcct.getDomainId(), systemAcct.getId(), 0);
try {
@@ -1120,7 +1153,7 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
_consoleProxyDao.update(proxy.getId(), vo);
// kick the state machine
- _consoleProxyDao.updateIf(proxy, VirtualMachine.Event.OperationSucceeded, null);
+ _itMgr.stateTransitTo(proxy, VirtualMachine.Event.OperationSucceeded, null);
txn.commit();
return proxy;
@@ -1147,8 +1180,9 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
if (ipAndVlan == null) {
s_logger.debug("Unable to get public ip address (type=Virtual) for console proxy vm for data center : " + dcId);
ipAndVlan = _vlanDao.assignPodDirectAttachIpAddress(dcId, podId, Account.ACCOUNT_ID_SYSTEM, DomainVO.ROOT_DOMAIN);
- if (ipAndVlan == null)
+ if (ipAndVlan == null) {
s_logger.debug("Unable to get public ip address (type=DirectAttach) for console proxy vm for data center : " + dcId);
+ }
}
if (ipAndVlan != null) {
VlanVO vlan = ipAndVlan.second();
@@ -1185,8 +1219,9 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
private ConsoleProxyAllocator getCurrentAllocator() {
// for now, only one adapter is supported
Enumeration it = _consoleProxyAllocators.enumeration();
- if (it.hasMoreElements())
+ if (it.hasMoreElements()) {
return it.nextElement();
+ }
return null;
}
@@ -1229,8 +1264,9 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
}
public void onLoadAnswer(ConsoleProxyLoadAnswer answer) {
- if (answer.getDetails() == null)
+ if (answer.getDetails() == null) {
return;
+ }
ConsoleProxyStatus status = null;
try {
@@ -1244,16 +1280,19 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
if (status != null) {
int count = 0;
- if (status.getConnections() != null)
+ if (status.getConnections() != null) {
count = status.getConnections().length;
+ }
byte[] details = null;
- if (answer.getDetails() != null)
+ if (answer.getDetails() != null) {
details = answer.getDetails().getBytes(Charset.forName("US-ASCII"));
+ }
_consoleProxyDao.update(answer.getProxyVmId(), count, DateUtil.currentGMTTime(), details);
} else {
- if (s_logger.isTraceEnabled())
+ if (s_logger.isTraceEnabled()) {
s_logger.trace("Unable to get console proxy load info, id : " + answer.getProxyVmId());
+ }
_consoleProxyDao.update(answer.getProxyVmId(), 0, DateUtil.currentGMTTime(), null);
// TODO : something is wrong with the VM, restart it?
@@ -1262,8 +1301,9 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
@Override
public void onLoadReport(ConsoleProxyLoadReportCommand cmd) {
- if (cmd.getLoadInfo() == null)
+ if (cmd.getLoadInfo() == null) {
return;
+ }
ConsoleProxyStatus status = null;
try {
@@ -1277,16 +1317,19 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
if (status != null) {
int count = 0;
- if (status.getConnections() != null)
+ if (status.getConnections() != null) {
count = status.getConnections().length;
+ }
byte[] details = null;
- if (cmd.getLoadInfo() != null)
+ if (cmd.getLoadInfo() != null) {
details = cmd.getLoadInfo().getBytes(Charset.forName("US-ASCII"));
+ }
_consoleProxyDao.update(cmd.getProxyVmId(), count, DateUtil.currentGMTTime(), details);
} else {
- if (s_logger.isTraceEnabled())
+ if (s_logger.isTraceEnabled()) {
s_logger.trace("Unable to get console proxy load info, id : " + cmd.getProxyVmId());
+ }
_consoleProxyDao.update(cmd.getProxyVmId(), 0, DateUtil.currentGMTTime(), null);
}
@@ -1315,8 +1358,9 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
}
if (cmd.getVmId() != null && cmd.getVmId().isEmpty()) {
- if (s_logger.isTraceEnabled())
+ if (s_logger.isTraceEnabled()) {
s_logger.trace("Invalid vm id sent from proxy(happens when proxy session has terminated)");
+ }
return new ConsoleAccessAuthenticationAnswer(cmd, false);
}
@@ -1376,8 +1420,9 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
// pinging the console proxy VM command port
//
// for now, just log a message
- if (s_logger.isInfoEnabled())
+ if (s_logger.isInfoEnabled()) {
s_logger.info("Console proxy agent is connected. proxy: " + host.getName());
+ }
/* update public/private ip address */
if (_IpAllocator != null && _IpAllocator.exteralIpAddressAllocatorEnabled()) {
@@ -1408,8 +1453,9 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
HostVO host = _hostDao.findById(agentId);
if (host.getType() == Type.ConsoleProxy) {
String name = host.getName();
- if (s_logger.isInfoEnabled())
+ if (s_logger.isInfoEnabled()) {
s_logger.info("Console proxy agent disconnected, proxy: " + name);
+ }
if (name != null && name.startsWith("v-")) {
String[] tokens = name.split("-");
long proxyVmId = 0;
@@ -1441,9 +1487,10 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
* ); stopProxy(proxy.getId()); } });
*/
} else {
- if (s_logger.isInfoEnabled())
+ if (s_logger.isInfoEnabled()) {
s_logger.info("Console proxy agent disconnected but corresponding console proxy VM no longer exists in DB, proxy: "
+ name);
+ }
}
} else {
assert (false) : "Invalid console proxy name: " + name;
@@ -1478,16 +1525,18 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
proxyLock.unlock();
}
} else {
- if (s_logger.isInfoEnabled())
+ if (s_logger.isInfoEnabled()) {
s_logger.info("Unable to acquire synchronization lock to start console proxy : " + readyProxy.getHostName());
+ }
}
} finally {
proxyLock.releaseRef();
}
}
} else {
- if (s_logger.isInfoEnabled())
+ if (s_logger.isInfoEnabled()) {
s_logger.info("Unable to acquire synchronization lock to allocate proxy storage, wait for next turn");
+ }
}
} catch (StorageUnavailableException e) {
s_logger.warn("Storage unavailable", e);
@@ -1520,8 +1569,9 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
}
private void reallyRun() {
- if (s_logger.isTraceEnabled())
+ if (s_logger.isTraceEnabled()) {
s_logger.trace("Begin console proxy capacity scan");
+ }
// config var for consoleproxy.restart check
String restart = _configDao.getValue("consoleproxy.restart");
@@ -1532,17 +1582,20 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
Map zoneHostInfoMap = getZoneHostInfo();
if (isServiceReady(zoneHostInfoMap)) {
- if (s_logger.isTraceEnabled())
+ if (s_logger.isTraceEnabled()) {
s_logger.trace("Service is ready, check to see if we need to allocate standby capacity");
+ }
if (!_capacityScanLock.lock(ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_COOPERATION)) {
- if (s_logger.isTraceEnabled())
+ if (s_logger.isTraceEnabled()) {
s_logger.trace("Capacity scan lock is used by others, skip and wait for my turn");
+ }
return;
}
- if (s_logger.isTraceEnabled())
+ if (s_logger.isTraceEnabled()) {
s_logger.trace("*** Begining capacity scan... ***");
+ }
try {
checkPendingProxyVMs();
@@ -1560,9 +1613,11 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
// indexing load info by data-center id
Map mapVmCounts = new HashMap();
- if (listVmCounts != null)
- for (ConsoleProxyLoadInfo info : listVmCounts)
+ if (listVmCounts != null) {
+ for (ConsoleProxyLoadInfo info : listVmCounts) {
mapVmCounts.put(info.getId(), info);
+ }
+ }
for (ConsoleProxyLoadInfo info : l) {
if (info.getName().equals(_instance)) {
@@ -1572,8 +1627,9 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
if (isZoneReady(zoneHostInfoMap, info.getId())) {
allocCapacity(info.getId());
} else {
- if (s_logger.isTraceEnabled())
+ if (s_logger.isTraceEnabled()) {
s_logger.trace("Zone " + info.getId() + " is not ready to alloc standy console proxy");
+ }
}
}
@@ -1591,47 +1647,54 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
if (isZoneReady(zoneHostInfoMap, info.getId())) {
allocCapacity(info.getId());
} else {
- if (s_logger.isTraceEnabled())
+ if (s_logger.isTraceEnabled()) {
s_logger.trace("Zone " + info.getId() + " is not ready to alloc standy console proxy");
+ }
}
}
}
}
- if (s_logger.isTraceEnabled())
+ if (s_logger.isTraceEnabled()) {
s_logger.trace("*** Stop capacity scan ***");
+ }
} finally {
_capacityScanLock.unlock();
}
} else {
- if (s_logger.isTraceEnabled())
+ if (s_logger.isTraceEnabled()) {
s_logger.trace("Service is not ready for capacity preallocation, wait for next time");
+ }
}
- if (s_logger.isTraceEnabled())
+ if (s_logger.isTraceEnabled()) {
s_logger.trace("End of console proxy capacity scan");
+ }
}
};
}
private boolean checkCapacity(ConsoleProxyLoadInfo proxyCountInfo, ConsoleProxyLoadInfo vmCountInfo) {
- if (proxyCountInfo.getCount() * _capacityPerProxy - vmCountInfo.getCount() <= _standbyCapacity)
+ if (proxyCountInfo.getCount() * _capacityPerProxy - vmCountInfo.getCount() <= _standbyCapacity) {
return false;
+ }
return true;
}
private void allocCapacity(long dataCenterId) {
- if (s_logger.isTraceEnabled())
+ if (s_logger.isTraceEnabled()) {
s_logger.trace("Allocate console proxy standby capacity for data center : " + dataCenterId);
+ }
boolean proxyFromStoppedPool = false;
ConsoleProxyVO proxy = assignProxyFromStoppedPool(dataCenterId);
if (proxy == null) {
- if (s_logger.isInfoEnabled())
+ if (s_logger.isInfoEnabled()) {
s_logger.info("No stopped console proxy is available, need to allocate a new console proxy");
+ }
if (_allocProxyLock.lock(ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_SYNC)) {
try {
@@ -1640,13 +1703,15 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
_allocProxyLock.unlock();
}
} else {
- if (s_logger.isInfoEnabled())
+ if (s_logger.isInfoEnabled()) {
s_logger.info("Unable to acquire synchronization lock to allocate proxy resource for standby capacity, wait for next scan");
+ }
return;
}
} else {
- if (s_logger.isInfoEnabled())
+ if (s_logger.isInfoEnabled()) {
s_logger.info("Found a stopped console proxy, bring it up to running pool. proxy vm id : " + proxy.getId());
+ }
proxyFromStoppedPool = true;
}
@@ -1661,8 +1726,9 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
proxyLock.unlock();
}
} else {
- if (s_logger.isInfoEnabled())
+ if (s_logger.isInfoEnabled()) {
s_logger.info("Unable to acquire synchronization lock to start proxy for standby capacity, proxy vm id : " + proxy.getId());
+ }
return;
}
} finally {
@@ -1670,15 +1736,18 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
}
if (proxy == null) {
- if (s_logger.isInfoEnabled())
+ if (s_logger.isInfoEnabled()) {
s_logger.info("Unable to start console proxy for standby capacity, proxy vm Id : " + proxyVmId
+ ", will recycle it and start a new one");
+ }
- if (proxyFromStoppedPool)
+ if (proxyFromStoppedPool) {
destroyProxy(proxyVmId, 0);
+ }
} else {
- if (s_logger.isInfoEnabled())
+ if (s_logger.isInfoEnabled()) {
s_logger.info("Console proxy " + proxy.getHostName() + " is started");
+ }
}
}
}
@@ -1686,8 +1755,9 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
public boolean isServiceReady(Map zoneHostInfoMap) {
for (ZoneHostInfo zoneHostInfo : zoneHostInfoMap.values()) {
if (isZoneHostReady(zoneHostInfo)) {
- if (s_logger.isInfoEnabled())
+ if (s_logger.isInfoEnabled()) {
s_logger.info("Zone " + zoneHostInfo.getDcId() + " is ready to launch");
+ }
return true;
}
}
@@ -1712,12 +1782,14 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
if (l != null && l.size() > 0 && l.get(0).second().intValue() > 0) {
return true;
} else {
- if (s_logger.isTraceEnabled())
+ if (s_logger.isTraceEnabled()) {
s_logger.trace("Primary storage is not ready, wait until it is ready to launch console proxy");
+ }
}
} else {
- if (s_logger.isTraceEnabled())
+ if (s_logger.isTraceEnabled()) {
s_logger.trace("Zone host is ready, but console proxy template is not ready");
+ }
}
}
return false;
@@ -1725,10 +1797,11 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
private boolean isZoneHostReady(ZoneHostInfo zoneHostInfo) {
int expectedFlags = 0;
- if (_use_storage_vm)
+ if (_use_storage_vm) {
expectedFlags = RunningHostInfoAgregator.ZoneHostInfo.ROUTING_HOST_MASK;
- else
+ } else {
expectedFlags = RunningHostInfoAgregator.ZoneHostInfo.ALL_HOST_MASK;
+ }
return (zoneHostInfo.getFlags() & expectedFlags) == expectedFlags;
}
@@ -1738,9 +1811,11 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
List l = _hostDao.getRunningHostCounts(new Date(cutTime.getTime() - ClusterManager.DEFAULT_HEARTBEAT_THRESHOLD));
RunningHostInfoAgregator aggregator = new RunningHostInfoAgregator();
- if (l.size() > 0)
- for (RunningHostCountInfo countInfo : l)
+ if (l.size() > 0) {
+ for (RunningHostCountInfo countInfo : l) {
aggregator.aggregate(countInfo);
+ }
+ }
return aggregator.getZoneHostInfoMap();
}
@@ -1752,16 +1827,18 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
@Override
public boolean start() {
- if (s_logger.isInfoEnabled())
+ if (s_logger.isInfoEnabled()) {
s_logger.info("Start console proxy manager");
+ }
return true;
}
@Override
public boolean stop() {
- if (s_logger.isInfoEnabled())
+ if (s_logger.isInfoEnabled()) {
s_logger.info("Stop console proxy manager");
+ }
_capacityScanScheduler.shutdownNow();
try {
@@ -1788,7 +1865,7 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
@Override
public void completeStartCommand(ConsoleProxyVO vm) {
- _consoleProxyDao.updateIf(vm, VirtualMachine.Event.AgentReportRunning, vm.getHostId());
+ _itMgr.stateTransitTo(vm, VirtualMachine.Event.AgentReportRunning, vm.getHostId());
}
@Override
@@ -1812,7 +1889,7 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
_dcDao.releaseLinkLocalIpAddress(guestIpAddress, proxy.getDataCenterId(), proxy.getId());
}
- if (!_consoleProxyDao.updateIf(proxy, ev, null)) {
+ if (!_itMgr.stateTransitTo(proxy, ev, null)) {
s_logger.debug("Unable to update the console proxy");
return;
}
@@ -1846,15 +1923,17 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
if (asyncExecutor != null) {
AsyncJobVO job = asyncExecutor.getJob();
- if (s_logger.isInfoEnabled())
+ if (s_logger.isInfoEnabled()) {
s_logger.info("Stop console proxy " + proxyVmId + ", update async job-" + job.getId());
+ }
_asyncMgr.updateAsyncJobAttachment(job.getId(), "console_proxy", proxyVmId);
}
ConsoleProxyVO proxy = _consoleProxyDao.findById(proxyVmId);
if (proxy == null) {
- if (s_logger.isDebugEnabled())
+ if (s_logger.isDebugEnabled()) {
s_logger.debug("Stopping console proxy failed: console proxy " + proxyVmId + " no longer exists");
+ }
return false;
}
/*
@@ -1865,8 +1944,9 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
try {
return stop(proxy, startEventId);
} catch (AgentUnavailableException e) {
- if (s_logger.isDebugEnabled())
+ if (s_logger.isDebugEnabled()) {
s_logger.debug("Stopping console proxy " + proxy.getHostName() + " failed : exception " + e.toString());
+ }
return false;
}
}
@@ -1877,8 +1957,9 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
if (asyncExecutor != null) {
AsyncJobVO job = asyncExecutor.getJob();
- if (s_logger.isInfoEnabled())
+ if (s_logger.isInfoEnabled()) {
s_logger.info("Reboot console proxy " + proxyVmId + ", update async job-" + job.getId());
+ }
_asyncMgr.updateAsyncJobAttachment(job.getId(), "console_proxy", proxyVmId);
}
@@ -1898,8 +1979,9 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
final Answer answer = _agentMgr.easySend(proxy.getHostId(), cmd);
if (answer != null) {
- if (s_logger.isDebugEnabled())
+ if (s_logger.isDebugEnabled()) {
s_logger.debug("Successfully reboot console proxy " + proxy.getHostName());
+ }
SubscriptionMgr.getInstance()
.notifySubscribers(
@@ -1918,8 +2000,9 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
_eventDao.persist(event);
return true;
} else {
- if (s_logger.isDebugEnabled())
+ if (s_logger.isDebugEnabled()) {
s_logger.debug("failed to reboot console proxy : " + proxy.getHostName());
+ }
final EventVO event = new EventVO();
event.setUserId(User.UID_SYSTEM);
@@ -1948,8 +2031,9 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
if (asyncExecutor != null) {
AsyncJobVO job = asyncExecutor.getJob();
- if (s_logger.isInfoEnabled())
+ if (s_logger.isInfoEnabled()) {
s_logger.info("Destroy console proxy " + vmId + ", update async job-" + job.getId());
+ }
_asyncMgr.updateAsyncJobAttachment(job.getId(), "console_proxy", vmId);
}
@@ -1969,7 +2053,7 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
s_logger.debug("Destroying console proxy vm " + vmId);
}
- if (!_consoleProxyDao.updateIf(vm, VirtualMachine.Event.DestroyRequested, null)) {
+ if (!_itMgr.stateTransitTo(vm, VirtualMachine.Event.DestroyRequested, null)) {
s_logger.debug("Unable to destroy the vm because it is not in the correct state: " + vmId);
return false;
}
@@ -1988,8 +2072,9 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
txn.start();
// release critical system resources used by the VM before we
// delete them
- if (vm.getPublicIpAddress() != null)
+ if (vm.getPublicIpAddress() != null) {
freePublicIpAddress(vm.getPublicIpAddress(), vm.getDataCenterId(), vm.getPodId());
+ }
vm.setPublicIpAddress(null);
_consoleProxyDao.remove(vm.getId());
@@ -2023,8 +2108,9 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
ConsoleProxyVO proxy = _consoleProxyDao.findById(vmId);
if (proxy != null) {
- if (proxy.getPublicIpAddress() != null)
+ if (proxy.getPublicIpAddress() != null) {
freePublicIpAddress(proxy.getPublicIpAddress(), proxy.getDataCenterId(), proxy.getPodId());
+ }
_consoleProxyDao.remove(vmId);
@@ -2050,7 +2136,7 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
@Override
public boolean stop(ConsoleProxyVO proxy, long startEventId) throws AgentUnavailableException {
- if (!_consoleProxyDao.updateIf(proxy, VirtualMachine.Event.StopRequested, proxy.getHostId())) {
+ if (!_itMgr.stateTransitTo(proxy, VirtualMachine.Event.StopRequested, proxy.getHostId())) {
s_logger.debug("Unable to stop console proxy: " + proxy.toString());
return false;
}
@@ -2129,7 +2215,7 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
public boolean migrate(ConsoleProxyVO proxy, HostVO host) {
HostVO fromHost = _hostDao.findById(proxy.getId());
- if (!_consoleProxyDao.updateIf(proxy, VirtualMachine.Event.MigrationRequested, proxy.getHostId())) {
+ if (! _itMgr.stateTransitTo(proxy, VirtualMachine.Event.MigrationRequested, proxy.getHostId())) {
s_logger.debug("State for " + proxy.toString() + " has changed so migration can not take place.");
return false;
}
@@ -2152,18 +2238,18 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
CheckVirtualMachineAnswer answer = (CheckVirtualMachineAnswer) _agentMgr.send(host.getId(), cvm);
if (!answer.getResult()) {
s_logger.debug("Unable to complete migration for " + proxy.getId());
- _consoleProxyDao.updateIf(proxy, VirtualMachine.Event.AgentReportStopped, null);
+ _itMgr.stateTransitTo(proxy, VirtualMachine.Event.AgentReportStopped, null);
return false;
}
State state = answer.getState();
if (state == State.Stopped) {
s_logger.warn("Unable to complete migration as we can not detect it on " + host.getId());
- _consoleProxyDao.updateIf(proxy, VirtualMachine.Event.AgentReportStopped, null);
+ _itMgr.stateTransitTo(proxy, VirtualMachine.Event.AgentReportStopped, null);
return false;
}
- _consoleProxyDao.updateIf(proxy, VirtualMachine.Event.OperationSucceeded, host.getId());
+ _itMgr.stateTransitTo(proxy, VirtualMachine.Event.OperationSucceeded, host.getId());
return true;
}
@@ -2245,15 +2331,17 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
event.setDescription(description);
event.setStartId(startEventId);
event = _eventDao.persist(event);
- if (event != null)
+ if (event != null) {
return event.getId();
+ }
return null;
}
@Override
public boolean configure(String name, Map params) throws ConfigurationException {
- if (s_logger.isInfoEnabled())
+ if (s_logger.isInfoEnabled()) {
s_logger.info("Start configuring console proxy manager : " + name);
+ }
_name = name;
@@ -2274,8 +2362,9 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
_proxyCmdPort = NumbersUtil.parseInt(value, DEFAULT_PROXY_CMD_PORT);
value = configs.get("consoleproxy.sslEnabled");
- if (value != null && value.equalsIgnoreCase("true"))
+ if (value != null && value.equalsIgnoreCase("true")) {
_sslEnabled = true;
+ }
value = configs.get("consoleproxy.capacityscan.interval");
_capacityScanInterval = NumbersUtil.parseLong(value, DEFAULT_CAPACITY_SCAN_INTERVAL);
@@ -2285,20 +2374,24 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
_proxySessionTimeoutValue = NumbersUtil.parseInt(configs.get("consoleproxy.session.timeout"), DEFAULT_PROXY_SESSION_TIMEOUT);
value = configs.get("consoleproxy.port");
- if (value != null)
+ if (value != null) {
_consoleProxyPort = NumbersUtil.parseInt(value, ConsoleProxyManager.DEFAULT_PROXY_VNC_PORT);
+ }
value = configs.get("consoleproxy.url.port");
- if (value != null)
+ if (value != null) {
_consoleProxyUrlPort = NumbersUtil.parseInt(value, ConsoleProxyManager.DEFAULT_PROXY_URL_PORT);
+ }
value = configs.get("system.vm.use.local.storage");
- if (value != null && value.equalsIgnoreCase("true"))
+ if (value != null && value.equalsIgnoreCase("true")) {
_use_lvm = true;
+ }
value = configs.get("secondary.storage.vm");
- if (value != null && value.equalsIgnoreCase("true"))
+ if (value != null && value.equalsIgnoreCase("true")) {
_use_storage_vm = true;
+ }
_useNewNetworking = Boolean.parseBoolean(configs.get("use.new.networking"));
@@ -2357,7 +2450,7 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
String multicastRateStr = _configDao.getValue("multicast.throttling.rate");
_networkRate = ((networkRateStr == null) ? 200 : Integer.parseInt(networkRateStr));
_multicastRate = ((multicastRateStr == null) ? 10 : Integer.parseInt(multicastRateStr));
- _serviceOffering = new ServiceOfferingVO("System Offering For Console Proxy", 1, _proxyRamSize, 0, 0, 0, false, null, NetworkOffering.GuestIpType.Virtualized,
+ _serviceOffering = new ServiceOfferingVO("System Offering For Console Proxy", 1, _proxyRamSize, 256, 0, 0, false, null, NetworkOffering.GuestIpType.Virtual,
useLocalStorage, true, null, true);
_serviceOffering.setUniqueName("Cloud.com-ConsoleProxy");
_serviceOffering = _offeringDao.persistSystemServiceOffering(_serviceOffering);
@@ -2368,8 +2461,9 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
_capacityScanScheduler.scheduleAtFixedRate(getCapacityScanTask(), STARTUP_DELAY, _capacityScanInterval, TimeUnit.MILLISECONDS);
- if (s_logger.isInfoEnabled())
+ if (s_logger.isInfoEnabled()) {
s_logger.info("Console Proxy Manager is configured.");
+ }
return true;
}
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/dc/dao/VlanDaoImpl.java b/server/src/com/cloud/dc/dao/VlanDaoImpl.java
index d3ff641396a..14d1419a06c 100644
--- a/server/src/com/cloud/dc/dao/VlanDaoImpl.java
+++ b/server/src/com/cloud/dc/dao/VlanDaoImpl.java
@@ -240,7 +240,7 @@ public class VlanDaoImpl extends GenericDaoBase implements VlanDao
if (vlan == null) {
return null;
}
- String ipAddress = _ipAddressDao.assignIpAddress(accountId, domainId, vlan.getId(), sourceNat);
+ String ipAddress = _ipAddressDao.assignIpAddress(accountId, domainId, vlan.getId(), sourceNat).getAddress();
if (ipAddress == null) {
return null;
}
@@ -270,7 +270,7 @@ public class VlanDaoImpl extends GenericDaoBase implements VlanDao
return null;
}
- String ipAddress = _ipAddressDao.assignIpAddress(accountId, domainId, vlan.getId(), false);
+ String ipAddress = _ipAddressDao.assignIpAddress(accountId, domainId, vlan.getId(), false).getAddress();
if (ipAddress == null) {
return null;
}
diff --git a/server/src/com/cloud/deploy/FirstFitPlanner.java b/server/src/com/cloud/deploy/FirstFitPlanner.java
new file mode 100644
index 00000000000..93f7d2a09ca
--- /dev/null
+++ b/server/src/com/cloud/deploy/FirstFitPlanner.java
@@ -0,0 +1,329 @@
+package com.cloud.deploy;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.ejb.Local;
+
+import org.apache.log4j.Logger;
+
+import com.cloud.capacity.CapacityVO;
+import com.cloud.capacity.dao.CapacityDao;
+import com.cloud.dc.ClusterVO;
+import com.cloud.dc.DataCenter;
+import com.cloud.dc.HostPodVO;
+import com.cloud.dc.Pod;
+import com.cloud.dc.dao.ClusterDao;
+import com.cloud.dc.dao.DataCenterDao;
+import com.cloud.dc.dao.HostPodDao;
+import com.cloud.exception.InsufficientServerCapacityException;
+import com.cloud.host.DetailVO;
+import com.cloud.host.Host;
+import com.cloud.host.HostVO;
+import com.cloud.host.Status;
+import com.cloud.host.dao.DetailsDao;
+import com.cloud.host.dao.HostDao;
+import com.cloud.offering.ServiceOffering;
+import com.cloud.org.Cluster;
+import com.cloud.storage.GuestOSCategoryVO;
+import com.cloud.storage.GuestOSVO;
+import com.cloud.storage.dao.GuestOSCategoryDao;
+import com.cloud.storage.dao.GuestOSDao;
+import com.cloud.template.VirtualMachineTemplate;
+import com.cloud.utils.component.Inject;
+import com.cloud.utils.db.DB;
+import com.cloud.utils.db.Transaction;
+import com.cloud.vm.VirtualMachine;
+import com.cloud.vm.VirtualMachineProfile;
+
+@Local(value=DeploymentPlanner.class)
+public class FirstFitPlanner extends PlannerBase implements DeploymentPlanner {
+ private static final Logger s_logger = Logger.getLogger(FirstFitPlanner.class);
+ @Inject private HostDao _hostDao;
+ @Inject private CapacityDao _capacityDao;
+ @Inject private DataCenterDao _dcDao;
+ @Inject private HostPodDao _podDao;
+ @Inject private ClusterDao _clusterDao;
+ @Inject DetailsDao _hostDetailsDao = null;
+ @Inject GuestOSDao _guestOSDao = null;
+ @Inject GuestOSCategoryDao _guestOSCategoryDao = null;
+
+ @Override
+ public DeployDestination plan(VirtualMachineProfile vmProfile,
+ DeploymentPlan plan, ExcludeList avoid)
+ throws InsufficientServerCapacityException {
+ VirtualMachine vm = vmProfile.getVirtualMachine();
+ ServiceOffering offering = vmProfile.getServiceOffering();
+ DataCenter dc = _dcDao.findById(vm.getDataCenterId());
+ int cpu_requested = offering.getCpu() * offering.getSpeed();
+ long ram_requested = offering.getRamSize() * 1024L * 1024L;
+
+ s_logger.debug("try to allocate a host from dc:" + plan.getDataCenterId() + ", pod:" + plan.getPodId() + ",cluster:" + plan.getClusterId() +
+ ", requested cpu: " + cpu_requested + ", requested ram: " + ram_requested);
+ if (vm.getLastHostId() != null) {
+ HostVO host = _hostDao.findById(vm.getLastHostId());
+
+ if (host != null && host.getStatus() == Status.Up) {
+ boolean canDepployToLastHost = deployToHost(host, cpu_requested, ram_requested, true, avoid);
+ if (canDepployToLastHost) {
+ Pod pod = _podDao.findById(vm.getPodId());
+ Cluster cluster = _clusterDao.findById(host.getClusterId());
+ return new DeployDestination(dc, pod, cluster, host);
+ }
+ }
+ }
+
+ /*Go through all the pods/clusters under zone*/
+ List pods = null;
+ if (plan.getPodId() != null) {
+ HostPodVO pod = _podDao.findById(plan.getPodId());
+ if (pod != null && dc.getId() == pod.getDataCenterId()) {
+ pods = new ArrayList(1);
+ pods.add(pod);
+ } else {
+ s_logger.debug("Can't enforce the pod selector");
+ return null;
+ }
+ }
+
+ if (pods == null)
+ pods = _podDao.listByDataCenterId(plan.getDataCenterId());
+
+ //Collections.shuffle(pods);
+
+ for (HostPodVO hostPod : pods) {
+ if (avoid.shouldAvoid(hostPod)) {
+ continue;
+ }
+
+ //Collections.shuffle(clusters);
+ List clusters = null;
+ if (plan.getClusterId() != null) {
+ ClusterVO cluster = _clusterDao.findById(plan.getClusterId());
+ if (cluster != null && hostPod.getId() == cluster.getPodId()) {
+ clusters = new ArrayList(1);
+ clusters.add(cluster);
+ } else {
+ s_logger.debug("Can't enforce the cluster selector");
+ return null;
+ }
+ }
+
+ if (clusters == null) {
+ clusters = _clusterDao.listByPodId(hostPod.getId());
+ }
+
+ for (ClusterVO clusterVO : clusters) {
+ if (avoid.shouldAvoid(clusterVO)) {
+ continue;
+ }
+
+ if (clusterVO.getHypervisorType() != vmProfile.getHypervisorType()) {
+ avoid.addCluster(clusterVO.getId());
+ continue;
+ }
+
+ List hosts = _hostDao.listBy(Host.Type.Routing, clusterVO.getId(), hostPod.getId(), dc.getId());
+ //Collections.shuffle(hosts);
+
+ // We will try to reorder the host lists such that we give priority to hosts that have
+ // the minimums to support a VM's requirements
+ hosts = prioritizeHosts(vmProfile.getTemplate(), hosts);
+
+ for (HostVO hostVO : hosts) {
+ boolean canDeployToHost = deployToHost(hostVO, cpu_requested, ram_requested, false, avoid);
+ if (canDeployToHost) {
+ Pod pod = _podDao.findById(hostPod.getId());
+ Cluster cluster = _clusterDao.findById(clusterVO.getId());
+ Host host = _hostDao.findById(hostVO.getId());
+ return new DeployDestination(dc, pod, cluster, host);
+ }
+ avoid.addHost(hostVO.getId());
+ }
+ avoid.addCluster(clusterVO.getId());
+ }
+ avoid.addPod(hostPod.getId());
+ }
+
+ return null;
+ }
+
+
+ @Override
+ public boolean check(VirtualMachineProfile vm, DeploymentPlan plan,
+ DeployDestination dest, ExcludeList exclude) {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ @DB
+ protected boolean deployToHost(HostVO host, Integer cpu, long ram, boolean fromLastHost, ExcludeList avoid) {
+ if (avoid.shouldAvoid(host)) {
+ return false;
+ }
+
+ CapacityVO capacityCpu = _capacityDao.findByHostIdType(host.getId(), CapacityVO.CAPACITY_TYPE_CPU);
+ CapacityVO capacityMem = _capacityDao.findByHostIdType(host.getId(), CapacityVO.CAPACITY_TYPE_MEMORY);
+
+ capacityCpu = _capacityDao.lockRow(capacityCpu.getId(), true);
+ capacityMem = _capacityDao.lockRow(capacityMem.getId(), true);
+
+ Transaction txn = Transaction.currentTxn();
+
+ try {
+ txn.start();
+
+ long usedCpu = capacityCpu.getUsedCapacity();
+ long usedMem = capacityMem.getUsedCapacity();
+ long reservedCpu = capacityCpu.getReservedCapacity();
+ long reservedMem = capacityMem.getReservedCapacity();
+ long totalCpu = capacityCpu.getTotalCapacity();
+ long totalMem = capacityMem.getTotalCapacity();
+
+ boolean success = false;
+ if (fromLastHost) {
+ /*alloc from reserved*/
+ if (reservedCpu >= cpu && reservedMem >= ram) {
+ capacityCpu.setReservedCapacity(reservedCpu - cpu);
+ capacityMem.setReservedCapacity(reservedMem - ram);
+ capacityCpu.setUsedCapacity(usedCpu + cpu);
+ capacityMem.setUsedCapacity(usedMem + ram);
+ success = true;
+ }
+ } else {
+ /*alloc from free resource*/
+ if ((reservedCpu + usedCpu + cpu <= totalCpu) && (reservedMem + usedMem + ram <= totalMem)) {
+ capacityCpu.setUsedCapacity(usedCpu + cpu);
+ capacityMem.setUsedCapacity(usedMem + ram);
+ success = true;
+ }
+ }
+
+ if (success) {
+ s_logger.debug("alloc cpu from host: " + host.getId() + ", old used: " + usedCpu + ", old reserved: " +
+ reservedCpu + ", old total: " + totalCpu +
+ "; new used:" + capacityCpu.getUsedCapacity() + ", reserved:" + capacityCpu.getReservedCapacity() + ", total: " + capacityCpu.getTotalCapacity() +
+ "; requested cpu:" + cpu + ",alloc_from_last:" + fromLastHost);
+
+ s_logger.debug("alloc mem from host: " + host.getId() + ", old used: " + usedMem + ", old reserved: " +
+ reservedMem + ", old total: " + totalMem + "; new used: " + capacityMem.getUsedCapacity() + ", reserved: " +
+ capacityMem.getReservedCapacity() + ", total: " + capacityMem.getTotalCapacity() + "; requested mem: " + ram + ",alloc_from_last:" + fromLastHost);
+
+ _capacityDao.update(capacityCpu.getId(), capacityCpu);
+ _capacityDao.update(capacityMem.getId(), capacityMem);
+ }
+
+ txn.commit();
+ return success;
+ } catch (Exception e) {
+ txn.rollback();
+ return false;
+ }
+ }
+
+ protected List prioritizeHosts(VirtualMachineTemplate template, List hosts) {
+ if (template == null) {
+ return hosts;
+ }
+
+ // Determine the guest OS category of the template
+ String templateGuestOSCategory = getTemplateGuestOSCategory(template);
+
+ List prioritizedHosts = new ArrayList();
+
+ // If a template requires HVM and a host doesn't support HVM, remove it from consideration
+ List hostsToCheck = new ArrayList();
+ if (template.isRequiresHvm()) {
+ for (HostVO host : hosts) {
+ if (hostSupportsHVM(host)) {
+ hostsToCheck.add(host);
+ }
+ }
+ } else {
+ hostsToCheck.addAll(hosts);
+ }
+
+ // If a host is tagged with the same guest OS category as the template, move it to a high priority list
+ // If a host is tagged with a different guest OS category than the template, move it to a low priority list
+ List highPriorityHosts = new ArrayList();
+ List lowPriorityHosts = new ArrayList();
+ for (HostVO host : hostsToCheck) {
+ String hostGuestOSCategory = getHostGuestOSCategory(host);
+ if (hostGuestOSCategory == null) {
+ continue;
+ } else if (templateGuestOSCategory.equals(hostGuestOSCategory)) {
+ highPriorityHosts.add(host);
+ } else {
+ lowPriorityHosts.add(host);
+ }
+ }
+
+ hostsToCheck.removeAll(highPriorityHosts);
+ hostsToCheck.removeAll(lowPriorityHosts);
+
+ // Prioritize the remaining hosts by HVM capability
+ for (HostVO host : hostsToCheck) {
+ if (!template.isRequiresHvm() && !hostSupportsHVM(host)) {
+ // Host and template both do not support hvm, put it as first consideration
+ prioritizedHosts.add(0, host);
+ } else {
+ // Template doesn't require hvm, but the machine supports it, make it last for consideration
+ prioritizedHosts.add(host);
+ }
+ }
+
+ // Merge the lists
+ prioritizedHosts.addAll(0, highPriorityHosts);
+ prioritizedHosts.addAll(lowPriorityHosts);
+
+ return prioritizedHosts;
+ }
+
+ protected boolean hostSupportsHVM(HostVO host) {
+ // Determine host capabilities
+ String caps = host.getCapabilities();
+
+ if (caps != null) {
+ String[] tokens = caps.split(",");
+ for (String token : tokens) {
+ if (token.contains("hvm")) {
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+
+ protected String getHostGuestOSCategory(HostVO host) {
+ DetailVO hostDetail = _hostDetailsDao.findDetail(host.getId(), "guest.os.category.id");
+ if (hostDetail != null) {
+ String guestOSCategoryIdString = hostDetail.getValue();
+ long guestOSCategoryId;
+
+ try {
+ guestOSCategoryId = Long.parseLong(guestOSCategoryIdString);
+ } catch (Exception e) {
+ return null;
+ }
+
+ GuestOSCategoryVO guestOSCategory = _guestOSCategoryDao.findById(guestOSCategoryId);
+
+ if (guestOSCategory != null) {
+ return guestOSCategory.getName();
+ } else {
+ return null;
+ }
+ } else {
+ return null;
+ }
+ }
+
+ protected String getTemplateGuestOSCategory(VirtualMachineTemplate template) {
+ long guestOSId = template.getGuestOSId();
+ GuestOSVO guestOS = _guestOSDao.findById(guestOSId);
+ long guestOSCategoryId = guestOS.getCategoryId();
+ GuestOSCategoryVO guestOSCategory = _guestOSCategoryDao.findById(guestOSCategoryId);
+ return guestOSCategory.getName();
+ }
+}
diff --git a/server/src/com/cloud/domain/dao/DomainDao.java b/server/src/com/cloud/domain/dao/DomainDao.java
index 37678ff2ec4..d94260fc7df 100644
--- a/server/src/com/cloud/domain/dao/DomainDao.java
+++ b/server/src/com/cloud/domain/dao/DomainDao.java
@@ -24,7 +24,7 @@ import com.cloud.domain.DomainVO;
import com.cloud.utils.db.GenericDao;
public interface DomainDao extends GenericDao {
- public void update(Long id, String domainName);
+ public void update(Long id, String domainName, String domainPath);
public DomainVO create(DomainVO domain);
public DomainVO findDomainByPath(String domainPath);
public boolean isChildDomain(Long parentId, Long childId);
diff --git a/server/src/com/cloud/domain/dao/DomainDaoImpl.java b/server/src/com/cloud/domain/dao/DomainDaoImpl.java
index 901ed42f1e1..d15e7e97881 100644
--- a/server/src/com/cloud/domain/dao/DomainDaoImpl.java
+++ b/server/src/com/cloud/domain/dao/DomainDaoImpl.java
@@ -68,9 +68,10 @@ public class DomainDaoImpl extends GenericDaoBase implements Dom
FindAllChildrenSearch.done();
}
- public void update(Long id, String domainName) {
+ public void update(Long id, String domainName, String domainPath) {
DomainVO ub = createForUpdate();
- ub.setName(domainName);
+ ub.setName(domainName);
+ ub.setPath(domainPath);
update(id, ub);
}
diff --git a/server/src/com/cloud/ha/HighAvailabilityManagerImpl.java b/server/src/com/cloud/ha/HighAvailabilityManagerImpl.java
index 0dbe82c07e6..1037199a44b 100644
--- a/server/src/com/cloud/ha/HighAvailabilityManagerImpl.java
+++ b/server/src/com/cloud/ha/HighAvailabilityManagerImpl.java
@@ -71,6 +71,7 @@ import com.cloud.vm.VMInstanceVO;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachine.Event;
import com.cloud.vm.VirtualMachineManager;
+import com.cloud.vm.VmManager;
import com.cloud.vm.dao.VMInstanceDao;
/**
@@ -130,6 +131,7 @@ public class HighAvailabilityManagerImpl implements HighAvailabilityManager {
@Inject StorageManager _storageMgr;
@Inject GuestOSDao _guestOSDao;
@Inject GuestOSCategoryDao _guestOSCategoryDao;
+ @Inject VmManager _itMgr;
String _instance;
ScheduledExecutorService _executor;
@@ -357,8 +359,8 @@ public class HighAvailabilityManagerImpl implements HighAvailabilityManager {
if (work.getStep() == Step.Investigating) {
if (vm.getHostId() == null || vm.getHostId() != work.getHostId()) {
s_logger.info("VM " + vm.toString() + " is now no longer on host " + work.getHostId());
- if (vm.getState() == State.Starting && vm.getUpdated() == work.getUpdateTime()) {
- _instanceDao.updateIf(vm, Event.AgentReportStopped, null);
+ if (vm.getState() == State.Starting && vm.getUpdated() == work.getUpdateTime()) {
+ _itMgr.stateTransitTo(vm, Event.AgentReportStopped, null);
}
return null;
}
@@ -518,7 +520,7 @@ public class HighAvailabilityManagerImpl implements HighAvailabilityManager {
s_logger.debug("Both states are " + agentState.toString() + " for " + serverName);
}
assert (agentState == State.Stopped || agentState == State.Running) : "If the states we send up is changed, this must be changed.";
- _instanceDao.updateIf(vm, agentState == State.Stopped ? VirtualMachine.Event.AgentReportStopped : VirtualMachine.Event.AgentReportRunning, vm.getHostId());
+ _itMgr.stateTransitTo(vm, agentState == State.Stopped ? VirtualMachine.Event.AgentReportStopped : VirtualMachine.Event.AgentReportRunning, vm.getHostId());
if (agentState == State.Stopped) {
s_logger.debug("State matches but the agent said stopped so let's send a cleanup anyways.");
return info.mgr.cleanup(vm, agentName);
@@ -548,8 +550,8 @@ public class HighAvailabilityManagerImpl implements HighAvailabilityManager {
} else if (serverState == State.Starting) {
s_logger.debug("Ignoring VM in starting mode: " + vm.getHostName());
} else {
- s_logger.debug("Sending cleanup to a stopped vm: " + agentName);
- _instanceDao.updateIf(vm, VirtualMachine.Event.AgentReportStopped, null);
+ s_logger.debug("Sending cleanup to a stopped vm: " + agentName);
+ _itMgr.stateTransitTo(vm, VirtualMachine.Event.AgentReportStopped, null);
command = info.mgr.cleanup(vm, agentName);
}
} else if (agentState == State.Running) {
@@ -573,7 +575,7 @@ public class HighAvailabilityManagerImpl implements HighAvailabilityManager {
vm = info.mgr.get(vm.getId());
command = info.mgr.cleanup(vm, agentName);
} else {
- _instanceDao.updateIf(vm, VirtualMachine.Event.AgentReportRunning, vm.getHostId());
+ _itMgr.stateTransitTo(vm, VirtualMachine.Event.AgentReportRunning, vm.getHostId());
}
} /*else if (agentState == State.Unknown) {
if (serverState == State.Running) {
@@ -745,7 +747,7 @@ public class HighAvailabilityManagerImpl implements HighAvailabilityManager {
if (work.getStep() == Step.Migrating) {
vm = mgr.get(vmId); // let's see if anything has changed.
boolean migrated = false;
- if (vm == null || vm.getRemoved() != null || vm.getHostId() == null || !_instanceDao.updateIf(vm, Event.MigrationRequested, vm.getHostId())) {
+ if (vm == null || vm.getRemoved() != null || vm.getHostId() == null || !_itMgr.stateTransitTo(vm, Event.MigrationRequested, vm.getHostId())) {
s_logger.info("Migration cancelled because state has changed: " + vm.toString());
} else {
try {
@@ -775,7 +777,7 @@ public class HighAvailabilityManagerImpl implements HighAvailabilityManager {
HostPodVO podVO = _podDao.findById(vm.getPodId());
_alertMgr.sendAlert(alertType, fromHost.getDataCenterId(), fromHost.getPodId(), "Unable to migrate vm " + vm.getHostName() + " from host " + fromHost.getName() + " in zone " + dcVO.getName() + " and pod " + podVO.getName(), "Migrate Command failed. Please check logs.");
- _instanceDao.updateIf(vm, Event.OperationFailed, vm.getHostId());
+ _itMgr.stateTransitTo(vm, Event.MigrationFailedOnSource, toHost.getId());
_agentMgr.maintenanceFailed(vm.getHostId());
Command cleanup = mgr.cleanup(vm, null);
@@ -805,7 +807,7 @@ public class HighAvailabilityManagerImpl implements HighAvailabilityManager {
} catch (final OperationTimedoutException e) {
s_logger.warn("Operation timed outfor " + vm.toString());
}
- _instanceDao.updateIf(vm, Event.OperationFailed, toHost.getId());
+ _itMgr.stateTransitTo(vm, Event.MigrationFailedOnDest, toHost.getId());
return (System.currentTimeMillis() >> 10) + _migrateRetryInterval;
}
diff --git a/server/src/com/cloud/hypervisor/kvm/discoverer/KvmServerDiscoverer.java b/server/src/com/cloud/hypervisor/kvm/discoverer/KvmServerDiscoverer.java
index 3500cfb21be..6dc31a64f0f 100644
--- a/server/src/com/cloud/hypervisor/kvm/discoverer/KvmServerDiscoverer.java
+++ b/server/src/com/cloud/hypervisor/kvm/discoverer/KvmServerDiscoverer.java
@@ -20,6 +20,7 @@ import com.cloud.agent.api.AgentControlCommand;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.Command;
import com.cloud.agent.api.StartupCommand;
+import com.cloud.configuration.Config;
import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.dc.ClusterVO;
import com.cloud.dc.dao.ClusterDao;
@@ -48,6 +49,8 @@ public class KvmServerDiscoverer extends DiscovererBase implements Discoverer,
private ConfigurationDao _configDao;
private String _hostIp;
private int _waitTime = 5; /*wait for 5 minutes*/
+ private String _kvmPrivateNic;
+ private String _kvmPublicNic;
@Inject HostDao _hostDao = null;
@Inject ClusterDao _clusterDao;
@@ -218,8 +221,18 @@ public class KvmServerDiscoverer extends DiscovererBase implements Discoverer,
s_logger.debug("copying " + _setupAgentPath + " to host");
SCPClient scp = new SCPClient(sshConnection);
scp.put(_setupAgentPath, "/usr/bin", "0755");
+
+ String parameters = " -h " + _hostIp + " -z " + dcId + " -p " + podId + " -c " + clusterId + " -u " + guid;
+
+ if (_kvmPublicNic != null) {
+ parameters += " -P " + _kvmPublicNic;
+ }
+
+ if (_kvmPrivateNic != null) {
+ parameters += " -N " + _kvmPrivateNic;
+ }
- sshExecuteCmd(sshConnection, "/usr/bin/setup_agent.sh " + " -h " + _hostIp + " -z " + dcId + " -p " + podId + " -c " + clusterId + " -u " + guid + " 1>&2", 3);
+ sshExecuteCmd(sshConnection, "/usr/bin/setup_agent.sh " + parameters + " 1>&2", 3);
KvmDummyResourceBase kvmResource = new KvmDummyResourceBase();
Map params = new HashMap();
@@ -276,6 +289,8 @@ public class KvmServerDiscoverer extends DiscovererBase implements Discoverer,
ComponentLocator locator = ComponentLocator.getCurrentLocator();
_configDao = locator.getDao(ConfigurationDao.class);
_setupAgentPath = Script.findScript(getPatchPath(), "setup_agent.sh");
+ _kvmPrivateNic = _configDao.getValue(Config.KvmPrivateNetwork.key());
+ _kvmPublicNic = _configDao.getValue(Config.KvmPublicNetwork.key());
if (_setupAgentPath == null) {
throw new ConfigurationException("Can't find setup_agent.sh");
diff --git a/server/src/com/cloud/migration/Db20to21MigrationUtil.java b/server/src/com/cloud/migration/Db20to21MigrationUtil.java
index 000f66e6f6c..6168fe6f6c6 100644
--- a/server/src/com/cloud/migration/Db20to21MigrationUtil.java
+++ b/server/src/com/cloud/migration/Db20to21MigrationUtil.java
@@ -305,7 +305,7 @@ public class Db20to21MigrationUtil {
_configDao.getValue(Config.ConsoleProxyRamSize.key()),
ConsoleProxyManager.DEFAULT_PROXY_VM_RAMSIZE);
ServiceOffering21VO soConsoleProxy = new ServiceOffering21VO("Fake Offering For DomP", 1,
- proxyRamSize, 0, 0, 0, false, null, NetworkOffering.GuestIpType.Virtualized,
+ proxyRamSize, 0, 0, 0, false, null, NetworkOffering.GuestIpType.Virtual,
useLocalStorage, true, null);
soConsoleProxy.setId(seq++);
soConsoleProxy.setUniqueName("Cloud.com-ConsoleProxy");
@@ -316,7 +316,7 @@ public class Db20to21MigrationUtil {
_configDao.getValue(Config.SecStorageVmRamSize.key()),
SecondaryStorageVmManager.DEFAULT_SS_VM_RAMSIZE);
ServiceOffering21VO soSecondaryVm = new ServiceOffering21VO("Fake Offering For Secondary Storage VM", 1,
- secStorageVmRamSize, 0, 0, 0, false, null, NetworkOffering.GuestIpType.Virtualized, useLocalStorage, true, null);
+ secStorageVmRamSize, 0, 0, 0, false, null, NetworkOffering.GuestIpType.Virtual, useLocalStorage, true, null);
soSecondaryVm.setId(seq++);
soSecondaryVm.setUniqueName("Cloud.com-SecondaryStorage");
soSecondaryVm = _serviceOffering21Dao.persist(soSecondaryVm);
@@ -324,7 +324,7 @@ public class Db20to21MigrationUtil {
int routerRamSize = NumbersUtil.parseInt(_configDao.getValue("router.ram.size"), 128);
ServiceOffering21VO soDomainRouter = new ServiceOffering21VO("Fake Offering For DomR", 1,
- routerRamSize, 0, 0, 0, false, null, NetworkOffering.GuestIpType.Virtualized, useLocalStorage, true, null);
+ routerRamSize, 0, 0, 0, false, null, NetworkOffering.GuestIpType.Virtual, useLocalStorage, true, null);
soDomainRouter.setId(seq++);
soDomainRouter.setUniqueName("Cloud.Com-SoftwareRouter");
soDomainRouter = _serviceOffering21Dao.persist(soDomainRouter);
diff --git a/server/src/com/cloud/migration/ServiceOffering20VO.java b/server/src/com/cloud/migration/ServiceOffering20VO.java
index acb355376f1..7d31fbb7ede 100644
--- a/server/src/com/cloud/migration/ServiceOffering20VO.java
+++ b/server/src/com/cloud/migration/ServiceOffering20VO.java
@@ -52,7 +52,7 @@ public class ServiceOffering20VO {
@Column(name="guest_ip_type")
@Enumerated(EnumType.STRING)
- private NetworkOffering.GuestIpType guestIpType = NetworkOffering.GuestIpType.Virtualized;
+ private NetworkOffering.GuestIpType guestIpType = NetworkOffering.GuestIpType.Virtual;
@Column(name="use_local_storage")
private boolean useLocalStorage;
@@ -67,7 +67,7 @@ public class ServiceOffering20VO {
}
public ServiceOffering20VO(Long id, String name, int cpu, int ramSize, int speed, int rateMbps, int multicastRateMbps, boolean offerHA, String displayText, boolean localStorageRequired) {
- this(id, name, cpu, ramSize, speed, rateMbps, multicastRateMbps, offerHA, displayText, NetworkOffering.GuestIpType.Virtualized, localStorageRequired);
+ this(id, name, cpu, ramSize, speed, rateMbps, multicastRateMbps, offerHA, displayText, NetworkOffering.GuestIpType.Virtual, localStorageRequired);
}
public ServiceOffering20VO(Long id, String name, int cpu, int ramSize, int speed, int rateMbps, int multicastRateMbps, boolean offerHA, String displayText, NetworkOffering.GuestIpType guestIpType, boolean useLocalStorage) {
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..0ea5fa11d59 100644
--- a/server/src/com/cloud/network/IPAddressVO.java
+++ b/server/src/com/cloud/network/IPAddressVO.java
@@ -29,18 +29,16 @@ import javax.persistence.TemporalType;
/**
* A bean representing a public IP Address
- *
- * @author Will Chan
*
*/
@Entity
@Table(name=("user_ip_address"))
public class IPAddressVO implements IpAddress {
@Column(name="account_id")
- private Long accountId = null;
+ private Long allocatedToAccountId = null;
@Column(name="domain_id")
- private Long domainId = null;
+ private Long allocatedInDomainId = null;
@Id
@Column(name="public_ip_address")
@@ -54,22 +52,34 @@ public class IPAddressVO implements IpAddress {
@Column(name="allocated")
@Temporal(value=TemporalType.TIMESTAMP)
- private Date allocated;
+ private Date allocatedTime;
@Column(name="vlan_db_id")
- private long vlanDbId;
+ private long vlanId;
@Column(name="one_to_one_nat")
private boolean oneToOneNat;
+
+ @Column(name="state")
+ private State state;
protected IPAddressVO() {
+ }
+
+ @Override
+ public boolean readyToUse() {
+ return state == State.Allocated;
}
public IPAddressVO(String address, long dataCenterId, long vlanDbId, boolean sourceNat) {
this.address = address;
this.dataCenterId = dataCenterId;
- this.vlanDbId = vlanDbId;
- this.sourceNat = sourceNat;
+ this.vlanId = vlanDbId;
+ this.sourceNat = sourceNat;
+ this.allocatedInDomainId = null;
+ this.allocatedToAccountId = null;
+ this.allocatedTime = null;
+ this.state = State.Free;
}
@Override
@@ -80,57 +90,51 @@ public class IPAddressVO implements IpAddress {
@Override
public String getAddress() {
return address;
- }
+ }
+
@Override
- public Long getAccountId() {
- return accountId;
- }
+ public Long getAllocatedToAccountId() {
+ return allocatedToAccountId;
+ }
+
@Override
- public Long getDomainId() {
- return domainId;
- }
+ public Long getAllocatedInDomainId() {
+ return allocatedInDomainId;
+ }
+
@Override
- public Date getAllocated() {
- return allocated;
- }
- @Override
- public boolean isSourceNat() {
- return sourceNat;
+ public Date getAllocatedTime() {
+ return allocatedTime;
}
- @Override
- public void setAccountId(Long accountId) {
- this.accountId = accountId;
+ public void setAllocatedToAccountId(Long accountId) {
+ this.allocatedToAccountId = accountId;
}
- @Override
- public void setDomainId(Long domainId) {
- this.domainId = domainId;
+ public void setAllocatedInDomainId(Long domainId) {
+ this.allocatedInDomainId = domainId;
}
- @Override
public void setSourceNat(boolean sourceNat) {
this.sourceNat = sourceNat;
}
@Override
- public boolean getSourceNat() {
- return this.sourceNat;
+ public boolean isSourceNat() {
+ return sourceNat;
}
- @Override
- public void setAllocated(Date allocated) {
- this.allocated = allocated;
+ public void setAllocatedTime(Date allocated) {
+ this.allocatedTime = allocated;
}
@Override
- public long getVlanDbId() {
- return this.vlanDbId;
+ public long getVlanId() {
+ return this.vlanId;
}
- @Override
- public void setVlanDbId(long vlanDbId) {
- this.vlanDbId = vlanDbId;
+ public void setVlanId(long vlanDbId) {
+ this.vlanId = vlanDbId;
}
@Override
@@ -138,9 +142,31 @@ public class IPAddressVO implements IpAddress {
return oneToOneNat;
}
- @Override
public void setOneToOneNat(boolean oneToOneNat) {
this.oneToOneNat = oneToOneNat;
+ }
+
+ @Override
+ public long getDomainId() {
+ return allocatedInDomainId == null ? -1 : allocatedInDomainId;
+ }
+
+ @Override
+ public long getAccountId() {
+ return allocatedToAccountId == null ? -1 : allocatedToAccountId;
+ }
+
+ @Override
+ public State getState() {
+ return state;
+ }
+
+ public void setState(State state) {
+ this.state = state;
+ }
+
+ @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..a0c6e0be4cb 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.DiscriminatorValue;
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;
-
+@DiscriminatorValue(value="LoadBalancing")
+@PrimaryKeyJoinColumn(name="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..cc1bceb376c 100644
--- a/server/src/com/cloud/network/NetworkManager.java
+++ b/server/src/com/cloud/network/NetworkManager.java
@@ -18,12 +18,9 @@
package com.cloud.network;
import java.util.List;
-import java.util.Map;
import com.cloud.dc.DataCenter;
import com.cloud.dc.DataCenterVO;
-import com.cloud.dc.HostPodVO;
-import com.cloud.dc.VlanVO;
import com.cloud.deploy.DeployDestination;
import com.cloud.deploy.DeploymentPlan;
import com.cloud.exception.ConcurrentOperationException;
@@ -33,17 +30,17 @@ import com.cloud.exception.InsufficientNetworkCapacityException;
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;
import com.cloud.vm.ReservationContext;
-import com.cloud.vm.UserVmVO;
import com.cloud.vm.VMInstanceVO;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachineProfile;
@@ -55,70 +52,6 @@ import com.cloud.vm.VirtualMachineProfile;
public interface NetworkManager extends NetworkService {
public static final int DEFAULT_ROUTER_VM_RAMSIZE = 128; // 128M
public static final boolean USE_POD_VLAN = false;
- /**
- * create the router.
- *
- * @param accountId account Id the router belongs to.
- * @param ipAddress public ip address the router should use to access the internet.
- * @param dcId data center id the router should live in.
- * @param domain domain name of this network.
- * @param offering service offering associated with this request
- * @return DomainRouterVO if created. null if not.
- */
- DomainRouterVO createRouter(long accountId, String ipAddress, long dcId, String domain, ServiceOfferingVO offering, long startEventId) throws ConcurrentOperationException;
-
- /**
- * create a DHCP server/user data server for directly connected VMs
- * @param userId the user id of the user creating the router.
- * @param accountId the account id of the user creating the router.
- * @param dcId data center id the router should live in.
- * @param domain domain name of this network.
- * @return DomainRouterVO if created. null if not.
- */
- DomainRouterVO createDhcpServerForDirectlyAttachedGuests(long userId, long accountId, DataCenterVO dc, HostPodVO pod, Long candidateHost, VlanVO vlan) throws ConcurrentOperationException;
-
- /**
- /*
- * Send ssh public/private key pair to specified host
- * @param hostId
- * @param pubKey
- * @param prvKey
- */
- boolean sendSshKeysToHost(Long hostId, String pubKey, String prvKey);
-
- /**
- * save a vm password on the router.
- *
- * @param routerId the ID of the router to save the password to
- * @param vmIpAddress the IP address of the User VM that will use the password
- * @param password the password to save to the router
- */
- boolean savePasswordToRouter(long routerId, String vmIpAddress, String password);
-
- DomainRouterVO startRouter(long routerId, long eventId);
-
- boolean releaseRouter(long routerId);
-
- boolean destroyRouter(long routerId);
-
- boolean stopRouter(long routerId, long eventId);
-
- boolean getRouterStatistics(long vmId, Map netStats, Map diskStats);
-
- boolean rebootRouter(long routerId, long eventId);
-
- /**
- * @param hostId get all of the virtual machine routers on a host.
- * @return collection of VirtualMachineRouter
- */
- List extends VirtualRouter> getRouters(long hostId);
-
- /**
- * @param routerId id of the router
- * @return VirtualMachineRouter
- */
- DomainRouterVO getRouter(long routerId);
-
/**
* Do all of the work of releasing public ip addresses. Note that
* if this method fails, there can be side effects.
@@ -140,28 +73,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 +92,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
@@ -195,22 +104,6 @@ public interface NetworkManager extends NetworkService {
*/
public boolean addDhcpEntry(long routerHostId, String routerIp, String vmName, String vmMac, String vmIp);
- /**
- * Adds a virtual machine into the guest network.
- * 1. Starts the domR
- * 2. Sets the dhcp Entry on the domR
- * 3. Sets the domR
- *
- * @param vm user vm to add to the guest network
- * @param password password for this vm. Can be null
- * @return DomainRouterVO if everything is successful. null if not.
- *
- * @throws ConcurrentOperationException if multiple starts are being attempted.
- */
- public DomainRouterVO addVirtualMachineToGuestNetwork(UserVmVO vm, String password, long startEventId) throws ConcurrentOperationException;
-
- String createZoneVlan(DomainRouterVO router);
-
/**
* Lists IP addresses that belong to VirtualNetwork VLANs
* @param accountId - account that the IP address should belong to
@@ -220,8 +113,8 @@ public interface NetworkManager extends NetworkService {
*/
List listPublicIpAddressesInVirtualNetwork(long accountId, long dcId, Boolean sourceNat);
- List setupNetworkConfiguration(Account owner, NetworkOfferingVO offering, DeploymentPlan plan, String name, String displayText);
- List setupNetworkConfiguration(Account owner, NetworkOfferingVO offering, Network predefined, DeploymentPlan plan, String name, String displayText);
+ List setupNetworkConfiguration(Account owner, NetworkOfferingVO offering, DeploymentPlan plan, String name, String displayText, boolean isShared);
+ List setupNetworkConfiguration(Account owner, NetworkOfferingVO offering, Network predefined, DeploymentPlan plan, String name, String displayText, boolean isShared);
List getSystemAccountNetworkOfferings(String... offeringNames);
@@ -240,7 +133,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..de7c70deeb6 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;
@@ -71,7 +60,6 @@ import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.configuration.dao.ResourceLimitDao;
import com.cloud.dc.DataCenter;
import com.cloud.dc.DataCenterVO;
-import com.cloud.dc.HostPodVO;
import com.cloud.dc.Vlan;
import com.cloud.dc.Vlan.VlanType;
import com.cloud.dc.VlanVO;
@@ -94,12 +82,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;
@@ -114,9 +100,10 @@ import com.cloud.network.dao.NetworkRuleConfigDao;
import com.cloud.network.dao.RemoteAccessVpnDao;
import com.cloud.network.dao.VpnUserDao;
import com.cloud.network.element.NetworkElement;
+import com.cloud.network.lb.LoadBalancingRulesManager;
import com.cloud.network.router.DomainRouterManager;
-import com.cloud.network.router.VirtualRouter;
import com.cloud.network.rules.FirewallRule;
+import com.cloud.network.rules.RulesManager;
import com.cloud.offering.NetworkOffering;
import com.cloud.offering.NetworkOffering.GuestIpType;
import com.cloud.offerings.NetworkOfferingVO;
@@ -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;
@@ -163,7 +147,6 @@ import com.cloud.vm.NicProfile;
import com.cloud.vm.NicVO;
import com.cloud.vm.ReservationContext;
import com.cloud.vm.State;
-import com.cloud.vm.UserVmVO;
import com.cloud.vm.VMInstanceVO;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachineProfile;
@@ -218,6 +201,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
@Inject RemoteAccessVpnDao _remoteAccessVpnDao = null;
@Inject VpnUserDao _vpnUsersDao = null;
@Inject DomainRouterManager _routerMgr;
+ @Inject RulesManager _rulesMgr;
+ @Inject LoadBalancingRulesManager _lbMgr;
@Inject(adapter=NetworkGuru.class)
Adapters _networkGurus;
@@ -231,15 +216,11 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
SearchBuilder AccountsUsingNetworkConfigurationSearch;
private Map _configs;
-
- @Override
- public boolean sendSshKeysToHost(Long hostId, String pubKey, String prvKey) {
- return _routerMgr.sendSshKeysToHost(hostId, pubKey, prvKey);
- }
+
@Override @DB
public String assignSourceNatIpAddress(Account account, final DataCenterVO dc, final String domain, final ServiceOfferingVO serviceOffering, long startEventId, HypervisorType hyperType) throws ResourceAllocationException {
- if (serviceOffering.getGuestIpType() == NetworkOffering.GuestIpType.DirectDual || serviceOffering.getGuestIpType() == NetworkOffering.GuestIpType.DirectSingle) {
+ if (serviceOffering.getGuestIpType() == NetworkOffering.GuestIpType.Direct) {
return null;
}
final long dcId = dc.getId();
@@ -335,7 +316,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
DomainRouterVO router = null;
try {
- router = createRouter(account.getId(), sourceNat, dcId, domain, serviceOffering, startEventId);
+ router = _routerMgr.createRouter(account.getId(), sourceNat, dcId, domain, serviceOffering, startEventId);
} catch (final Exception e) {
s_logger.error("Unable to create router for " + account.getAccountName(), e);
}
@@ -480,56 +461,6 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
}
}
- @Override
- @DB
- public DomainRouterVO createDhcpServerForDirectlyAttachedGuests(long userId, long accountId, DataCenterVO dc, HostPodVO pod, Long candidateHost, VlanVO guestVlan) throws ConcurrentOperationException{
- return _routerMgr.createDhcpServerForDirectlyAttachedGuests(userId, accountId, dc, pod, candidateHost, guestVlan);
- }
-
- @Override
- public boolean releaseRouter(final long routerId) {
- return destroyRouter(routerId);
- }
-
- @Override @DB
- public DomainRouterVO createRouter(final long accountId, final String publicIpAddress, final long dataCenterId,
- String domain, final ServiceOfferingVO offering, long startEventId)
- throws ConcurrentOperationException {
- return _routerMgr.createRouter(accountId, publicIpAddress, dataCenterId, domain, offering, startEventId);
- }
-
- @Override
- public boolean destroyRouter(final long routerId) {
- return _routerMgr.destroyRouter(routerId);
- }
-
- @Override
- public boolean savePasswordToRouter(final long routerId, final String vmIpAddress, final String password) {
- return _routerMgr.savePasswordToRouter(routerId, vmIpAddress, password);
- }
-
- @Override
- public DomainRouterVO startRouter(final long routerId, long eventId) {
- return _routerMgr.startRouter(routerId, eventId);
- }
-
- @Override
- public boolean stopRouter(final long routerId, long eventId) {
- return _routerMgr.stopRouter(routerId, eventId);
- }
-
-
- @Override
- public boolean getRouterStatistics(final long vmId, final Map netStats, final Map diskStats) {
- return _routerMgr.getRouterStatistics(vmId, netStats, diskStats);
- }
-
-
- @Override
- public boolean rebootRouter(final long routerId, long startEventId) {
- return _routerMgr.rebootRouter(routerId, startEventId);
- }
-
@Override
public boolean associateIP(final DomainRouterVO router, final List ipAddrList, final boolean add, long vmId) {
Commands cmds = new Commands(OnError.Continue);
@@ -538,7 +469,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
for (final String ipAddress: ipAddrList) {
IPAddressVO ip = _ipAddressDao.findById(ipAddress);
- VlanVO vlan = _vlanDao.findById(ip.getVlanDbId());
+ VlanVO vlan = _vlanDao.findById(ip.getVlanId());
ArrayList ipList = vlanIpMap.get(vlan.getId());
if (ipList == null) {
ipList = new ArrayList();
@@ -556,7 +487,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
} });
for (final IPAddressVO ip: ipList) {
- sourceNat = ip.getSourceNat();
+ sourceNat = ip.isSourceNat();
VlanVO vlan = vlanAndIp.getKey();
String vlanId = vlan.getVlanId();
String vlanGateway = vlan.getVlanGateway();
@@ -782,7 +713,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
public boolean associateIP(final DomainRouterVO router, final String ipAddress, final boolean add, long vmId) {
Commands cmds = new Commands(OnError.Continue);
IPAddressVO ip = _ipAddressDao.findById(ipAddress);
- VlanVO vlan = _vlanDao.findById(ip.getVlanDbId());
+ VlanVO vlan = _vlanDao.findById(ip.getVlanId());
boolean sourceNat = ip.isSourceNat();
boolean firstIP = (!sourceNat && (_ipAddressDao.countIPs(vlan.getDataCenterId(), router.getAccountId(), vlan.getVlanId(), vlan.getVlanGateway(), vlan.getVlanNetmask()) == 1));
String vlanId = vlan.getVlanId();
@@ -821,846 +752,121 @@ 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.");
- }
- }
-
+ @DB
+ protected IPAddressVO releaseOwnershipOfIpAddress(String ipAddress) {
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);
+ IPAddressVO ip = _ipAddressDao.lockRow(ipAddress, true);
+ if (ip == null) {
+ s_logger.warn("Unable to find allocated ip: " + ipAddress);
+ return null;
}
-
- // 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);
- }
+
+ if (ip.getAllocatedTime() == null) {
+ s_logger.debug("Ip Address is already rleeased: " + ipAddress);
+ return null;
}
+
+ ip.setAllocatedToAccountId(null);
+ ip.setAllocatedInDomainId(null);
+ _ipAddressDao.update(ip.getAddress(), ip);
+ txn.commit();
+ return ip;
}
-
- @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
+
+ @Override
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);
-
+ IPAddressVO ip = releaseOwnershipOfIpAddress(ipAddress);
+ if (ip == null) {
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);
+ }
+
+ Ip addr = new Ip(ipAddress);
+
+ if (s_logger.isDebugEnabled()) {
+ s_logger.debug("Releasing ip " + ipAddress + "; sourceNat = " + ip.isSourceNat());
+ }
+
+ boolean success = true;
+ try {
+ if (!_rulesMgr.revokeAllRules(addr, userId)) {
+ s_logger.warn("Unable to revoke all the port forwarding rules for ip " + ip);
+ success = false;
+ }
+ } catch (ResourceUnavailableException e) {
+ s_logger.warn("Unable to revoke all the port forwarding rules for ip " + ip, e);
+ success = false;
+ }
+
+ if (!_lbMgr.removeAllLoadBalanacers(addr)) {
+ s_logger.warn("Unable to revoke all the load balancer rules for ip " + ip);
+ success = false;
+ }
+
+ for (NetworkElement ne : _networkElements) {
+ try {
+ ne.disassociate(null, new Ip(ipAddress));
+ } catch (ResourceUnavailableException e) {
+ s_logger.warn("Unable to release the ip address " + ip, e);
+ success = false;
}
}
- }
-
- @Override
- public DomainRouterVO getRouter(final long routerId) {
- return _routerMgr.getRouter(routerId);
- }
-
- @Override
- public List extends VirtualRouter> getRouters(final long hostId) {
- 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);
+
+ if (success) {
+ _ipAddressDao.unassignIpAddress(ipAddress);
+ s_logger.debug("released a public ip: " + ipAddress);
}
+
+ final EventVO event = new EventVO();
+ event.setUserId(userId);
+ event.setAccountId(ip.getAllocatedToAccountId());
+ 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 success;
+
+// 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);
+// }
- 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();
- }
+// 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 {
}
private Integer getIntegerConfigValue(String configKey, Integer dflt) {
@@ -1727,9 +933,9 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
storageNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(storageNetworkOffering);
_systemNetworks.put(NetworkOfferingVO.SystemVmStorageNetwork, storageNetworkOffering);
- NetworkOfferingVO defaultGuestNetworkOffering = new NetworkOfferingVO(NetworkOffering.DefaultVirtualizedNetworkOffering, "Virtual Vlan", TrafficType.Guest, GuestIpType.Virtualized, false, false, rateMbps, multicastRateMbps, null, false, true);
+ NetworkOfferingVO defaultGuestNetworkOffering = new NetworkOfferingVO(NetworkOffering.DefaultVirtualizedNetworkOffering, "Virtual Vlan", TrafficType.Guest, GuestIpType.Virtual, false, false, rateMbps, multicastRateMbps, null, true);
defaultGuestNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(defaultGuestNetworkOffering);
- NetworkOfferingVO defaultGuestDirectNetworkOffering = new NetworkOfferingVO(NetworkOffering.DefaultDirectNetworkOffering, "Direct", TrafficType.Guest, GuestIpType.DirectSingle, false, false, rateMbps, multicastRateMbps, null, false, true);
+ NetworkOfferingVO defaultGuestDirectNetworkOffering = new NetworkOfferingVO(NetworkOffering.DefaultDirectNetworkOffering, "Direct", TrafficType.Guest, GuestIpType.Direct, false, false, rateMbps, multicastRateMbps, null, true);
defaultGuestNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(defaultGuestDirectNetworkOffering);
AccountsUsingNetworkConfigurationSearch = _accountDao.createSearchBuilder();
@@ -1771,23 +977,10 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
return (answer != null && answer.getResult());
}
- @Override
- public DomainRouterVO addVirtualMachineToGuestNetwork(UserVmVO vm, String password, long startEventId) throws ConcurrentOperationException {
- return _routerMgr.addVirtualMachineToGuestNetwork(vm, password, startEventId);
- }
-
- public void releaseVirtualMachineFromGuestNetwork(UserVmVO vm) {
- }
-
- @Override
- public String createZoneVlan(DomainRouterVO router) {
- return _routerMgr.createZoneVlan(router);
- }
-
@Override
public List listPublicIpAddressesInVirtualNetwork(long accountId, long dcId, Boolean sourceNat) {
SearchBuilder