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 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 result = _mgr.searchForIpForwardingRules(this); + List 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 result = _mgr.listLoadBalancerInstances(this); + List 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 loadBalancers = _mgr.searchForLoadBalancers(this); + List 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 result = _networkService.listPortForwardingRules(this); + List 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 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 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 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 vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientNetworkCapacityException; - boolean release(Network config, NicProfile nic, VirtualMachineProfile 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 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 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 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 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 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 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 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 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 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 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 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 searchForVpnUsers(ListVpnUsersCmd cmd); - List 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> addDao(String name, Class> 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 dao = (GenericDao)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 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 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 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 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 ipAddressSB = _ipAddressDao.createSearchBuilder(); - ipAddressSB.and("accountId", ipAddressSB.entity().getAccountId(), SearchCriteria.Op.EQ); + ipAddressSB.and("accountId", ipAddressSB.entity().getAllocatedToAccountId(), SearchCriteria.Op.EQ); ipAddressSB.and("dataCenterId", ipAddressSB.entity().getDataCenterId(), SearchCriteria.Op.EQ); if (sourceNat != null) { ipAddressSB.and("sourceNat", ipAddressSB.entity().isSourceNat(), SearchCriteria.Op.EQ); @@ -1795,7 +988,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag SearchBuilder virtualNetworkVlanSB = _vlanDao.createSearchBuilder(); virtualNetworkVlanSB.and("vlanType", virtualNetworkVlanSB.entity().getVlanType(), SearchCriteria.Op.EQ); - ipAddressSB.join("virtualNetworkVlanSB", virtualNetworkVlanSB, ipAddressSB.entity().getVlanDbId(), virtualNetworkVlanSB.entity().getId(), JoinBuilder.JoinType.INNER); + ipAddressSB.join("virtualNetworkVlanSB", virtualNetworkVlanSB, ipAddressSB.entity().getVlanId(), virtualNetworkVlanSB.entity().getId(), JoinBuilder.JoinType.INNER); SearchCriteria ipAddressSC = ipAddressSB.create(); ipAddressSC.setParameters("accountId", accountId); @@ -1809,12 +1002,12 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } @Override - public List setupNetworkConfiguration(Account owner, NetworkOfferingVO offering, DeploymentPlan plan, String name, String displayText) { - return setupNetworkConfiguration(owner, offering, null, plan, name, displayText); + public List setupNetworkConfiguration(Account owner, NetworkOfferingVO offering, DeploymentPlan plan, String name, String displayText, boolean isShared) { + return setupNetworkConfiguration(owner, offering, null, plan, name, displayText, isShared); } @Override - public List setupNetworkConfiguration(Account owner, NetworkOfferingVO offering, Network predefined, DeploymentPlan plan, String name, String displayText) { + public List setupNetworkConfiguration(Account owner, NetworkOfferingVO offering, Network predefined, DeploymentPlan plan, String name, String displayText, boolean isShared) { List configs = _networkConfigDao.listBy(owner.getId(), offering.getId(), plan.getDataCenterId()); if (configs.size() > 0) { if (s_logger.isDebugEnabled()) { @@ -1847,7 +1040,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag related = id; } - NetworkVO vo = new NetworkVO(id, config, offering.getId(), plan.getDataCenterId(), guru.getName(), owner.getDomainId(), owner.getId(), related, name, displayText); + NetworkVO vo = new NetworkVO(id, config, offering.getId(), plan.getDataCenterId(), guru.getName(), owner.getDomainId(), owner.getId(), related, name, displayText, isShared); configs.add(_networkConfigDao.persist(vo)); } @@ -2122,320 +1315,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return _nicDao.listBy(vm.getId()); } - @Override @DB - public boolean removeFromLoadBalancer(RemoveFromLoadBalancerRuleCmd cmd) throws InvalidParameterValueException { - Long userId = UserContext.current().getUserId(); - Account account = UserContext.current().getAccount(); - Long loadBalancerId = cmd.getId(); - Long vmInstanceId = cmd.getVirtualMachineId(); - List instanceIds = cmd.getVirtualMachineIds(); - - if ((vmInstanceId == null) && (instanceIds == null)) { - throw new ServerApiException(BaseCmd.PARAM_ERROR, "No virtual machine id specified."); - } - - // if a single instanceId was given, add it to the list so we can always just process the list if instanceIds - if (instanceIds == null) { - instanceIds = new ArrayList(); - instanceIds.add(vmInstanceId); - } - - if (userId == null) { - userId = Long.valueOf(1); - } - - LoadBalancerVO loadBalancer = _loadBalancerDao.findById(Long.valueOf(loadBalancerId)); - - if (loadBalancer == null) { - throw new ServerApiException(BaseCmd.PARAM_ERROR, "Unable to find load balancer rule with id " + loadBalancerId); - } else if (account != null) { - if (!isAdmin(account.getType()) && (loadBalancer.getAccountId() != account.getId())) { - throw new ServerApiException(BaseCmd.PARAM_ERROR, "Account " + account.getAccountName() + " does not own load balancer rule " + loadBalancer.getName() + - " (id:" + loadBalancer.getId() + ")"); - } else if (!_domainDao.isChildDomain(account.getDomainId(), loadBalancer.getDomainId())) { - throw new ServerApiException(BaseCmd.PARAM_ERROR, "Invalid load balancer rule id (" + loadBalancer.getId() + ") given, unable to remove virtual machine instances."); - } - } - - Transaction txn = Transaction.currentTxn(); - LoadBalancerVO loadBalancerLock = null; - boolean success = true; - try { - - IPAddressVO ipAddress = _ipAddressDao.findById(loadBalancer.getIpAddress()); - if (ipAddress == null) { - return false; - } - - DomainRouterVO router = _routerMgr.getRouter(ipAddress.getAccountId(), ipAddress.getDataCenterId()); - if (router == null) { - return false; - } - - txn.start(); - for (Long instanceId : instanceIds) { - UserVm userVm = _userVmDao.findById(instanceId); - if (userVm == null) { - s_logger.warn("Unable to find virtual machine with id " + instanceId); - throw new InvalidParameterValueException("Unable to find virtual machine with id " + instanceId); - } - FirewallRuleVO fwRule = _rulesDao.findByGroupAndPrivateIp(loadBalancerId, userVm.getGuestIpAddress(), false); - if (fwRule != null) { - fwRule.setEnabled(false); - _rulesDao.update(fwRule.getId(), fwRule); - } - } - - List allLbRules = new ArrayList(); - IPAddressVO ipAddr = _ipAddressDao.findById(loadBalancer.getIpAddress()); - List ipAddrs = listPublicIpAddressesInVirtualNetwork(loadBalancer.getAccountId(), ipAddr.getDataCenterId(), null); - for (IPAddressVO ipv : ipAddrs) { - List rules = _rulesDao.listIPForwarding(ipv.getAddress(), false); - allLbRules.addAll(rules); - } - - updateFirewallRules(loadBalancer.getIpAddress(), allLbRules, router); - - // firewall rules are updated, lock the load balancer as mappings are updated - loadBalancerLock = _loadBalancerDao.acquireInLockTable(loadBalancerId); - if (loadBalancerLock == null) { - s_logger.warn("removeFromLoadBalancer: failed to lock load balancer " + loadBalancerId + ", deleting mappings anyway..."); - } - - // remove all the loadBalancer->VM mappings - _loadBalancerVMMapDao.remove(loadBalancerId, instanceIds, Boolean.FALSE); - - // Save and create the event - String description; - String type = EventTypes.EVENT_NET_RULE_DELETE; - String level = EventVO.LEVEL_INFO; - - for (FirewallRuleVO updatedRule : allLbRules) { - if (!updatedRule.isEnabled()) { - _rulesDao.remove(updatedRule.getId()); - - description = "deleted load balancer rule [" + updatedRule.getPublicIpAddress() + ":" + updatedRule.getPublicPort() + "]->[" - + updatedRule.getPrivateIpAddress() + ":" + updatedRule.getPrivatePort() + "]" + " " + updatedRule.getProtocol(); - - EventUtils.saveEvent(userId, loadBalancer.getAccountId(), level, type, description); - } - } - txn.commit(); - } catch (Exception ex) { - s_logger.warn("Failed to delete load balancing rule with exception: ", ex); - success = false; - txn.rollback(); - } finally { - if (loadBalancerLock != null) { - _loadBalancerDao.releaseFromLockTable(loadBalancerId); - } - } - return success; - } - - @Override @DB - public boolean deleteLoadBalancerRule(DeleteLoadBalancerRuleCmd cmd) throws InvalidParameterValueException, PermissionDeniedException{ - Long loadBalancerId = cmd.getId(); - Long userId = UserContext.current().getUserId(); - Account account = UserContext.current().getAccount(); - - ///verify input parameters - LoadBalancerVO loadBalancer = _loadBalancerDao.findById(loadBalancerId); - if (loadBalancer == null) { - throw new InvalidParameterValueException ("Unable to find load balancer rule with id " + loadBalancerId); - } - - if (account != null) { - if (!isAdmin(account.getType())) { - if (loadBalancer.getAccountId() != account.getId()) { - throw new PermissionDeniedException("Account " + account.getAccountName() + " does not own load balancer rule " + loadBalancer.getName() + " (id:" + loadBalancerId + "), permission denied"); - } - } else if (!_domainDao.isChildDomain(account.getDomainId(), loadBalancer.getDomainId())) { - throw new PermissionDeniedException("Unable to delete load balancer rule " + loadBalancer.getName() + " (id:" + loadBalancerId + "), permission denied."); - } - } - - if (userId == null) { - userId = Long.valueOf(1); - } - - Transaction txn = Transaction.currentTxn(); - LoadBalancerVO loadBalancerLock = null; - try { - - IPAddressVO ipAddress = _ipAddressDao.findById(loadBalancer.getIpAddress()); - if (ipAddress == null) { - return false; - } - - DomainRouterVO router = _routerMgr.getRouter(ipAddress.getAccountId(), ipAddress.getDataCenterId()); - List fwRules = _firewallRulesDao.listByLoadBalancerId(loadBalancerId); - - txn.start(); - - if ((fwRules != null) && !fwRules.isEmpty()) { - for (FirewallRuleVO fwRule : fwRules) { - fwRule.setEnabled(false); - _firewallRulesDao.update(fwRule.getId(), fwRule); - } - - List allLbRules = new ArrayList(); - List ipAddrs = listPublicIpAddressesInVirtualNetwork(loadBalancer.getAccountId(), ipAddress.getDataCenterId(), null); - for (IPAddressVO ipv : ipAddrs) { - List rules = _firewallRulesDao.listIPForwarding(ipv.getAddress(), false); - allLbRules.addAll(rules); - } - - updateFirewallRules(loadBalancer.getIpAddress(), allLbRules, router); - - // firewall rules are updated, lock the load balancer as the mappings are updated - loadBalancerLock = _loadBalancerDao.acquireInLockTable(loadBalancerId); - if (loadBalancerLock == null) { - s_logger.warn("deleteLoadBalancer: failed to lock load balancer " + loadBalancerId + ", deleting mappings anyway..."); - } - - // remove all loadBalancer->VM mappings - List lbVmMap = _loadBalancerVMMapDao.listByLoadBalancerId(loadBalancerId); - if (lbVmMap != null && !lbVmMap.isEmpty()) { - for (LoadBalancerVMMapVO lb : lbVmMap) { - _loadBalancerVMMapDao.remove(lb.getId()); - } - } - - // Save and create the event - String description; - String type = EventTypes.EVENT_NET_RULE_DELETE; - String ruleName = "load balancer"; - String level = EventVO.LEVEL_INFO; - Account accountOwner = _accountDao.findById(loadBalancer.getAccountId()); - - for (FirewallRuleVO updatedRule : fwRules) { - _firewallRulesDao.remove(updatedRule.getId()); - - description = "deleted " + ruleName + " rule [" + updatedRule.getPublicIpAddress() + ":" + updatedRule.getPublicPort() + "]->[" - + updatedRule.getPrivateIpAddress() + ":" + updatedRule.getPrivatePort() + "]" + " " + updatedRule.getProtocol(); - - EventUtils.saveEvent(userId, accountOwner.getId(), level, type, description); - } - } - - txn.commit(); - } catch (Exception ex) { - txn.rollback(); - s_logger.error("Unexpected exception deleting load balancer " + loadBalancerId, ex); - return false; - } finally { - if (loadBalancerLock != null) { - _loadBalancerDao.releaseFromLockTable(loadBalancerId); - } - } - - boolean success = _loadBalancerDao.remove(loadBalancerId); - - // save off an event for removing the load balancer - EventVO event = new EventVO(); - event.setUserId(userId); - event.setAccountId(loadBalancer.getAccountId()); - event.setType(EventTypes.EVENT_LOAD_BALANCER_DELETE); - if (success) { - event.setLevel(EventVO.LEVEL_INFO); - String params = "id="+loadBalancer.getId(); - event.setParameters(params); - event.setDescription("Successfully deleted load balancer " + loadBalancer.getName() + " (id:" + loadBalancer.getId() + ")"); - } else { - event.setLevel(EventVO.LEVEL_ERROR); - event.setDescription("Failed to delete load balancer " + loadBalancer.getName() + " (id:" + loadBalancer.getId() + ")"); - } - _eventDao.persist(event); - return success; - } - - - @Override @DB - public LoadBalancerVO updateLoadBalancerRule(UpdateLoadBalancerRuleCmd cmd) throws InvalidParameterValueException, PermissionDeniedException{ - Long loadBalancerId = cmd.getId(); - String privatePort = cmd.getPrivatePort(); - String algorithm = cmd.getAlgorithm(); - String name = cmd.getLoadBalancerName(); - String description = cmd.getDescription(); - Account account = UserContext.current().getAccount(); - - //Verify input parameters - LoadBalancerVO loadBalancer = _loadBalancerDao.findById(loadBalancerId); - if (loadBalancer == null) { - throw new InvalidParameterValueException("Unable to find load balancer rule " + loadBalancerId + " for update."); - } - - // make sure the name's not already in use - if (name != null) { - LoadBalancerVO existingLB = _loadBalancerDao.findByAccountAndName(loadBalancer.getAccountId(), name); - if ((existingLB != null) && (existingLB.getId() != loadBalancer.getId())) { - throw new InvalidParameterValueException("Unable to update load balancer " + loadBalancer.getName() + " with new name " + name + ", the name is already in use."); - } - } - - Account lbOwner = _accountDao.findById(loadBalancer.getAccountId()); - if (lbOwner == null) { - throw new InvalidParameterValueException("Unable to update load balancer rule, cannot find owning account"); - } - - Long accountId = lbOwner.getId(); - if (account != null) { - if (!isAdmin(account.getType())) { - if (account.getId() != accountId.longValue()) { - throw new PermissionDeniedException("Unable to update load balancer rule, permission denied"); - } - } else if (!_domainDao.isChildDomain(account.getDomainId(), lbOwner.getDomainId())) { - throw new PermissionDeniedException("Unable to update load balancer rule, permission denied."); - } - } - - String updatedPrivatePort = ((privatePort == null) ? loadBalancer.getPrivatePort() : privatePort); - String updatedAlgorithm = ((algorithm == null) ? loadBalancer.getAlgorithm() : algorithm); - String updatedName = ((name == null) ? loadBalancer.getName() : name); - String updatedDescription = ((description == null) ? loadBalancer.getDescription() : description); - - Transaction txn = Transaction.currentTxn(); - try { - txn.start(); - loadBalancer.setPrivatePort(updatedPrivatePort); - loadBalancer.setAlgorithm(updatedAlgorithm); - loadBalancer.setName(updatedName); - loadBalancer.setDescription(updatedDescription); - _loadBalancerDao.update(loadBalancer.getId(), loadBalancer); - - List fwRules = _firewallRulesDao.listByLoadBalancerId(loadBalancer.getId()); - if ((fwRules != null) && !fwRules.isEmpty()) { - for (FirewallRuleVO fwRule : fwRules) { - fwRule.setPrivatePort(updatedPrivatePort); - fwRule.setAlgorithm(updatedAlgorithm); - _firewallRulesDao.update(fwRule.getId(), fwRule); - } - } - txn.commit(); - } catch (RuntimeException ex) { - s_logger.warn("Unhandled exception trying to update load balancer rule", ex); - txn.rollback(); - throw ex; - } finally { - txn.close(); - } - - // now that the load balancer has been updated, reconfigure the HA Proxy on the router with all the LB rules - List allLbRules = new ArrayList(); - IPAddressVO ipAddress = _ipAddressDao.findById(loadBalancer.getIpAddress()); - List ipAddrs = listPublicIpAddressesInVirtualNetwork(loadBalancer.getAccountId(), ipAddress.getDataCenterId(), null); - for (IPAddressVO ipv : ipAddrs) { - List rules = _firewallRulesDao.listIPForwarding(ipv.getAddress(), false); - allLbRules.addAll(rules); - } - - IPAddressVO ip = _ipAddressDao.findById(loadBalancer.getIpAddress()); - DomainRouterVO router = _routerMgr.getRouter(ip.getAccountId(), ip.getDataCenterId()); - updateFirewallRules(loadBalancer.getIpAddress(), allLbRules, router); - return _loadBalancerDao.findById(loadBalancer.getId()); - } public static boolean isAdmin(short accountType) { return ((accountType == Account.ACCOUNT_TYPE_ADMIN) || @@ -2445,8 +1325,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag private Account findAccountByIpAddress(String ipAddress) { IPAddressVO address = _ipAddressDao.findById(ipAddress); - if ((address != null) && (address.getAccountId() != null)) { - return _accountDao.findById(address.getAccountId()); + if ((address != null) && (address.getAllocatedToAccountId() != null)) { + return _accountDao.findById(address.getAllocatedToAccountId()); } return null; } @@ -2488,7 +1368,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return false; } - if (ipVO.getAllocated() == null) { + if (ipVO.getAllocatedTime() == null) { return true; } @@ -2497,18 +1377,18 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return false; } - if ((ipVO.getAccountId() == null) || (ipVO.getAccountId().longValue() != accountId)) { + if ((ipVO.getAllocatedToAccountId() == null) || (ipVO.getAllocatedToAccountId().longValue() != accountId)) { // FIXME: is the user visible in the admin account's domain???? if (!BaseCmd.isAdmin(Account.getType())) { if (s_logger.isDebugEnabled()) { s_logger.debug("permission denied disassociating IP address " + ipAddress + "; acct: " + accountId + "; ip (acct / dc / dom / alloc): " - + ipVO.getAccountId() + " / " + ipVO.getDataCenterId() + " / " + ipVO.getDomainId() + " / " + ipVO.getAllocated()); + + ipVO.getAllocatedToAccountId() + " / " + ipVO.getDataCenterId() + " / " + ipVO.getAllocatedInDomainId() + " / " + ipVO.getAllocatedTime()); } throw new PermissionDeniedException("User/account does not own supplied address"); } } - if (ipVO.getAllocated() == null) { + if (ipVO.getAllocatedTime() == null) { return true; } @@ -2516,13 +1396,13 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag throw new IllegalArgumentException("ip address is used for source nat purposes and can not be disassociated."); } - VlanVO vlan = _vlanDao.findById(ipVO.getVlanDbId()); + VlanVO vlan = _vlanDao.findById(ipVO.getVlanId()); if (!vlan.getVlanType().equals(VlanType.VirtualNetwork)) { throw new IllegalArgumentException("only ip addresses that belong to a virtual network may be disassociated."); } //Check for account wide pool. It will have an entry for account_vlan_map. - if (_accountVlanMapDao.findAccountVlanMap(accountId,ipVO.getVlanDbId()) != null){ + if (_accountVlanMapDao.findAccountVlanMap(accountId,ipVO.getVlanId()) != null){ throw new PermissionDeniedException(ipAddress + " belongs to Account wide IP pool and cannot be disassociated"); } @@ -2544,121 +1424,6 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } } - @Override @DB - public boolean deletePortForwardingRule(Long id, boolean sysContext) { - Long ruleId = id; - Long userId = null; - Account account = null; - if(sysContext){ - userId = User.UID_SYSTEM; - account = _accountDao.findById(User.UID_SYSTEM); - }else{ - userId = UserContext.current().getUserId(); - account = UserContext.current().getAccount(); - } - - - //verify input parameters here - FirewallRuleVO rule = _firewallRulesDao.findById(ruleId); - if (rule == null) { - throw new InvalidParameterValueException("Unable to find port forwarding rule " + ruleId); - } - - String publicIp = rule.getPublicIpAddress(); - String privateIp = rule.getPrivateIpAddress(); - - IPAddressVO ipAddress = _ipAddressDao.findById(publicIp); - if (ipAddress == null) { - throw new InvalidParameterValueException("Unable to find IP address for port forwarding rule " + ruleId); - } - - // although we are not writing these values to the DB, we will check - // them out of an abundance - // of caution (may not be warranted) - String privatePort = rule.getPrivatePort(); - String publicPort = rule.getPublicPort(); - if (!NetUtils.isValidPort(publicPort) || !NetUtils.isValidPort(privatePort)) { - throw new InvalidParameterValueException("Invalid value for port"); - } - - String proto = rule.getProtocol(); - if (!NetUtils.isValidProto(proto)) { - throw new InvalidParameterValueException("Invalid protocol"); - } - - Account ruleOwner = _accountDao.findById(ipAddress.getAccountId()); - if (ruleOwner == null) { - throw new InvalidParameterValueException("Unable to find owning account for port forwarding rule " + ruleId); - } - - // if an admin account was passed in, or no account was passed in, make sure we honor the accountName/domainId parameters - if (account != null) { - if (isAdmin(account.getType())) { - if (!_domainDao.isChildDomain(account.getDomainId(), ruleOwner.getDomainId())) { - throw new PermissionDeniedException("Unable to delete port forwarding rule " + ruleId + ", permission denied."); - } - } else if (account.getId() != ruleOwner.getId()) { - throw new PermissionDeniedException("Unable to delete port forwarding rule " + ruleId + ", permission denied."); - } - } - - Transaction txn = Transaction.currentTxn(); - boolean locked = false; - boolean success = false; - try { - - IPAddressVO ipVO = _ipAddressDao.acquireInLockTable(publicIp); - if (ipVO == null) { - // throw this exception because hackers can use the api to probe for allocated ips - throw new PermissionDeniedException("User does not own supplied address"); - } - - locked = true; - txn.start(); - List fwdings = _firewallRulesDao.listIPForwardingForUpdate(publicIp, publicPort, proto); - FirewallRuleVO fwRule = null; - if (fwdings.size() == 0) { - throw new InvalidParameterValueException("No such rule"); - } else if (fwdings.size() == 1) { - fwRule = fwdings.get(0); - if (fwRule.getPrivateIpAddress().equalsIgnoreCase(privateIp) && fwRule.getPrivatePort().equals(privatePort)) { - _firewallRulesDao.expunge(fwRule.getId()); - } else { - throw new InvalidParameterValueException("No such rule"); - } - } else { - throw new CloudRuntimeException("Multiple matches. Please contact support"); - } - fwRule.setEnabled(false); - success = updateFirewallRule(fwRule, null, null); - - String description; - String type = EventTypes.EVENT_NET_RULE_DELETE; - String level = EventVO.LEVEL_INFO; - String ruleName = rule.isForwarding() ? "ip forwarding" : "load balancer"; - - if (success) { - description = "deleted " + ruleName + " rule [" + publicIp + ":" + rule.getPublicPort() + "]->[" + rule.getPrivateIpAddress() + ":" - + rule.getPrivatePort() + "] " + rule.getProtocol(); - } else { - level = EventVO.LEVEL_ERROR; - description = "Error while deleting " + ruleName + " rule [" + publicIp + ":" + rule.getPublicPort() + "]->[" + rule.getPrivateIpAddress() + ":" - + rule.getPrivatePort() + "] " + rule.getProtocol(); - } - EventUtils.saveEvent(userId, ipAddress.getAccountId(), level, type, description); - txn.commit(); - }catch (Exception ex) { - txn.rollback(); - s_logger.error("Unexpected exception deleting port forwarding rule " + ruleId, ex); - return false; - }finally { - if (locked) { - _ipAddressDao.releaseFromLockTable(publicIp); - } - txn.close(); - } - return success; - } @Override public List getAccountsUsingNetworkConfiguration(long configurationId) { @@ -2684,7 +1449,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @Override public List setupNetworkConfiguration(Account owner, ServiceOfferingVO offering, DeploymentPlan plan) { NetworkOfferingVO networkOffering = _networkOfferingDao.findByServiceOffering(offering); - return setupNetworkConfiguration(owner, networkOffering, plan, null, null); + return setupNetworkConfiguration(owner, networkOffering, plan, null, null, false); } private String [] getGuestIpRange() { @@ -2698,124 +1463,125 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @DB public RemoteAccessVpnVO createRemoteAccessVpn(CreateRemoteAccessVpnCmd cmd) throws InvalidParameterValueException, PermissionDeniedException, ConcurrentOperationException { - String publicIp = cmd.getPublicIp(); - IPAddressVO ipAddr = null; - Account account = getAccountForApiCommand(cmd.getAccountName(), cmd.getDomainId()); - if (publicIp == null) { - List accountAddrs = _ipAddressDao.listByAccount(account.getId()); - for (IPAddressVO addr: accountAddrs){ - if (addr.getSourceNat() && addr.getDataCenterId() == cmd.getZoneId()){ - ipAddr = addr; - publicIp = ipAddr.getAddress(); - break; - } - } - if (ipAddr == null) { - throw new InvalidParameterValueException("Account " + account.getAccountName() + " does not have any public ip addresses in zone " + cmd.getZoneId()); - } - } - - // make sure ip address exists - ipAddr = _ipAddressDao.findById(publicIp); - if (ipAddr == null) { - throw new InvalidParameterValueException("Unable to create remote access vpn, invalid public IP address " + publicIp); - } - - VlanVO vlan = _vlanDao.findById(ipAddr.getVlanDbId()); - if (vlan != null) { - if (!VlanType.VirtualNetwork.equals(vlan.getVlanType())) { - throw new InvalidParameterValueException("Unable to create VPN for IP address " + publicIp + ", only VirtualNetwork type IP addresses can be used for VPN."); - } - } - assert vlan != null:"Inconsistent DB state -- ip address does not belong to any vlan?"; - - if ((ipAddr.getAccountId() == null) || (ipAddr.getAllocated() == null)) { - throw new PermissionDeniedException("Unable to create VPN, permission denied for ip " + publicIp); - } - - if (account != null) { - if ((account.getType() == Account.ACCOUNT_TYPE_ADMIN) || (account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN)) { - if (!_domainDao.isChildDomain(account.getDomainId(), ipAddr.getDomainId())) { - throw new PermissionDeniedException("Unable to create VPN with public IP address " + publicIp + ", permission denied."); - } - } else if (account.getId() != ipAddr.getAccountId().longValue()) { - throw new PermissionDeniedException("Unable to create VPN for account " + account.getAccountName() + " doesn't own ip address " + publicIp); - } - } - - RemoteAccessVpnVO vpnVO = _remoteAccessVpnDao.findByPublicIpAddress(publicIp); - if (vpnVO != null) { - throw new InvalidParameterValueException("A Remote Access VPN already exists for this public Ip address"); - } - //TODO: assumes one virtual network / domr per account per zone - vpnVO = _remoteAccessVpnDao.findByAccountAndZone(account.getId(), cmd.getZoneId()); - if (vpnVO != null) { - throw new InvalidParameterValueException("A Remote Access VPN already exists for this account"); - } - String ipRange = cmd.getIpRange(); - if (ipRange == null) { - ipRange = _configs.get(Config.RemoteAccessVpnClientIpRange.key()); - } - String [] range = ipRange.split("-"); - if (range.length != 2) { - throw new InvalidParameterValueException("Invalid ip range"); - } - if (!NetUtils.isValidIp(range[0]) || !NetUtils.isValidIp(range[1])){ - throw new InvalidParameterValueException("Invalid ip in range specification " + ipRange); - } - if (!NetUtils.validIpRange(range[0], range[1])){ - throw new InvalidParameterValueException("Invalid ip range " + ipRange); - } - String [] guestIpRange = getGuestIpRange(); - if (NetUtils.ipRangesOverlap(range[0], range[1], guestIpRange[0], guestIpRange[1])) { - throw new InvalidParameterValueException("Invalid ip range: " + ipRange + " overlaps with guest ip range " + guestIpRange[0] + "-" + guestIpRange[1]); - } - //TODO: check sufficient range - //TODO: check overlap with private and public ip ranges in datacenter - - long startIp = NetUtils.ip2Long(range[0]); - String newIpRange = NetUtils.long2Ip(++startIp) + "-" + range[1]; - String sharedSecret = PasswordGenerator.generatePresharedKey(getIntegerConfigValue(Config.RemoteAccessVpnPskLength.key(), 24)); - Transaction txn = Transaction.currentTxn(); - txn.start(); - boolean locked = false; - try { - ipAddr = _ipAddressDao.acquireInLockTable(publicIp); - if (ipAddr == null) { - throw new ConcurrentOperationException("Another operation active, unable to create vpn"); - } - locked = true; - //check overlap with port forwarding rules on this ip (udp ports 500, 4500) - List existing = _rulesDao.listIPForwardingByPortAndProto(publicIp, NetUtils.VPN_PORT, NetUtils.UDP_PROTO); - if (!existing.isEmpty()) { - throw new InvalidParameterValueException("UDP Port " + NetUtils.VPN_PORT + " is configured for destination NAT"); - } - existing = _rulesDao.listIPForwardingByPortAndProto(publicIp, NetUtils.VPN_NATT_PORT, NetUtils.UDP_PROTO); - if (!existing.isEmpty()) { - throw new InvalidParameterValueException("UDP Port " + NetUtils.VPN_NATT_PORT + " is configured for destination NAT"); - } - existing = _rulesDao.listIPForwardingByPortAndProto(publicIp, NetUtils.VPN_L2TP_PORT, NetUtils.UDP_PROTO); - if (!existing.isEmpty()) { - throw new InvalidParameterValueException("UDP Port " + NetUtils.VPN_L2TP_PORT + " is configured for destination NAT"); - } - if (_rulesDao.isPublicIpOneToOneNATted(publicIp)) { - throw new InvalidParameterValueException("Public Ip " + publicIp + " is configured for destination NAT"); - } - vpnVO = new RemoteAccessVpnVO(account.getId(), cmd.getZoneId(), publicIp, range[0], newIpRange, sharedSecret); - vpnVO = _remoteAccessVpnDao.persist(vpnVO); - FirewallRuleVO rule = new FirewallRuleVO(null, publicIp, NetUtils.VPN_PORT, guestIpRange[0], NetUtils.VPN_PORT, true, NetUtils.UDP_PROTO, false, null); - _rulesDao.persist(rule); - rule = new FirewallRuleVO(null, publicIp, NetUtils.VPN_NATT_PORT, guestIpRange[0], NetUtils.VPN_NATT_PORT, true, NetUtils.UDP_PROTO, false, null); - _rulesDao.persist(rule); - rule = new FirewallRuleVO(null, publicIp, NetUtils.VPN_L2TP_PORT, guestIpRange[0], NetUtils.VPN_L2TP_PORT, true, NetUtils.UDP_PROTO, false, null); - _rulesDao.persist(rule); - txn.commit(); - return vpnVO; - } finally { - if (locked) { - _ipAddressDao.releaseFromLockTable(publicIp); - } - } + return null; +// String publicIp = cmd.getPublicIp(); +// IPAddressVO ipAddr = null; +// Account account = getAccountForApiCommand(cmd.getAccountName(), cmd.getDomainId()); +// if (publicIp == null) { +// List accountAddrs = _ipAddressDao.listByAccount(account.getId()); +// for (IPAddressVO addr: accountAddrs){ +// if (addr.getSourceNat() && addr.getDataCenterId() == cmd.getZoneId()){ +// ipAddr = addr; +// publicIp = ipAddr.getAddress(); +// break; +// } +// } +// if (ipAddr == null) { +// throw new InvalidParameterValueException("Account " + account.getAccountName() + " does not have any public ip addresses in zone " + cmd.getZoneId()); +// } +// } +// +// // make sure ip address exists +// ipAddr = _ipAddressDao.findById(publicIp); +// if (ipAddr == null) { +// throw new InvalidParameterValueException("Unable to create remote access vpn, invalid public IP address " + publicIp); +// } +// +// VlanVO vlan = _vlanDao.findById(ipAddr.getVlanDbId()); +// if (vlan != null) { +// if (!VlanType.VirtualNetwork.equals(vlan.getVlanType())) { +// throw new InvalidParameterValueException("Unable to create VPN for IP address " + publicIp + ", only VirtualNetwork type IP addresses can be used for VPN."); +// } +// } +// assert vlan != null:"Inconsistent DB state -- ip address does not belong to any vlan?"; +// +// if ((ipAddr.getAccountId() == null) || (ipAddr.getAllocated() == null)) { +// throw new PermissionDeniedException("Unable to create VPN, permission denied for ip " + publicIp); +// } +// +// if (account != null) { +// if ((account.getType() == Account.ACCOUNT_TYPE_ADMIN) || (account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN)) { +// if (!_domainDao.isChildDomain(account.getDomainId(), ipAddr.getDomainId())) { +// throw new PermissionDeniedException("Unable to create VPN with public IP address " + publicIp + ", permission denied."); +// } +// } else if (account.getId() != ipAddr.getAccountId().longValue()) { +// throw new PermissionDeniedException("Unable to create VPN for account " + account.getAccountName() + " doesn't own ip address " + publicIp); +// } +// } +// +// RemoteAccessVpnVO vpnVO = _remoteAccessVpnDao.findByPublicIpAddress(publicIp); +// if (vpnVO != null) { +// throw new InvalidParameterValueException("A Remote Access VPN already exists for this public Ip address"); +// } +// //TODO: assumes one virtual network / domr per account per zone +// vpnVO = _remoteAccessVpnDao.findByAccountAndZone(account.getId(), cmd.getZoneId()); +// if (vpnVO != null) { +// throw new InvalidParameterValueException("A Remote Access VPN already exists for this account"); +// } +// String ipRange = cmd.getIpRange(); +// if (ipRange == null) { +// ipRange = _configs.get(Config.RemoteAccessVpnClientIpRange.key()); +// } +// String [] range = ipRange.split("-"); +// if (range.length != 2) { +// throw new InvalidParameterValueException("Invalid ip range"); +// } +// if (!NetUtils.isValidIp(range[0]) || !NetUtils.isValidIp(range[1])){ +// throw new InvalidParameterValueException("Invalid ip in range specification " + ipRange); +// } +// if (!NetUtils.validIpRange(range[0], range[1])){ +// throw new InvalidParameterValueException("Invalid ip range " + ipRange); +// } +// String [] guestIpRange = getGuestIpRange(); +// if (NetUtils.ipRangesOverlap(range[0], range[1], guestIpRange[0], guestIpRange[1])) { +// throw new InvalidParameterValueException("Invalid ip range: " + ipRange + " overlaps with guest ip range " + guestIpRange[0] + "-" + guestIpRange[1]); +// } +// //TODO: check sufficient range +// //TODO: check overlap with private and public ip ranges in datacenter +// +// long startIp = NetUtils.ip2Long(range[0]); +// String newIpRange = NetUtils.long2Ip(++startIp) + "-" + range[1]; +// String sharedSecret = PasswordGenerator.generatePresharedKey(getIntegerConfigValue(Config.RemoteAccessVpnPskLength.key(), 24)); +// Transaction txn = Transaction.currentTxn(); +// txn.start(); +// boolean locked = false; +// try { +// ipAddr = _ipAddressDao.acquireInLockTable(publicIp); +// if (ipAddr == null) { +// throw new ConcurrentOperationException("Another operation active, unable to create vpn"); +// } +// locked = true; +// //check overlap with port forwarding rules on this ip (udp ports 500, 4500) +// List existing = _rulesDao.listIPForwardingByPortAndProto(publicIp, NetUtils.VPN_PORT, NetUtils.UDP_PROTO); +// if (!existing.isEmpty()) { +// throw new InvalidParameterValueException("UDP Port " + NetUtils.VPN_PORT + " is configured for destination NAT"); +// } +// existing = _rulesDao.listIPForwardingByPortAndProto(publicIp, NetUtils.VPN_NATT_PORT, NetUtils.UDP_PROTO); +// if (!existing.isEmpty()) { +// throw new InvalidParameterValueException("UDP Port " + NetUtils.VPN_NATT_PORT + " is configured for destination NAT"); +// } +// existing = _rulesDao.listIPForwardingByPortAndProto(publicIp, NetUtils.VPN_L2TP_PORT, NetUtils.UDP_PROTO); +// if (!existing.isEmpty()) { +// throw new InvalidParameterValueException("UDP Port " + NetUtils.VPN_L2TP_PORT + " is configured for destination NAT"); +// } +// if (_rulesDao.isPublicIpOneToOneNATted(publicIp)) { +// throw new InvalidParameterValueException("Public Ip " + publicIp + " is configured for destination NAT"); +// } +// vpnVO = new RemoteAccessVpnVO(account.getId(), cmd.getZoneId(), publicIp, range[0], newIpRange, sharedSecret); +// vpnVO = _remoteAccessVpnDao.persist(vpnVO); +// PortForwardingRuleVO rule = new PortForwardingRuleVO(null, publicIp, NetUtils.VPN_PORT, guestIpRange[0], NetUtils.VPN_PORT, true, NetUtils.UDP_PROTO, false, null); +// _rulesDao.persist(rule); +// rule = new PortForwardingRuleVO(null, publicIp, NetUtils.VPN_NATT_PORT, guestIpRange[0], NetUtils.VPN_NATT_PORT, true, NetUtils.UDP_PROTO, false, null); +// _rulesDao.persist(rule); +// rule = new PortForwardingRuleVO(null, publicIp, NetUtils.VPN_L2TP_PORT, guestIpRange[0], NetUtils.VPN_L2TP_PORT, true, NetUtils.UDP_PROTO, false, null); +// _rulesDao.persist(rule); +// txn.commit(); +// return vpnVO; +// } finally { +// if (locked) { +// _ipAddressDao.releaseFromLockTable(publicIp); +// } +// } } @Override @@ -2824,7 +1590,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag Long userId = UserContext.current().getUserId(); Account account = getAccountForApiCommand(cmd.getAccountName(), cmd.getDomainId()); EventUtils.saveStartedEvent(userId, account.getId(), EventTypes.EVENT_REMOTE_ACCESS_VPN_CREATE, "Creating a Remote Access VPN for account: " + account.getAccountName() + " in zone " + cmd.getZoneId(), cmd.getStartEventId()); - RemoteAccessVpnVO vpnVO = _remoteAccessVpnDao.findById(cmd.getId()); + RemoteAccessVpnVO vpnVO = _remoteAccessVpnDao.findById(cmd.getEntityId()); String publicIp = vpnVO.getVpnServerAddress(); Long vpnId = vpnVO.getId(); Transaction txn = Transaction.currentTxn(); @@ -2859,44 +1625,45 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @Override @DB public boolean destroyRemoteAccessVpn(DeleteRemoteAccessVpnCmd cmd) throws ConcurrentOperationException { - Long userId = UserContext.current().getUserId(); - Account account = getAccountForApiCommand(cmd.getAccountName(), cmd.getDomainId()); - //TODO: assumes one virtual network / domr per account per zone - RemoteAccessVpnVO vpnVO = _remoteAccessVpnDao.findByAccountAndZone(account.getId(), cmd.getZoneId()); - if (vpnVO == null) { - throw new InvalidParameterValueException("No VPN found for account " + account.getAccountName() + " in zone " + cmd.getZoneId()); - } - EventUtils.saveStartedEvent(userId, account.getId(), EventTypes.EVENT_REMOTE_ACCESS_VPN_DESTROY, "Deleting Remote Access VPN for account: " + account.getAccountName() + " in zone " + cmd.getZoneId(), cmd.getStartEventId()); - String publicIp = vpnVO.getVpnServerAddress(); - Long vpnId = vpnVO.getId(); - Transaction txn = Transaction.currentTxn(); - txn.start(); - boolean locked = false; - boolean deleted = false; - try { - IPAddressVO ipAddr = _ipAddressDao.acquireInLockTable(publicIp); - if (ipAddr == null) { - throw new ConcurrentOperationException("Another operation active, unable to create vpn"); - } - locked = true; - - deleted = _routerMgr.deleteRemoteAccessVpn(vpnVO); - return deleted; - } finally { - if (deleted) { - _remoteAccessVpnDao.remove(vpnId); - _rulesDao.deleteIPForwardingByPublicIpAndPort(publicIp, NetUtils.VPN_PORT); - _rulesDao.deleteIPForwardingByPublicIpAndPort(publicIp, NetUtils.VPN_NATT_PORT); - _rulesDao.deleteIPForwardingByPublicIpAndPort(publicIp, NetUtils.VPN_L2TP_PORT); - EventUtils.saveEvent(userId, account.getId(), EventTypes.EVENT_REMOTE_ACCESS_VPN_DESTROY, "Deleted Remote Access VPN for account: " + account.getAccountName() + " in zone " + cmd.getZoneId()); - } else { - EventUtils.saveEvent(userId, account.getId(), EventVO.LEVEL_ERROR, EventTypes.EVENT_REMOTE_ACCESS_VPN_DESTROY, "Unable to delete Remote Access VPN ", account.getAccountName() + " in zone " + cmd.getZoneId()); - } - txn.commit(); - if (locked) { - _ipAddressDao.releaseFromLockTable(publicIp); - } - } +// Long userId = UserContext.current().getUserId(); +// Account account = getAccountForApiCommand(cmd.getAccountName(), cmd.getDomainId()); +// //TODO: assumes one virtual network / domr per account per zone +// RemoteAccessVpnVO vpnVO = _remoteAccessVpnDao.findByAccountAndZone(account.getId(), cmd.getZoneId()); +// if (vpnVO == null) { +// throw new InvalidParameterValueException("No VPN found for account " + account.getAccountName() + " in zone " + cmd.getZoneId()); +// } +// EventUtils.saveStartedEvent(userId, account.getId(), EventTypes.EVENT_REMOTE_ACCESS_VPN_DESTROY, "Deleting Remote Access VPN for account: " + account.getAccountName() + " in zone " + cmd.getZoneId(), cmd.getStartEventId()); +// String publicIp = vpnVO.getVpnServerAddress(); +// Long vpnId = vpnVO.getId(); +// Transaction txn = Transaction.currentTxn(); +// txn.start(); +// boolean locked = false; +// boolean deleted = false; +// try { +// IPAddressVO ipAddr = _ipAddressDao.acquireInLockTable(publicIp); +// if (ipAddr == null) { +// throw new ConcurrentOperationException("Another operation active, unable to create vpn"); +// } +// locked = true; +// +// deleted = _routerMgr.deleteRemoteAccessVpn(vpnVO); +// return deleted; +// } finally { +// if (deleted) { +// _remoteAccessVpnDao.remove(vpnId); +// _rulesDao.deleteIPForwardingByPublicIpAndPort(publicIp, NetUtils.VPN_PORT); +// _rulesDao.deleteIPForwardingByPublicIpAndPort(publicIp, NetUtils.VPN_NATT_PORT); +// _rulesDao.deleteIPForwardingByPublicIpAndPort(publicIp, NetUtils.VPN_L2TP_PORT); +// EventUtils.saveEvent(userId, account.getId(), EventTypes.EVENT_REMOTE_ACCESS_VPN_DESTROY, "Deleted Remote Access VPN for account: " + account.getAccountName() + " in zone " + cmd.getZoneId()); +// } else { +// EventUtils.saveEvent(userId, account.getId(), EventVO.LEVEL_ERROR, EventTypes.EVENT_REMOTE_ACCESS_VPN_DESTROY, "Unable to delete Remote Access VPN ", account.getAccountName() + " in zone " + cmd.getZoneId()); +// } +// txn.commit(); +// if (locked) { +// _ipAddressDao.releaseFromLockTable(publicIp); +// } +// } + return false; // FIXME } @Override @@ -3024,286 +1791,10 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } @Override @DB - public Network getNetworkConfiguration(long id) { + public Network getNetwork(long id) { return _networkConfigDao.findById(id); } - @Override @DB - public FirewallRule createIpForwardingRuleOnDomr(long ruleId) { - Transaction txn = Transaction.currentTxn(); - txn.start(); - boolean success = false; - FirewallRuleVO rule = null; - IPAddressVO ipAddress = null; - boolean locked = false; - try { - //get the rule - rule = _rulesDao.findById(ruleId); - - if(rule == null){ - throw new PermissionDeniedException("Cannot create ip forwarding rule in db"); - } - - //get ip address - ipAddress = _ipAddressDao.findById(rule.getPublicIpAddress()); - if (ipAddress == null) { - throw new InvalidParameterValueException("Unable to create ip forwarding rule on address " + ipAddress + ", invalid IP address specified."); - } - - //sync point - ipAddress = _ipAddressDao.acquireInLockTable(ipAddress.getAddress()); - - if(ipAddress == null){ - s_logger.warn("Unable to acquire lock on ipAddress for creating static NAT rule"); - return rule; - }else{ - locked = true; - } - - //get the domain router object - DomainRouterVO router = _routerMgr.getRouter(ipAddress.getAccountId(), ipAddress.getDataCenterId()); - success = createOrDeleteIpForwardingRuleOnDomr(rule,router,rule.getPrivateIpAddress(),true); //true +> create - - if(!success){ - //corner case; delete record from db as domR rule creation failed - _rulesDao.remove(ruleId); - throw new PermissionDeniedException("Cannot create ip forwarding rule on domr, hence deleting created record in db"); - } - - //update the user_ip_address record - ipAddress.setOneToOneNat(true); - _ipAddressDao.update(ipAddress.getAddress(),ipAddress); - - // Save and create the event - String description; - String ruleName = "ip forwarding"; - String level = EventVO.LEVEL_INFO; - - description = "created new " + ruleName + " rule [" + rule.getPublicIpAddress() + "]->[" - + rule.getPrivateIpAddress() + "]" + ":" + rule.getProtocol(); - - EventUtils.saveEvent(UserContext.current().getUserId(), ipAddress.getAccountId(), level, EventTypes.EVENT_NET_RULE_ADD, description); - txn.commit(); - } catch (Exception e) { - txn.rollback(); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage()); - }finally{ - if(locked){ - _ipAddressDao.releaseFromLockTable(ipAddress.getAddress()); - } - } - return rule; - } - - @Override @DB - public FirewallRule createIpForwardingRuleInDb(String ipAddr, long virtualMachineId) { - - Transaction txn = Transaction.currentTxn(); - txn.start(); - UserVmVO userVM = null; - FirewallRuleVO newFwRule = null; - boolean locked = false; - try { - // validate IP Address exists - IPAddressVO ipAddress = _ipAddressDao.findById(ipAddr); - if (ipAddress == null) { - throw new InvalidParameterValueException("Unable to create ip forwarding rule on address " + ipAddress + ", invalid IP address specified."); - } - - // validate user VM exists - userVM = _vmDao.findById(virtualMachineId); - if (userVM == null) { - throw new InvalidParameterValueException("Unable to create ip forwarding rule on address " + ipAddress + ", invalid virtual machine id specified (" + virtualMachineId + ")."); - } - - //sync point; cannot lock on rule ; hence sync on vm - userVM = _vmDao.acquireInLockTable(userVM.getId()); - - if(userVM == null){ - s_logger.warn("Unable to acquire lock on user vm for creating static NAT rule"); - return newFwRule; - }else{ - locked = true; - } - - // validate that IP address and userVM belong to the same account - if ((ipAddress.getAccountId() == null) || (ipAddress.getAccountId().longValue() != userVM.getAccountId())) { - throw new InvalidParameterValueException("Unable to create ip forwarding rule, IP address " + ipAddress + " owner is not the same as owner of virtual machine " + userVM.toString()); - } - - // validate that userVM is in the same availability zone as the IP address - if (ipAddress.getDataCenterId() != userVM.getDataCenterId()) { - throw new InvalidParameterValueException("Unable to create ip forwarding rule, IP address " + ipAddress + " is not in the same availability zone as virtual machine " + userVM.toString()); - } - - // if an admin account was passed in, or no account was passed in, make sure we honor the accountName/domainId parameters - Account account = UserContext.current().getAccount(); - if (account != null) { - if ((account.getType() == Account.ACCOUNT_TYPE_ADMIN) || (account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN)) { - if (!_domainDao.isChildDomain(account.getDomainId(), userVM.getDomainId())) { - throw new PermissionDeniedException("Unable to create ip forwarding rule, IP address " + ipAddress + " to virtual machine " + virtualMachineId + ", permission denied."); - } - } else if (account.getId() != userVM.getAccountId()) { - throw new PermissionDeniedException("Unable to create ip forwarding rule, IP address " + ipAddress + " to virtual machine " + virtualMachineId + ", permission denied."); - } - } - - // check for ip address/port conflicts by checking existing port/ip forwarding rules - List existingFirewallRules = _rulesDao.findRuleByPublicIp(ipAddr); - - if(existingFirewallRules.size() > 0){ - throw new NetworkRuleConflictException("There already exists a firewall rule for public ip:"+ipAddr); - } - - //check for ip address/port conflicts by checking existing load balancing rules - List existingLoadBalancerRules = _loadBalancerDao.listByIpAddress(ipAddr); - - if(existingLoadBalancerRules.size() > 0){ - throw new NetworkRuleConflictException("There already exists a load balancer rule for public ip:"+ipAddr); - } - - //if given ip address is already source nat, return error - if(ipAddress.isSourceNat()){ - throw new PermissionDeniedException("Cannot create a static nat rule for the ip:"+ipAddress.getAddress()+" ,this is already a source nat ip address"); - } - - //if given ip address is already static nat, return error - if(ipAddress.isOneToOneNat()){ - throw new PermissionDeniedException("Cannot create a static nat rule for the ip:"+ipAddress.getAddress()+" ,this is already a static nat ip address"); - } - - newFwRule = new FirewallRuleVO(); - newFwRule.setEnabled(true); - newFwRule.setForwarding(true); - newFwRule.setPrivatePort(null); - newFwRule.setProtocol(NetUtils.NAT_PROTO);//protocol cannot be null; adding this as a NAT - newFwRule.setPublicPort(null); - newFwRule.setPublicIpAddress(ipAddress.getAddress()); - newFwRule.setPrivateIpAddress(userVM.getGuestIpAddress()); - newFwRule.setGroupId(null); - - _rulesDao.persist(newFwRule); - txn.commit(); - } catch (Exception e) { - s_logger.warn("Unable to create new firewall rule for static NAT"); - txn.rollback(); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR,"Unable to create new firewall rule for static NAT:"+e.getMessage()); - }finally{ - if(locked) { - _vmDao.releaseFromLockTable(userVM.getId()); - } - } - - return newFwRule; - } - - @Override @DB - public boolean deleteIpForwardingRule(Long id) { - Long ruleId = id; - Long userId = UserContext.current().getUserId(); - Account account = UserContext.current().getAccount(); - - //verify input parameters here - FirewallRuleVO rule = _firewallRulesDao.findById(ruleId); - if (rule == null) { - throw new InvalidParameterValueException("Unable to find port forwarding rule " + ruleId); - } - - String publicIp = rule.getPublicIpAddress(); - - - IPAddressVO ipAddress = _ipAddressDao.findById(publicIp); - if (ipAddress == null) { - throw new InvalidParameterValueException("Unable to find IP address for ip forwarding rule " + ruleId); - } - - // although we are not writing these values to the DB, we will check - // them out of an abundance - // of caution (may not be warranted) - - Account ruleOwner = _accountDao.findById(ipAddress.getAccountId()); - if (ruleOwner == null) { - throw new InvalidParameterValueException("Unable to find owning account for ip forwarding rule " + ruleId); - } - - // if an admin account was passed in, or no account was passed in, make sure we honor the accountName/domainId parameters - if (account != null) { - if (isAdmin(account.getType())) { - if (!_domainDao.isChildDomain(account.getDomainId(), ruleOwner.getDomainId())) { - throw new PermissionDeniedException("Unable to delete ip forwarding rule " + ruleId + ", permission denied."); - } - } else if (account.getId() != ruleOwner.getId()) { - throw new PermissionDeniedException("Unable to delete ip forwarding rule " + ruleId + ", permission denied."); - } - } - - Transaction txn = Transaction.currentTxn(); - boolean locked = false; - boolean success = false; - try { - - ipAddress = _ipAddressDao.acquireInLockTable(publicIp); - if (ipAddress == null) { - throw new PermissionDeniedException("Unable to obtain lock on record for deletion"); - } - - locked = true; - txn.start(); - - final DomainRouterVO router = _routerMgr.getRouter(ipAddress.getAccountId(), ipAddress.getDataCenterId()); - success = createOrDeleteIpForwardingRuleOnDomr(rule, router, rule.getPrivateIpAddress(), false); - _firewallRulesDao.remove(ruleId); - - //update the ip_address record - ipAddress.setOneToOneNat(false); - _ipAddressDao.persist(ipAddress); - - String description; - String type = EventTypes.EVENT_NET_RULE_DELETE; - String level = EventVO.LEVEL_INFO; - String ruleName = rule.isForwarding() ? "ip forwarding" : "load balancer"; - - if (success) { - description = "deleted " + ruleName + " rule [" + publicIp +"]->[" + rule.getPrivateIpAddress() + "] " + rule.getProtocol(); - } else { - level = EventVO.LEVEL_ERROR; - description = "Error while deleting " + ruleName + " rule [" + publicIp + "]->[" + rule.getPrivateIpAddress() +"] " + rule.getProtocol(); - } - EventUtils.saveEvent(userId, ipAddress.getAccountId(), level, type, description); - txn.commit(); - }catch (Exception ex) { - txn.rollback(); - s_logger.error("Unexpected exception deleting port forwarding rule " + ruleId, ex); - return false; - }finally { - if (locked) { - _ipAddressDao.releaseFromLockTable(publicIp); - } - txn.close(); - } - return success; - } - - private boolean createOrDeleteIpForwardingRuleOnDomr(FirewallRuleVO fwRule, DomainRouterVO router, String guestIp, boolean create){ - - Commands cmds = new Commands(OnError.Continue); - final SetFirewallRuleCommand cmd = new SetFirewallRuleCommand(router.getInstanceName(), router.getPrivateIpAddress(),fwRule, create); - cmds.addCommand(cmd); - try { - _agentMgr.send(router.getHostId(), cmds); - } catch (final AgentUnavailableException e) { - s_logger.warn("agent unavailable", e); - } catch (final OperationTimedoutException e) { - s_logger.warn("Timed Out", e); - } - Answer[] answers = cmds.getAnswers(); - if (answers == null || answers[0].getResult() == false ){ - return false; - }else{ - return true; - } - } - @Override @DB public Network createNetwork(CreateNetworkCmd cmd) throws InvalidParameterValueException, PermissionDeniedException{ Account ctxAccount = UserContext.current().getAccount(); @@ -3321,6 +1812,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag String vlanId = cmd.getVlan(); String name = cmd.getNetworkName(); String displayText = cmd.getDisplayText(); + Boolean isShared = cmd.getIsShared(); Account owner = null; //Check if network offering exists @@ -3352,10 +1844,6 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } else { owner = ctxAccount; } - - if (owner.getId() == Account.ACCOUNT_ID_SYSTEM && !networkOffering.isShared()) { - throw new InvalidParameterValueException("Non-system account is required when create a network from Dedicated network offering with id=" + networkOfferingId); - } //VlanId can be specified only when network offering supports it if (vlanId != null && !networkOffering.getSpecifyVlan()) { @@ -3383,7 +1871,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } } - List networks = setupNetworkConfiguration(owner, networkOffering, userNetwork, plan, name, displayText); + List networks = setupNetworkConfiguration(owner, networkOffering, userNetwork, plan, name, displayText, isShared); Long networkId = null; if (networks == null || networks.isEmpty()) { @@ -3393,12 +1881,12 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag networkId = networks.get(0).getId(); } - //If network offering is shared, don't pass owner account and networkOfferingId for vlan - if (networkOffering.isShared()) { + //Don't pass owner to create vlan when network offering is of type Direct + if (networkOffering.getGuestIpType() == GuestIpType.Direct) { owner = null; } - if (ctxAccount.getType() == Account.ACCOUNT_TYPE_ADMIN && networkOffering.getGuestIpType() != GuestIpType.Virtualized && startIP != null && endIP != null && gateway != null) { + if (ctxAccount.getType() == Account.ACCOUNT_TYPE_ADMIN && networkOffering.getGuestIpType() != GuestIpType.Virtual && startIP != null && endIP != null && gateway != null) { //Create vlan ip range Vlan vlan = _configMgr.createVlanAndPublicIpRange(userId, zoneId, podId, startIP, endIP, gateway, vlanNetmask, false, vlanId, owner, networkId); if (vlan == null) { @@ -3421,10 +1909,12 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag public List searchForNetworks(ListNetworksCmd cmd) { Object id = cmd.getId(); Object keyword = cmd.getKeyword(); + Long zoneId= cmd.getZoneId(); Account account = UserContext.current().getAccount(); Long domainId = cmd.getDomainId(); String accountName = cmd.getAccountName(); Long accountId = null; + if (isAdmin(account.getType())) { if (domainId != null) { if ((account != null) && !_domainDao.isChildDomain(account.getDomainId(), domainId)) { @@ -3438,14 +1928,24 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } accountId = account.getId(); } - } + } else { + accountId = account.getId(); + } } else { accountId = account.getId(); } - Filter searchFilter = new Filter(NetworkVO.class, "id", false, cmd.getStartIndex(), cmd.getPageSizeVal()); - SearchCriteria sc = _networkConfigDao.createSearchCriteria(); + SearchBuilder sb = _networkConfigDao.createSearchBuilder(); + + //Don't display networks created of system network offerings + SearchBuilder networkOfferingSearch = _networkOfferingDao.createSearchBuilder(); + networkOfferingSearch.and("systemOnly", networkOfferingSearch.entity().isSystemOnly(), SearchCriteria.Op.EQ); + sb.join("networkOfferingSearch", networkOfferingSearch, sb.entity().getNetworkOfferingId(), networkOfferingSearch.entity().getId(), JoinBuilder.JoinType.INNER); + + + SearchCriteria sc = sb.create(); + sc.setJoinParameters("networkOfferingSearch", "systemOnly", false); if (keyword != null) { SearchCriteria ssc = _networkConfigDao.createSearchCriteria(); @@ -3457,9 +1957,17 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag sc.addAnd("id", SearchCriteria.Op.EQ, id); } - if (accountId != null) { - sc.addAnd("accountId", SearchCriteria.Op.EQ, accountId); + if (zoneId != null) { + sc.addAnd("dataCenterId", SearchCriteria.Op.EQ, zoneId); } + + SearchCriteria ssc = _networkConfigDao.createSearchCriteria(); + ssc.addOr("accountId", SearchCriteria.Op.EQ, accountId); + if (accountName == null && domainId == null) { + ssc.addOr("accountId", SearchCriteria.Op.EQ, 1L); + } + sc.addAnd("accountId", SearchCriteria.Op.SC, ssc); + return _networkConfigDao.search(sc, searchFilter); } @@ -3533,4 +2041,29 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } } + + @Override + public boolean applyRules(Ip ip, List rules, boolean continueOnError) throws ResourceUnavailableException { + if (rules.size() == 0) { + s_logger.debug("There are no rules to forward to the network elements"); + return true; + } + + boolean success = true; + Network network = _networkConfigDao.findById(rules.get(0).getNetworkId()); + for (NetworkElement ne : _networkElements) { + try { + boolean handled = ne.applyRules(network, rules); + s_logger.debug("Network Rules for " + ip + " were " + (handled ? "" : " not") + " handled by " + ne.getName()); + } catch (ResourceUnavailableException e) { + if (!continueOnError) { + throw e; + } + s_logger.warn("Problems with " + ne.getName() + " but pushing on", e); + success = false; + } + } + + return success; + } } diff --git a/server/src/com/cloud/network/NetworkVO.java b/server/src/com/cloud/network/NetworkVO.java index d99d06369e4..a83d54816c1 100644 --- a/server/src/com/cloud/network/NetworkVO.java +++ b/server/src/com/cloud/network/NetworkVO.java @@ -115,6 +115,9 @@ public class NetworkVO implements Network { @Column(name="dns2") String dns2; + @Column(name="shared") + boolean isShared; + public NetworkVO() { } @@ -137,8 +140,8 @@ public class NetworkVO implements Network { this.guestType = guestType; } - public NetworkVO(long id, Network that, long offeringId, long dataCenterId, String guruName, long domainId, long accountId, long related, String name, String displayText) { - this(id, that.getTrafficType(), that.getGuestType(), that.getMode(), that.getBroadcastDomainType(), offeringId, dataCenterId, domainId, accountId, related, name, displayText); + public NetworkVO(long id, Network that, long offeringId, long dataCenterId, String guruName, long domainId, long accountId, long related, String name, String displayText, Boolean isShared) { + this(id, that.getTrafficType(), that.getGuestType(), that.getMode(), that.getBroadcastDomainType(), offeringId, dataCenterId, domainId, accountId, related, name, displayText, isShared); this.gateway = that.getGateway(); this.dns1 = that.getDns1(); this.dns2 = that.getDns2(); @@ -162,8 +165,9 @@ public class NetworkVO implements Network { * @param accountId * @param name * @param displayText + * @param isShared TODO */ - public NetworkVO(long id, TrafficType trafficType, GuestIpType guestType, Mode mode, BroadcastDomainType broadcastDomainType, long networkOfferingId, long dataCenterId, long domainId, long accountId, long related, String name, String displayText) { + public NetworkVO(long id, TrafficType trafficType, GuestIpType guestType, Mode mode, BroadcastDomainType broadcastDomainType, long networkOfferingId, long dataCenterId, long domainId, long accountId, long related, String name, String displayText, Boolean isShared) { this(trafficType, guestType, mode, broadcastDomainType, networkOfferingId, dataCenterId); this.domainId = domainId; this.accountId = accountId; @@ -171,6 +175,7 @@ public class NetworkVO implements Network { this.id = id; this.name = name; this.displayText = displayText; + this.isShared = isShared; } @Override @@ -327,6 +332,15 @@ public class NetworkVO implements Network { public void setDisplayText(String displayText) { this.displayText = displayText; } + + @Override + public boolean isShared() { + return isShared; + } + + public void setShared(boolean isShared) { + this.isShared = isShared; + } @Override public boolean equals(Object obj) { @@ -359,4 +373,6 @@ public class NetworkVO implements Network { buf.append(id).append("|").append(trafficType.toString()).append("|").append(networkOfferingId).append("]"); return buf.toString(); } + + } diff --git a/server/src/com/cloud/network/configuration/GuestNetworkGuru.java b/server/src/com/cloud/network/configuration/GuestNetworkGuru.java index e134aca6033..972a0825ef3 100644 --- a/server/src/com/cloud/network/configuration/GuestNetworkGuru.java +++ b/server/src/com/cloud/network/configuration/GuestNetworkGuru.java @@ -32,13 +32,13 @@ import com.cloud.deploy.DeploymentPlan; import com.cloud.exception.InsufficientAddressCapacityException; import com.cloud.exception.InsufficientVirtualNetworkCapcityException; import com.cloud.exception.InvalidParameterValueException; +import com.cloud.network.Network; +import com.cloud.network.Network.State; +import com.cloud.network.NetworkManager; +import com.cloud.network.NetworkVO; import com.cloud.network.Networks.BroadcastDomainType; import com.cloud.network.Networks.Mode; import com.cloud.network.Networks.TrafficType; -import com.cloud.network.Network; -import com.cloud.network.Network.State; -import com.cloud.network.NetworkVO; -import com.cloud.network.NetworkManager; import com.cloud.offering.NetworkOffering; import com.cloud.offering.NetworkOffering.GuestIpType; import com.cloud.resource.Resource.ReservationStrategy; @@ -77,7 +77,7 @@ public class GuestNetworkGuru extends AdapterBase implements NetworkGuru { GuestIpType ipType = offering.getGuestIpType(); BroadcastDomainType broadcastType = null; Mode mode = null; - if (ipType == GuestIpType.Virtualized) { + if (ipType == GuestIpType.Virtual) { mode = Mode.Dhcp; broadcastType = BroadcastDomainType.Vlan; } else { @@ -229,7 +229,6 @@ public class GuestNetworkGuru extends AdapterBase implements NetworkGuru { @Override public boolean trash(Network config, NetworkOffering offering, Account owner) { - // TODO Auto-generated method stub return true; } } diff --git a/server/src/com/cloud/network/dao/FirewallRulesDao.java b/server/src/com/cloud/network/dao/FirewallRulesDao.java index 62cb4bde12e..c7941f7c45e 100644 --- a/server/src/com/cloud/network/dao/FirewallRulesDao.java +++ b/server/src/com/cloud/network/dao/FirewallRulesDao.java @@ -18,40 +18,47 @@ package com.cloud.network.dao; -import java.util.List; - -import com.cloud.network.FirewallRuleVO; +import java.util.List; + +import com.cloud.network.rules.FirewallRuleVO; import com.cloud.utils.db.GenericDao; +import com.cloud.utils.net.Ip; /* * Data Access Object for user_ip_address and ip_forwarding tables */ -public interface FirewallRulesDao extends GenericDao { - public List listIPForwarding(String publicIPAddress, boolean forwarding); - public List listIPForwarding(String publicIPAddress, String port, boolean forwarding); - - public List listIPForwarding(long userId); - public List listIPForwarding(long userId, long dcId); - public void deleteIPForwardingByPublicIpAddress(String ipAddress); - public List listIPForwarding(String publicIPAddress); - public List listIPForwardingForUpdate(String publicIPAddress); - public void disableIPForwarding(String publicIPAddress); - public List listIPForwardingForUpdate(String publicIp, boolean fwding); - public List listIPForwardingForUpdate(String publicIp, String publicPort, String proto); - public List listIPForwardingByPortAndProto(String publicIp, String publicPort, String proto); - - public List listLoadBalanceRulesForUpdate(String publicIp, String publicPort, String algo); - public List listIpForwardingRulesForLoadBalancers(String publicIp); - - - public List listRulesExcludingPubIpPort(String publicIpAddress, long securityGroupId); - public List listBySecurityGroupId(long securityGroupId); - public List listByLoadBalancerId(long loadBalancerId); - public List listForwardingByPubAndPrivIp(boolean forwarding, String publicIPAddress, String privateIp); - public FirewallRuleVO findByGroupAndPrivateIp(long groupId, String privateIp, boolean forwarding); - public List listByPrivateIp(String privateIp); - public boolean isPublicIpOneToOneNATted(String publicIp); - void deleteIPForwardingByPublicIpAndPort(String ipAddress, String port); - public List listIPForwardingForLB(long userId, long dcId); - public List findRuleByPublicIp(String publicIp); +public interface FirewallRulesDao extends GenericDao { + List listByIpAndNotRevoked(Ip ip); + + boolean setStateToAdd(FirewallRuleVO rule); + + boolean revoke(FirewallRuleVO rule); + +// public List listIPForwarding(String publicIPAddress, boolean forwarding); +// public List listIPForwarding(String publicIPAddress, String port, boolean forwarding); +// +// public List listIPForwarding(long userId); +// public List listIPForwarding(long userId, long dcId); +// public void deleteIPForwardingByPublicIpAddress(String ipAddress); +// public List listIPForwarding(String publicIPAddress); +// public List listIPForwardingForUpdate(String publicIPAddress); +// public void disableIPForwarding(String publicIPAddress); +// public List listIPForwardingForUpdate(String publicIp, boolean fwding); +// public List listIPForwardingForUpdate(String publicIp, String publicPort, String proto); +// public List listIPForwardingByPortAndProto(String publicIp, String publicPort, String proto); +// +// public List listLoadBalanceRulesForUpdate(String publicIp, String publicPort, String algo); +// public List listIpForwardingRulesForLoadBalancers(String publicIp); +// +// +// public List listRulesExcludingPubIpPort(String publicIpAddress, long securityGroupId); +// public List listBySecurityGroupId(long securityGroupId); +// public List listByLoadBalancerId(long loadBalancerId); +// public List listForwardingByPubAndPrivIp(boolean forwarding, String publicIPAddress, String privateIp); +// public PortForwardingRuleVO findByGroupAndPrivateIp(long groupId, String privateIp, boolean forwarding); +// public List findByPublicIpPrivateIpForNatRule(String publicIp,String privateIp); +// public List listByPrivateIp(String privateIp); +// public boolean isPublicIpOneToOneNATted(String publicIp); +// void deleteIPForwardingByPublicIpAndPort(String ipAddress, String port); +// public List listIPForwardingForLB(long userId, long dcId); } diff --git a/server/src/com/cloud/network/dao/FirewallRulesDaoImpl.java b/server/src/com/cloud/network/dao/FirewallRulesDaoImpl.java index 8a2033d7cea..28852a35605 100644 --- a/server/src/com/cloud/network/dao/FirewallRulesDaoImpl.java +++ b/server/src/com/cloud/network/dao/FirewallRulesDaoImpl.java @@ -18,407 +18,457 @@ package com.cloud.network.dao; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.util.ArrayList; import java.util.List; -import java.util.Map; import javax.ejb.Local; -import javax.naming.ConfigurationException; import org.apache.log4j.Logger; -import com.cloud.network.FirewallRuleVO; +import com.cloud.network.rules.FirewallRule.State; +import com.cloud.network.rules.FirewallRuleVO; +import com.cloud.utils.db.DB; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.db.Transaction; import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.exception.CloudRuntimeException; -import com.cloud.utils.net.NetUtils; +import com.cloud.utils.net.Ip; -@Local(value = { FirewallRulesDao.class }) +@Local(value=FirewallRulesDao.class) @DB(txn=false) public class FirewallRulesDaoImpl extends GenericDaoBase implements FirewallRulesDao { private static final Logger s_logger = Logger.getLogger(FirewallRulesDaoImpl.class); - - public static String SELECT_IP_FORWARDINGS_BY_USERID_SQL = null; - public static String SELECT_IP_FORWARDINGS_BY_USERID_AND_DCID_SQL = null; - public static String SELECT_LB_FORWARDINGS_BY_USERID_AND_DCID_SQL = null; - - - public static final String DELETE_IP_FORWARDING_BY_IPADDRESS_SQL = "DELETE FROM ip_forwarding WHERE public_ip_address = ?"; - public static final String DELETE_IP_FORWARDING_BY_IP_PORT_SQL = "DELETE FROM ip_forwarding WHERE public_ip_address = ? and public_port = ?"; - - public static final String DISABLE_IP_FORWARDING_BY_IPADDRESS_SQL = "UPDATE ip_forwarding set enabled=0 WHERE public_ip_address = ?"; - - - protected SearchBuilder FWByIPSearch; - protected SearchBuilder FWByIPAndForwardingSearch; - protected SearchBuilder FWByIPPortAndForwardingSearch; - protected SearchBuilder FWByIPPortProtoSearch; - protected SearchBuilder FWByIPPortAlgoSearch; - protected SearchBuilder FWByPrivateIPSearch; - protected SearchBuilder RulesExcludingPubIpPort; - protected SearchBuilder FWByGroupId; - protected SearchBuilder FWByIpForLB; - - protected SearchBuilder FWByGroupAndPrivateIp; - protected SearchBuilder FWByPublicIpSearch; - protected SearchBuilder OneToOneNATSearch; - - - protected FirewallRulesDaoImpl() { - } - - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - if (!super.configure(name, params)) { - return false; - } - - SELECT_IP_FORWARDINGS_BY_USERID_SQL = buildSelectByUserIdSql(); - if (s_logger.isDebugEnabled()) { - s_logger.debug(SELECT_IP_FORWARDINGS_BY_USERID_SQL); - } - - SELECT_IP_FORWARDINGS_BY_USERID_AND_DCID_SQL = buildSelectByUserIdAndDatacenterIdSql(); - if (s_logger.isDebugEnabled()) { - s_logger.debug(SELECT_IP_FORWARDINGS_BY_USERID_AND_DCID_SQL); - } - - SELECT_LB_FORWARDINGS_BY_USERID_AND_DCID_SQL = buildSelectByUserIdAndDatacenterIdForLBSql(); - if (s_logger.isDebugEnabled()) { - s_logger.debug(SELECT_LB_FORWARDINGS_BY_USERID_AND_DCID_SQL); - } - - - FWByIPSearch = createSearchBuilder(); - FWByIPSearch.and("publicIpAddress", FWByIPSearch.entity().getPublicIpAddress(), SearchCriteria.Op.EQ); - FWByIPSearch.done(); - - FWByIPAndForwardingSearch = createSearchBuilder(); - FWByIPAndForwardingSearch.and("publicIpAddress", FWByIPAndForwardingSearch.entity().getPublicIpAddress(), SearchCriteria.Op.EQ); - FWByIPAndForwardingSearch.and("forwarding", FWByIPAndForwardingSearch.entity().isForwarding(), SearchCriteria.Op.EQ); - FWByIPAndForwardingSearch.done(); - - FWByIPPortAndForwardingSearch = createSearchBuilder(); - FWByIPPortAndForwardingSearch.and("publicIpAddress", FWByIPPortAndForwardingSearch.entity().getPublicIpAddress(), SearchCriteria.Op.EQ); - FWByIPPortAndForwardingSearch.and("publicPort", FWByIPPortAndForwardingSearch.entity().getPublicPort(), SearchCriteria.Op.EQ); - FWByIPPortAndForwardingSearch.and("forwarding", FWByIPPortAndForwardingSearch.entity().isForwarding(), SearchCriteria.Op.EQ); - FWByIPPortAndForwardingSearch.done(); - - FWByIPPortProtoSearch = createSearchBuilder(); - FWByIPPortProtoSearch.and("publicIpAddress", FWByIPPortProtoSearch.entity().getPublicIpAddress(), SearchCriteria.Op.EQ); - FWByIPPortProtoSearch.and("publicPort", FWByIPPortProtoSearch.entity().getPublicPort(), SearchCriteria.Op.EQ); - FWByIPPortProtoSearch.and("protocol", FWByIPPortProtoSearch.entity().getProtocol(), SearchCriteria.Op.EQ); - FWByIPPortProtoSearch.done(); - - FWByIPPortAlgoSearch = createSearchBuilder(); - FWByIPPortAlgoSearch.and("publicIpAddress", FWByIPPortAlgoSearch.entity().getPublicIpAddress(), SearchCriteria.Op.EQ); - FWByIPPortAlgoSearch.and("publicPort", FWByIPPortAlgoSearch.entity().getPublicPort(), SearchCriteria.Op.EQ); - FWByIPPortAlgoSearch.and("algorithm", FWByIPPortAlgoSearch.entity().getAlgorithm(), SearchCriteria.Op.EQ); - FWByIPPortAlgoSearch.done(); - - FWByPrivateIPSearch = createSearchBuilder(); - FWByPrivateIPSearch.and("privateIpAddress", FWByPrivateIPSearch.entity().getPrivateIpAddress(), SearchCriteria.Op.EQ); - FWByPrivateIPSearch.done(); - - RulesExcludingPubIpPort = createSearchBuilder(); - RulesExcludingPubIpPort.and("publicIpAddress", RulesExcludingPubIpPort.entity().getPrivateIpAddress(), SearchCriteria.Op.EQ); - RulesExcludingPubIpPort.and("groupId", RulesExcludingPubIpPort.entity().getGroupId(), SearchCriteria.Op.NEQ); - RulesExcludingPubIpPort.and("forwarding", RulesExcludingPubIpPort.entity().isForwarding(), SearchCriteria.Op.EQ); - RulesExcludingPubIpPort.done(); - - FWByGroupId = createSearchBuilder(); - FWByGroupId.and("groupId", FWByGroupId.entity().getGroupId(), SearchCriteria.Op.EQ); - FWByGroupId.and("forwarding", FWByGroupId.entity().isForwarding(), SearchCriteria.Op.EQ); - FWByGroupId.done(); - - FWByGroupAndPrivateIp = createSearchBuilder(); - FWByGroupAndPrivateIp.and("groupId", FWByGroupAndPrivateIp.entity().getGroupId(), SearchCriteria.Op.EQ); - FWByGroupAndPrivateIp.and("privateIpAddress", FWByGroupAndPrivateIp.entity().getPrivateIpAddress(), SearchCriteria.Op.EQ); - FWByGroupAndPrivateIp.and("forwarding", FWByGroupAndPrivateIp.entity().isForwarding(), SearchCriteria.Op.EQ); - FWByGroupAndPrivateIp.done(); - - FWByPublicIpSearch = createSearchBuilder(); - FWByPublicIpSearch.and("publicIpAddress", FWByPublicIpSearch.entity().getPublicIpAddress(), SearchCriteria.Op.EQ); - FWByPublicIpSearch.done(); - - OneToOneNATSearch = createSearchBuilder(); - OneToOneNATSearch.and("publicIpAddress", OneToOneNATSearch.entity().getPublicIpAddress(), SearchCriteria.Op.EQ); - OneToOneNATSearch.and("protocol", OneToOneNATSearch.entity().getProtocol(), SearchCriteria.Op.EQ); - OneToOneNATSearch.done(); - - FWByIpForLB = createSearchBuilder(); - FWByIpForLB.and("publicIpAddress", FWByIpForLB.entity().getPublicIpAddress(), SearchCriteria.Op.EQ); - FWByIpForLB.and("groupId", FWByIpForLB.entity().getGroupId(), SearchCriteria.Op.NNULL); - FWByIpForLB.and("forwarding", FWByIpForLB.entity().isForwarding(), SearchCriteria.Op.EQ); - FWByIpForLB.done(); - - return true; - } - - protected String buildSelectByUserIdSql() { - StringBuilder sql = createPartialSelectSql(null, true); - sql.insert(sql.length() - 6, ", user_ip_address "); - sql.append("ip_forwarding.public_ip_address = user_ip_address.public_ip_address AND user_ip_address.account_id = ?"); - - return sql.toString(); - } - - protected String buildSelectByUserIdAndDatacenterIdSql() { - return "SELECT i.id, i.group_id, i.public_ip_address, i.public_port, i.private_ip_address, i.private_port, i.enabled, i.protocol, i.forwarding, i.algorithm FROM ip_forwarding i, user_ip_address u WHERE i.public_ip_address=u.public_ip_address AND u.account_id=? AND u.data_center_id=?"; - } - protected String buildSelectByUserIdAndDatacenterIdForLBSql() { - return "SELECT i.id, i.group_id, i.public_ip_address, i.public_port, i.private_ip_address, i.private_port, i.enabled, i.protocol, i.forwarding, i.algorithm FROM ip_forwarding i, user_ip_address u WHERE i.public_ip_address=u.public_ip_address AND u.account_id=? AND u.data_center_id=? AND i.group_id is not NULL"; - } - - public List listIPForwarding(String publicIPAddress, boolean forwarding) { - SearchCriteria sc = FWByIPAndForwardingSearch.create(); - sc.setParameters("publicIpAddress", publicIPAddress); - sc.setParameters("forwarding", forwarding); - return listBy(sc); - } - - @Override - public List listIPForwarding(long userId) { - Transaction txn = Transaction.currentTxn(); - List forwardings = new ArrayList(); - PreparedStatement pstmt = null; - try { - pstmt = txn.prepareAutoCloseStatement(SELECT_IP_FORWARDINGS_BY_USERID_SQL); - pstmt.setLong(1, userId); - ResultSet rs = pstmt.executeQuery(); - while (rs.next()) { - forwardings.add(toEntityBean(rs, false)); - } - } catch (Exception e) { - s_logger.warn(e); - } - return forwardings; - } - - public List listIPForwarding(long userId, long dcId) { - Transaction txn = Transaction.currentTxn(); - List forwardings = new ArrayList(); - PreparedStatement pstmt = null; - try { - pstmt = txn.prepareAutoCloseStatement(SELECT_IP_FORWARDINGS_BY_USERID_AND_DCID_SQL); - pstmt.setLong(1, userId); - pstmt.setLong(2, dcId); - ResultSet rs = pstmt.executeQuery(); - while (rs.next()) { - forwardings.add(toEntityBean(rs, false)); - } - } catch (Exception e) { - s_logger.warn(e); - } - return forwardings; - } - - @Override - public void deleteIPForwardingByPublicIpAddress(String ipAddress) { - Transaction txn = Transaction.currentTxn(); - PreparedStatement pstmt = null; - try { - pstmt = txn.prepareAutoCloseStatement(DELETE_IP_FORWARDING_BY_IPADDRESS_SQL); - pstmt.setString(1, ipAddress); - pstmt.executeUpdate(); - } catch (Exception e) { - s_logger.warn(e); - } - } + protected final SearchBuilder AllFieldsSearch; + protected final SearchBuilder IpNotRevokedSearch; + + protected FirewallRulesDaoImpl() { + super(); + + AllFieldsSearch = createSearchBuilder(); + AllFieldsSearch.and("ip", AllFieldsSearch.entity().getSourceIpAddress(), Op.EQ); + AllFieldsSearch.and("protocol", AllFieldsSearch.entity().getProtocol(), Op.EQ); + AllFieldsSearch.and("state", AllFieldsSearch.entity().getState(), Op.EQ); + AllFieldsSearch.and("purpose", AllFieldsSearch.entity().getPurpose(), Op.EQ); + AllFieldsSearch.and("account", AllFieldsSearch.entity().getAccountId(), Op.EQ); + AllFieldsSearch.and("domain", AllFieldsSearch.entity().getDomainId(), Op.EQ); + AllFieldsSearch.and("id", AllFieldsSearch.entity().getId(), Op.EQ); + AllFieldsSearch.done(); + + + IpNotRevokedSearch = createSearchBuilder(); + IpNotRevokedSearch.and("ip", IpNotRevokedSearch.entity().getSourceIpAddress(), Op.EQ); + IpNotRevokedSearch.and("state", IpNotRevokedSearch.entity().getState(), Op.NEQ); + IpNotRevokedSearch.done(); + + } @Override - public void deleteIPForwardingByPublicIpAndPort(String ipAddress, String port) { - Transaction txn = Transaction.currentTxn(); - PreparedStatement pstmt = null; - try { - pstmt = txn.prepareAutoCloseStatement(DELETE_IP_FORWARDING_BY_IP_PORT_SQL); - pstmt.setString(1, ipAddress); - pstmt.setString(2, port); - - pstmt.executeUpdate(); - } catch (Exception e) { - s_logger.warn(e); - } - } - - @Override - public List listIPForwarding(String publicIPAddress) { - SearchCriteria sc = FWByIPSearch.create(); - sc.setParameters("publicIpAddress", publicIPAddress); - return listBy(sc); - } - - @Override - public List listIPForwardingForUpdate(String publicIPAddress) { - SearchCriteria sc = FWByIPSearch.create(); - sc.setParameters("publicIpAddress", publicIPAddress); - return listBy(sc, null); - } - - @Override - public List listIPForwardingForUpdate(String publicIp, boolean fwding) { - SearchCriteria sc = FWByIPAndForwardingSearch.create(); - sc.setParameters("publicIpAddress", publicIp); - sc.setParameters("forwarding", fwding); - return search(sc, null); - } - - @Override - public List listIPForwardingForUpdate(String publicIp, - String publicPort, String proto) { - SearchCriteria sc = FWByIPPortProtoSearch.create(); - sc.setParameters("publicIpAddress", publicIp); - sc.setParameters("publicPort", publicPort); - sc.setParameters("protocol", proto); - return search(sc, null); - } - - @Override - public List listLoadBalanceRulesForUpdate(String publicIp, - String publicPort, String algo) { - SearchCriteria sc = FWByIPPortAlgoSearch.create(); - sc.setParameters("publicIpAddress", publicIp); - sc.setParameters("publicPort", publicPort); - sc.setParameters("algorithm", algo); - return listBy(sc, null); - } - - @Override - public List listIPForwarding(String publicIPAddress, - String port, boolean forwarding) { - SearchCriteria sc = FWByIPPortAndForwardingSearch.create(); - sc.setParameters("publicIpAddress", publicIPAddress); - sc.setParameters("publicPort", port); - sc.setParameters("forwarding", forwarding); - - return listBy(sc); - } - - @Override - public void disableIPForwarding(String publicIPAddress) { - Transaction txn = Transaction.currentTxn(); - PreparedStatement pstmt = null; - try { - txn.start(); - pstmt = txn.prepareAutoCloseStatement(DISABLE_IP_FORWARDING_BY_IPADDRESS_SQL); - pstmt.setString(1, publicIPAddress); - pstmt.executeUpdate(); - txn.commit(); - } catch (Exception e) { - txn.rollback(); - throw new CloudRuntimeException("DB Exception ", e); - } - } - - @Override - public List listRulesExcludingPubIpPort(String publicIpAddress, long securityGroupId) { - SearchCriteria sc = RulesExcludingPubIpPort.create(); - sc.setParameters("publicIpAddress", publicIpAddress); - sc.setParameters("groupId", securityGroupId); - sc.setParameters("forwarding", false); - return listBy(sc); - } - - @Override - public List listBySecurityGroupId(long securityGroupId) { - SearchCriteria sc = FWByGroupId.create(); - sc.setParameters("groupId", securityGroupId); - sc.setParameters("forwarding", Boolean.TRUE); - return listBy(sc); - } - - @Override - public List listForwardingByPubAndPrivIp(boolean forwarding, String publicIPAddress, String privateIp) { - SearchCriteria sc = FWByIPAndForwardingSearch.create(); - sc.setParameters("publicIpAddress", publicIPAddress); - sc.setParameters("forwarding", forwarding); - sc.addAnd("privateIpAddress", SearchCriteria.Op.EQ, privateIp); - return listBy(sc); - } - - @Override - public List listByLoadBalancerId(long loadBalancerId) { - SearchCriteria sc = FWByGroupId.create(); - sc.setParameters("groupId", loadBalancerId); - sc.setParameters("forwarding", Boolean.FALSE); - return listBy(sc); - } - - @Override - public FirewallRuleVO findByGroupAndPrivateIp(long groupId, String privateIp, boolean forwarding) { - SearchCriteria sc = FWByGroupAndPrivateIp.create(); - sc.setParameters("groupId", groupId); - sc.setParameters("privateIpAddress", privateIp); - sc.setParameters("forwarding", forwarding); - return findOneBy(sc); - - } - - @Override - public List findRuleByPublicIp(String publicIp){ - SearchCriteria sc = FWByPublicIpSearch.create(); - sc.setParameters("publicIpAddress", publicIp); - return listBy(sc); - } - - @Override - public List listByPrivateIp(String privateIp) { - SearchCriteria sc = FWByPrivateIPSearch.create(); - sc.setParameters("privateIpAddress", privateIp); + public List listByIpAndNotRevoked(Ip ip) { + SearchCriteria sc = IpNotRevokedSearch.create(); + sc.setParameters("ip", ip); + sc.setParameters("state", State.Revoke); + return listBy(sc); - } - - @Override - public List listIPForwardingByPortAndProto(String publicIp, - String publicPort, String proto) { - SearchCriteria sc = FWByIPPortProtoSearch.create(); - sc.setParameters("publicIpAddress", publicIp); - sc.setParameters("publicPort", publicPort); - sc.setParameters("protocol", proto); - return search(sc, null); - } - - @Override - public boolean isPublicIpOneToOneNATted(String publicIp) { - SearchCriteria sc = OneToOneNATSearch.create(); - sc.setParameters("publicIpAddress", publicIp); - sc.setParameters("protocol", NetUtils.NAT_PROTO); - List rules = search(sc, null); - if (rules.size() != 1) - return false; - return rules.get(1).getProtocol().equalsIgnoreCase(NetUtils.NAT_PROTO); - } - - @Override - public List listIpForwardingRulesForLoadBalancers( - String publicIp) { - SearchCriteria sc = FWByIpForLB.create(); - sc.setParameters("publicIpAddress", publicIp); - sc.setParameters("forwarding", false); - return search(sc, null); - } - - @Override - public List listIPForwardingForLB(long userId, long dcId) { - Transaction txn = Transaction.currentTxn(); - List forwardings = new ArrayList(); - PreparedStatement pstmt = null; - try { - pstmt = txn.prepareAutoCloseStatement(SELECT_LB_FORWARDINGS_BY_USERID_AND_DCID_SQL); - pstmt.setLong(1, userId); - pstmt.setLong(2, dcId); - ResultSet rs = pstmt.executeQuery(); - while (rs.next()) { - forwardings.add(toEntityBean(rs, false)); - } - } catch (Exception e) { - s_logger.warn(e); - } - return forwardings; - } + } + + @Override + public boolean setStateToAdd(FirewallRuleVO rule) { + SearchCriteria sc = AllFieldsSearch.create(); + sc.setParameters("id", rule.getId()); + sc.setParameters("state", State.Staged); + + rule.setState(State.Add); + + return update(rule, sc) > 0; + } + + @Override + public boolean revoke(FirewallRuleVO rule) { + rule.setState(State.Revoke); + return update(rule.getId(), rule); + } + + + +// public static String SELECT_IP_FORWARDINGS_BY_USERID_SQL = null; +// public static String SELECT_IP_FORWARDINGS_BY_USERID_AND_DCID_SQL = null; +// public static String SELECT_LB_FORWARDINGS_BY_USERID_AND_DCID_SQL = null; +// +// +// public static final String DELETE_IP_FORWARDING_BY_IPADDRESS_SQL = "DELETE FROM ip_forwarding WHERE public_ip_address = ?"; +// public static final String DELETE_IP_FORWARDING_BY_IP_PORT_SQL = "DELETE FROM ip_forwarding WHERE public_ip_address = ? and public_port = ?"; +// +// public static final String DISABLE_IP_FORWARDING_BY_IPADDRESS_SQL = "UPDATE ip_forwarding set enabled=0 WHERE public_ip_address = ?"; +// +// +// protected SearchBuilder FWByIPAndForwardingSearch; +// protected SearchBuilder FWByIPPortAndForwardingSearch; +// protected SearchBuilder FWByIPPortProtoSearch; +// protected SearchBuilder FWByIPPortAlgoSearch; +// protected SearchBuilder FWByPrivateIPSearch; +// protected SearchBuilder RulesExcludingPubIpPort; +// protected SearchBuilder FWByGroupId; +// protected SearchBuilder FWByIpForLB; +// +// protected SearchBuilder FWByGroupAndPrivateIp; +// protected SearchBuilder FWByPrivateIpPrivatePortPublicIpPublicPortSearch; +// protected SearchBuilder OneToOneNATSearch; +// +// +// protected FirewallRulesDaoImpl() { +// } +// +// @Override +// public boolean configure(String name, Map params) throws ConfigurationException { +// if (!super.configure(name, params)) { +// return false; +// } +// +// SELECT_IP_FORWARDINGS_BY_USERID_SQL = buildSelectByUserIdSql(); +// if (s_logger.isDebugEnabled()) { +// s_logger.debug(SELECT_IP_FORWARDINGS_BY_USERID_SQL); +// } +// +// SELECT_IP_FORWARDINGS_BY_USERID_AND_DCID_SQL = buildSelectByUserIdAndDatacenterIdSql(); +// if (s_logger.isDebugEnabled()) { +// s_logger.debug(SELECT_IP_FORWARDINGS_BY_USERID_AND_DCID_SQL); +// } +// +// SELECT_LB_FORWARDINGS_BY_USERID_AND_DCID_SQL = buildSelectByUserIdAndDatacenterIdForLBSql(); +// if (s_logger.isDebugEnabled()) { +// s_logger.debug(SELECT_LB_FORWARDINGS_BY_USERID_AND_DCID_SQL); +// } +// +// +// FWByIPSearch = createSearchBuilder(); +// FWByIPSearch.and("publicIpAddress", FWByIPSearch.entity().getSourceIpAddress(), SearchCriteria.Op.EQ); +// FWByIPSearch.done(); +// +// FWByIPAndForwardingSearch = createSearchBuilder(); +// FWByIPAndForwardingSearch.and("publicIpAddress", FWByIPAndForwardingSearch.entity().getSourceIpAddress(), SearchCriteria.Op.EQ); +// FWByIPAndForwardingSearch.and("forwarding", FWByIPAndForwardingSearch.entity().isForwarding(), SearchCriteria.Op.EQ); +// FWByIPAndForwardingSearch.done(); +// +// FWByIPPortAndForwardingSearch = createSearchBuilder(); +// FWByIPPortAndForwardingSearch.and("publicIpAddress", FWByIPPortAndForwardingSearch.entity().getSourceIpAddress(), SearchCriteria.Op.EQ); +// FWByIPPortAndForwardingSearch.and("publicPort", FWByIPPortAndForwardingSearch.entity().getSourcePort(), SearchCriteria.Op.EQ); +// FWByIPPortAndForwardingSearch.and("forwarding", FWByIPPortAndForwardingSearch.entity().isForwarding(), SearchCriteria.Op.EQ); +// FWByIPPortAndForwardingSearch.done(); +// +// FWByIPPortProtoSearch = createSearchBuilder(); +// FWByIPPortProtoSearch.and("publicIpAddress", FWByIPPortProtoSearch.entity().getSourceIpAddress(), SearchCriteria.Op.EQ); +// FWByIPPortProtoSearch.and("publicPort", FWByIPPortProtoSearch.entity().getSourcePort(), SearchCriteria.Op.EQ); +// FWByIPPortProtoSearch.and("protocol", FWByIPPortProtoSearch.entity().getProtocol(), SearchCriteria.Op.EQ); +// FWByIPPortProtoSearch.done(); +// +// FWByIPPortAlgoSearch = createSearchBuilder(); +// FWByIPPortAlgoSearch.and("publicIpAddress", FWByIPPortAlgoSearch.entity().getSourceIpAddress(), SearchCriteria.Op.EQ); +// FWByIPPortAlgoSearch.and("publicPort", FWByIPPortAlgoSearch.entity().getSourcePort(), SearchCriteria.Op.EQ); +// FWByIPPortAlgoSearch.and("algorithm", FWByIPPortAlgoSearch.entity().getAlgorithm(), SearchCriteria.Op.EQ); +// FWByIPPortAlgoSearch.done(); +// +// FWByPrivateIPSearch = createSearchBuilder(); +// FWByPrivateIPSearch.and("privateIpAddress", FWByPrivateIPSearch.entity().getDestinationIpAddress(), SearchCriteria.Op.EQ); +// FWByPrivateIPSearch.done(); +// +// RulesExcludingPubIpPort = createSearchBuilder(); +// RulesExcludingPubIpPort.and("publicIpAddress", RulesExcludingPubIpPort.entity().getDestinationIpAddress(), SearchCriteria.Op.EQ); +// RulesExcludingPubIpPort.and("groupId", RulesExcludingPubIpPort.entity().getGroupId(), SearchCriteria.Op.NEQ); +// RulesExcludingPubIpPort.and("forwarding", RulesExcludingPubIpPort.entity().isForwarding(), SearchCriteria.Op.EQ); +// RulesExcludingPubIpPort.done(); +// +// FWByGroupId = createSearchBuilder(); +// FWByGroupId.and("groupId", FWByGroupId.entity().getGroupId(), SearchCriteria.Op.EQ); +// FWByGroupId.and("forwarding", FWByGroupId.entity().isForwarding(), SearchCriteria.Op.EQ); +// FWByGroupId.done(); +// +// FWByGroupAndPrivateIp = createSearchBuilder(); +// FWByGroupAndPrivateIp.and("groupId", FWByGroupAndPrivateIp.entity().getGroupId(), SearchCriteria.Op.EQ); +// FWByGroupAndPrivateIp.and("privateIpAddress", FWByGroupAndPrivateIp.entity().getDestinationIpAddress(), SearchCriteria.Op.EQ); +// FWByGroupAndPrivateIp.and("forwarding", FWByGroupAndPrivateIp.entity().isForwarding(), SearchCriteria.Op.EQ); +// FWByGroupAndPrivateIp.done(); +// +// FWByPrivateIpPrivatePortPublicIpPublicPortSearch = createSearchBuilder(); +// FWByPrivateIpPrivatePortPublicIpPublicPortSearch.and("publicIpAddress", FWByPrivateIpPrivatePortPublicIpPublicPortSearch.entity().getSourceIpAddress(), SearchCriteria.Op.EQ); +// FWByPrivateIpPrivatePortPublicIpPublicPortSearch.and("privateIpAddress", FWByPrivateIpPrivatePortPublicIpPublicPortSearch.entity().getDestinationIpAddress(), SearchCriteria.Op.EQ); +// FWByPrivateIpPrivatePortPublicIpPublicPortSearch.and("privatePort", FWByPrivateIpPrivatePortPublicIpPublicPortSearch.entity().getDestinationPort(), SearchCriteria.Op.NULL); +// FWByPrivateIpPrivatePortPublicIpPublicPortSearch.and("publicPort", FWByPrivateIpPrivatePortPublicIpPublicPortSearch.entity().getSourcePort(), SearchCriteria.Op.NULL); +// FWByPrivateIpPrivatePortPublicIpPublicPortSearch.done(); +// +// OneToOneNATSearch = createSearchBuilder(); +// OneToOneNATSearch.and("publicIpAddress", OneToOneNATSearch.entity().getSourceIpAddress(), SearchCriteria.Op.EQ); +// OneToOneNATSearch.and("protocol", OneToOneNATSearch.entity().getProtocol(), SearchCriteria.Op.EQ); +// OneToOneNATSearch.done(); +// +// FWByIpForLB = createSearchBuilder(); +// FWByIpForLB.and("publicIpAddress", FWByIpForLB.entity().getSourceIpAddress(), SearchCriteria.Op.EQ); +// FWByIpForLB.and("groupId", FWByIpForLB.entity().getGroupId(), SearchCriteria.Op.NNULL); +// FWByIpForLB.and("forwarding", FWByIpForLB.entity().isForwarding(), SearchCriteria.Op.EQ); +// FWByIpForLB.done(); +// +// return true; +// } +// +// protected String buildSelectByUserIdSql() { +// StringBuilder sql = createPartialSelectSql(null, true); +// sql.insert(sql.length() - 6, ", user_ip_address "); +// sql.append("ip_forwarding.public_ip_address = user_ip_address.public_ip_address AND user_ip_address.account_id = ?"); +// +// return sql.toString(); +// } +// +// protected String buildSelectByUserIdAndDatacenterIdSql() { +// return "SELECT i.id, i.group_id, i.public_ip_address, i.public_port, i.private_ip_address, i.private_port, i.enabled, i.protocol, i.forwarding, i.algorithm FROM ip_forwarding i, user_ip_address u WHERE i.public_ip_address=u.public_ip_address AND u.account_id=? AND u.data_center_id=?"; +// } +// +// protected String buildSelectByUserIdAndDatacenterIdForLBSql() { +// return "SELECT i.id, i.group_id, i.public_ip_address, i.public_port, i.private_ip_address, i.private_port, i.enabled, i.protocol, i.forwarding, i.algorithm FROM ip_forwarding i, user_ip_address u WHERE i.public_ip_address=u.public_ip_address AND u.account_id=? AND u.data_center_id=? AND i.group_id is not NULL"; +// } +// +// public List listIPForwarding(String publicIPAddress, boolean forwarding) { +// SearchCriteria sc = FWByIPAndForwardingSearch.create(); +// sc.setParameters("publicIpAddress", publicIPAddress); +// sc.setParameters("forwarding", forwarding); +// return listBy(sc); +// } +// +// @Override +// public List listIPForwarding(long userId) { +// Transaction txn = Transaction.currentTxn(); +// List forwardings = new ArrayList(); +// PreparedStatement pstmt = null; +// try { +// pstmt = txn.prepareAutoCloseStatement(SELECT_IP_FORWARDINGS_BY_USERID_SQL); +// pstmt.setLong(1, userId); +// ResultSet rs = pstmt.executeQuery(); +// while (rs.next()) { +// forwardings.add(toEntityBean(rs, false)); +// } +// } catch (Exception e) { +// s_logger.warn(e); +// } +// return forwardings; +// } +// +// public List listIPForwarding(long userId, long dcId) { +// Transaction txn = Transaction.currentTxn(); +// List forwardings = new ArrayList(); +// PreparedStatement pstmt = null; +// try { +// pstmt = txn.prepareAutoCloseStatement(SELECT_IP_FORWARDINGS_BY_USERID_AND_DCID_SQL); +// pstmt.setLong(1, userId); +// pstmt.setLong(2, dcId); +// ResultSet rs = pstmt.executeQuery(); +// while (rs.next()) { +// forwardings.add(toEntityBean(rs, false)); +// } +// } catch (Exception e) { +// s_logger.warn(e); +// } +// return forwardings; +// } +// +// @Override +// public void deleteIPForwardingByPublicIpAddress(String ipAddress) { +// Transaction txn = Transaction.currentTxn(); +// PreparedStatement pstmt = null; +// try { +// pstmt = txn.prepareAutoCloseStatement(DELETE_IP_FORWARDING_BY_IPADDRESS_SQL); +// pstmt.setString(1, ipAddress); +// pstmt.executeUpdate(); +// } catch (Exception e) { +// s_logger.warn(e); +// } +// } +// +// @Override +// public void deleteIPForwardingByPublicIpAndPort(String ipAddress, String port) { +// Transaction txn = Transaction.currentTxn(); +// PreparedStatement pstmt = null; +// try { +// pstmt = txn.prepareAutoCloseStatement(DELETE_IP_FORWARDING_BY_IP_PORT_SQL); +// pstmt.setString(1, ipAddress); +// pstmt.setString(2, port); +// +// pstmt.executeUpdate(); +// } catch (Exception e) { +// s_logger.warn(e); +// } +// } +// +// @Override +// public List listIPForwarding(String publicIPAddress) { +// SearchCriteria sc = FWByIPSearch.create(); +// sc.setParameters("publicIpAddress", publicIPAddress); +// return listBy(sc); +// } +// +// @Override +// public List listIPForwardingForUpdate(String publicIPAddress) { +// SearchCriteria sc = FWByIPSearch.create(); +// sc.setParameters("publicIpAddress", publicIPAddress); +// return listBy(sc, null); +// } +// +// @Override +// public List listIPForwardingForUpdate(String publicIp, boolean fwding) { +// SearchCriteria sc = FWByIPAndForwardingSearch.create(); +// sc.setParameters("publicIpAddress", publicIp); +// sc.setParameters("forwarding", fwding); +// return search(sc, null); +// } +// +// @Override +// public List listIPForwardingForUpdate(String publicIp, +// String publicPort, String proto) { +// SearchCriteria sc = FWByIPPortProtoSearch.create(); +// sc.setParameters("publicIpAddress", publicIp); +// sc.setParameters("publicPort", publicPort); +// sc.setParameters("protocol", proto); +// return search(sc, null); +// } +// +// @Override +// public List listLoadBalanceRulesForUpdate(String publicIp, +// String publicPort, String algo) { +// SearchCriteria sc = FWByIPPortAlgoSearch.create(); +// sc.setParameters("publicIpAddress", publicIp); +// sc.setParameters("publicPort", publicPort); +// sc.setParameters("algorithm", algo); +// return listBy(sc, null); +// } +// +// @Override +// public List listIPForwarding(String publicIPAddress, +// String port, boolean forwarding) { +// SearchCriteria sc = FWByIPPortAndForwardingSearch.create(); +// sc.setParameters("publicIpAddress", publicIPAddress); +// sc.setParameters("publicPort", port); +// sc.setParameters("forwarding", forwarding); +// +// return listBy(sc); +// } +// +// @Override +// public void disableIPForwarding(String publicIPAddress) { +// Transaction txn = Transaction.currentTxn(); +// PreparedStatement pstmt = null; +// try { +// txn.start(); +// pstmt = txn.prepareAutoCloseStatement(DISABLE_IP_FORWARDING_BY_IPADDRESS_SQL); +// pstmt.setString(1, publicIPAddress); +// pstmt.executeUpdate(); +// txn.commit(); +// } catch (Exception e) { +// txn.rollback(); +// throw new CloudRuntimeException("DB Exception ", e); +// } +// } +// +// @Override +// public List listRulesExcludingPubIpPort(String publicIpAddress, long securityGroupId) { +// SearchCriteria sc = RulesExcludingPubIpPort.create(); +// sc.setParameters("publicIpAddress", publicIpAddress); +// sc.setParameters("groupId", securityGroupId); +// sc.setParameters("forwarding", false); +// return listBy(sc); +// } +// +// @Override +// public List listBySecurityGroupId(long securityGroupId) { +// SearchCriteria sc = FWByGroupId.create(); +// sc.setParameters("groupId", securityGroupId); +// sc.setParameters("forwarding", Boolean.TRUE); +// return listBy(sc); +// } +// +// @Override +// public List listForwardingByPubAndPrivIp(boolean forwarding, String publicIPAddress, String privateIp) { +// SearchCriteria sc = FWByIPAndForwardingSearch.create(); +// sc.setParameters("publicIpAddress", publicIPAddress); +// sc.setParameters("forwarding", forwarding); +// sc.addAnd("privateIpAddress", SearchCriteria.Op.EQ, privateIp); +// return listBy(sc); +// } +// +// @Override +// public List listByLoadBalancerId(long loadBalancerId) { +// SearchCriteria sc = FWByGroupId.create(); +// sc.setParameters("groupId", loadBalancerId); +// sc.setParameters("forwarding", Boolean.FALSE); +// return listBy(sc); +// } +// +// @Override +// public PortForwardingRuleVO findByGroupAndPrivateIp(long groupId, String privateIp, boolean forwarding) { +// SearchCriteria sc = FWByGroupAndPrivateIp.create(); +// sc.setParameters("groupId", groupId); +// sc.setParameters("privateIpAddress", privateIp); +// sc.setParameters("forwarding", forwarding); +// return findOneBy(sc); +// +// } +// +// @Override +// public List findByPublicIpPrivateIpForNatRule(String publicIp, String privateIp){ +// SearchCriteria sc = FWByPrivateIpPrivatePortPublicIpPublicPortSearch.create(); +// sc.setParameters("publicIpAddress", publicIp); +// sc.setParameters("privateIpAddress", privateIp); +// return listBy(sc); +// } +// +// @Override +// public List listByPrivateIp(String privateIp) { +// SearchCriteria sc = FWByPrivateIPSearch.create(); +// sc.setParameters("privateIpAddress", privateIp); +// return listBy(sc); +// } +// +// @Override +// public List listIPForwardingByPortAndProto(String publicIp, +// String publicPort, String proto) { +// SearchCriteria sc = FWByIPPortProtoSearch.create(); +// sc.setParameters("publicIpAddress", publicIp); +// sc.setParameters("publicPort", publicPort); +// sc.setParameters("protocol", proto); +// return search(sc, null); +// } +// +// @Override +// public boolean isPublicIpOneToOneNATted(String publicIp) { +// SearchCriteria sc = OneToOneNATSearch.create(); +// sc.setParameters("publicIpAddress", publicIp); +// sc.setParameters("protocol", NetUtils.NAT_PROTO); +// List rules = search(sc, null); +// if (rules.size() != 1) +// return false; +// return rules.get(1).getProtocol().equalsIgnoreCase(NetUtils.NAT_PROTO); +// } +// +// @Override +// public List listIpForwardingRulesForLoadBalancers( +// String publicIp) { +// SearchCriteria sc = FWByIpForLB.create(); +// sc.setParameters("publicIpAddress", publicIp); +// sc.setParameters("forwarding", false); +// return search(sc, null); +// } +// +// @Override +// public List listIPForwardingForLB(long userId, long dcId) { +// Transaction txn = Transaction.currentTxn(); +// List forwardings = new ArrayList(); +// PreparedStatement pstmt = null; +// try { +// pstmt = txn.prepareAutoCloseStatement(SELECT_LB_FORWARDINGS_BY_USERID_AND_DCID_SQL); +// pstmt.setLong(1, userId); +// pstmt.setLong(2, dcId); +// ResultSet rs = pstmt.executeQuery(); +// while (rs.next()) { +// forwardings.add(toEntityBean(rs, false)); +// } +// } catch (Exception e) { +// s_logger.warn(e); +// } +// return forwardings; +// } } diff --git a/server/src/com/cloud/network/dao/IPAddressDao.java b/server/src/com/cloud/network/dao/IPAddressDao.java index e87e9e3558a..73b1d45327c 100644 --- a/server/src/com/cloud/network/dao/IPAddressDao.java +++ b/server/src/com/cloud/network/dao/IPAddressDao.java @@ -18,8 +18,8 @@ package com.cloud.network.dao; -import java.util.List; - +import java.util.List; + import com.cloud.network.IPAddressVO; import com.cloud.utils.db.GenericDao; @@ -32,7 +32,7 @@ public interface IPAddressDao extends GenericDao { * @param sourceNat is it for source nat? * @return public ip address */ - public String assignIpAddress(long accountId, long domainId, long vlanDbId, boolean sourceNat); + public IPAddressVO assignIpAddress(long accountId, long domainId, long vlanDbId, boolean sourceNat); public void unassignIpAddress(String ipAddress); diff --git a/server/src/com/cloud/network/dao/IPAddressDaoImpl.java b/server/src/com/cloud/network/dao/IPAddressDaoImpl.java index 3c85cc6dc00..2560eb36d99 100644 --- a/server/src/com/cloud/network/dao/IPAddressDaoImpl.java +++ b/server/src/com/cloud/network/dao/IPAddressDaoImpl.java @@ -16,8 +16,8 @@ * */ -package com.cloud.network.dao; - +package com.cloud.network.dao; + import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; @@ -29,213 +29,207 @@ import javax.ejb.Local; import org.apache.log4j.Logger; import com.cloud.network.IPAddressVO; +import com.cloud.network.IpAddress.State; import com.cloud.utils.db.DB; +import com.cloud.utils.db.Filter; import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.GenericSearchBuilder; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; +import com.cloud.utils.db.SearchCriteria.Func; +import com.cloud.utils.db.SearchCriteria.Op; import com.cloud.utils.db.Transaction; - -@Local(value={IPAddressDao.class}) -public class IPAddressDaoImpl extends GenericDaoBase implements IPAddressDao { - private static final Logger s_logger = Logger.getLogger(IPAddressDaoImpl.class); - - protected SearchBuilder DcIpSearch; - protected SearchBuilder VlanDbIdSearchUnallocated; - protected SearchBuilder AccountSearch; - - // make it public for JUnit test - public IPAddressDaoImpl() { - DcIpSearch = createSearchBuilder(); - DcIpSearch.and("dataCenterId", DcIpSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ); - DcIpSearch.and("ipAddress", DcIpSearch.entity().getAddress(), SearchCriteria.Op.EQ); - DcIpSearch.done(); - - VlanDbIdSearchUnallocated = createSearchBuilder(); - VlanDbIdSearchUnallocated.and("allocated", VlanDbIdSearchUnallocated.entity().getAllocated(), SearchCriteria.Op.NULL); - VlanDbIdSearchUnallocated.and("vlanDbId", VlanDbIdSearchUnallocated.entity().getVlanDbId(), SearchCriteria.Op.EQ); - //VlanDbIdSearchUnallocated.addRetrieve("ipAddress", VlanDbIdSearchUnallocated.entity().getAddress()); - VlanDbIdSearchUnallocated.done(); - - AccountSearch = createSearchBuilder(); - AccountSearch.and("accountId", AccountSearch.entity().getAccountId(), SearchCriteria.Op.EQ); - AccountSearch.done(); - } - - public boolean mark(long dcId, String ip) { - SearchCriteria sc = DcIpSearch.create(); - sc.setParameters("dataCenterId", dcId); - sc.setParameters("ipAddress", ip); - - IPAddressVO vo = createForUpdate(); - vo.setAllocated(new Date()); - - return update(vo, sc) >= 1; - } +import com.cloud.utils.exception.CloudRuntimeException; +@Local(value = { IPAddressDao.class }) +@DB +public class IPAddressDaoImpl extends GenericDaoBase implements IPAddressDao { + private static final Logger s_logger = Logger.getLogger(IPAddressDaoImpl.class); + + protected final SearchBuilder AllFieldsSearch; + protected final SearchBuilder VlanDbIdSearchUnallocated; + protected final GenericSearchBuilder AllIpCount; + protected final GenericSearchBuilder AllocatedIpCount; + + // make it public for JUnit test + public IPAddressDaoImpl() { + AllFieldsSearch = createSearchBuilder(); + AllFieldsSearch.and("dataCenterId", AllFieldsSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ); + AllFieldsSearch.and("ipAddress", AllFieldsSearch.entity().getAddress(), SearchCriteria.Op.EQ); + AllFieldsSearch.and("vlan", AllFieldsSearch.entity().getVlanId(), Op.EQ); + AllFieldsSearch.and("accountId", AllFieldsSearch.entity().getAllocatedToAccountId(), Op.EQ); + AllFieldsSearch.and("sourceNat", AllFieldsSearch.entity().isSourceNat(), SearchCriteria.Op.EQ); + AllFieldsSearch.done(); + + VlanDbIdSearchUnallocated = createSearchBuilder(); + VlanDbIdSearchUnallocated.and("allocated", VlanDbIdSearchUnallocated.entity().getAllocatedTime(), SearchCriteria.Op.NULL); + VlanDbIdSearchUnallocated.and("vlanDbId", VlanDbIdSearchUnallocated.entity().getVlanId(), SearchCriteria.Op.EQ); + VlanDbIdSearchUnallocated.done(); + + AllIpCount = createSearchBuilder(Integer.class); + AllIpCount.select(null, Func.COUNT, AllIpCount.entity().getAddress()); + AllIpCount.and("dc", AllIpCount.entity().getDataCenterId(), Op.EQ); + AllIpCount.and("vlan", AllIpCount.entity().getVlanId(), Op.EQ); + AllIpCount.done(); + + AllocatedIpCount = createSearchBuilder(Integer.class); + AllocatedIpCount.select(null, Func.COUNT, AllocatedIpCount.entity().getAddress()); + AllocatedIpCount.and("dc", AllocatedIpCount.entity().getDataCenterId(), Op.EQ); + AllocatedIpCount.and("vlan", AllocatedIpCount.entity().getVlanId(), Op.EQ); + AllocatedIpCount.and("allocated", AllocatedIpCount.entity().getAllocatedTime(), Op.NNULL); + AllocatedIpCount.done(); + } + + @Override + public boolean mark(long dcId, String ip) { + SearchCriteria sc = AllFieldsSearch.create(); + sc.setParameters("dataCenterId", dcId); + sc.setParameters("ipAddress", ip); + + IPAddressVO vo = createForUpdate(); + vo.setAllocatedTime(new Date()); + vo.setState(State.Allocated); + + return update(vo, sc) >= 1; + } + + @Override @DB public List assignAcccountSpecificIps(long accountId, long domainId, Long vlanDbId, boolean sourceNat) { - - SearchBuilder VlanDbIdSearch = createSearchBuilder(); - VlanDbIdSearch.and("vlanDbId", VlanDbIdSearch.entity().getVlanDbId(), SearchCriteria.Op.EQ); - VlanDbIdSearch.and("sourceNat", VlanDbIdSearch.entity().getSourceNat(), SearchCriteria.Op.EQ); - VlanDbIdSearch.done(); - Transaction txn = Transaction.currentTxn(); - try { - txn.start(); - SearchCriteria sc = VlanDbIdSearch.create(); - sc.setParameters("vlanDbId", vlanDbId); - sc.setParameters("sourceNat", sourceNat); - - List ipList = this.lockRows(sc, null, true); - List ipStringList = new ArrayList(); - - for(IPAddressVO ip:ipList){ - - ip.setAccountId(accountId); - ip.setAllocated(new Date()); - ip.setDomainId(domainId); - ip.setSourceNat(sourceNat); - - if (!update(ip.getAddress(), ip)) { - s_logger.debug("Unable to retrieve ip address " + ip.getAddress()); - return null; - } - ipStringList.add(ip.getAddress()); - } - txn.commit(); - return ipStringList; - } catch (Exception e) { - s_logger.warn("Unable to assign IP", e); - } - return null; - - } - public void setIpAsSourceNat(String ipAddr){ + Transaction txn = Transaction.currentTxn(); + txn.start(); + SearchCriteria sc = AllFieldsSearch.create(); + sc.setParameters("vlan", vlanDbId); + sc.setParameters("sourceNat", sourceNat); - IPAddressVO ip = createForUpdate(ipAddr); - ip.setSourceNat(true); - s_logger.debug("Setting " + ipAddr + " as source Nat "); - update(ipAddr, ip); - } - - @Override - public String assignIpAddress(long accountId, long domainId, long vlanDbId, boolean sourceNat) { - - Transaction txn = Transaction.currentTxn(); - try { - txn.start(); - SearchCriteria sc = VlanDbIdSearchUnallocated.create(); - sc.setParameters("vlanDbId", vlanDbId); - - IPAddressVO ip = this.lockOneRandomRow(sc, true); - if(ip != null) { - ip.setAccountId(accountId); - ip.setAllocated(new Date()); - ip.setDomainId(domainId); - ip.setSourceNat(sourceNat); - - if (!update(ip.getAddress(), ip)) { - s_logger.debug("Unable to retrieve any ip addresses"); - return null; - } - - txn.commit(); - return ip.getAddress(); - } else { - txn.rollback(); - //we do not log this as an error now, as there can be multiple vlans across which we iterate - s_logger.warn("Unable to find an available IP address with related vlan, vlanDbId: " + vlanDbId); - } - } catch (Exception e) { - s_logger.warn("Unable to assign IP", e); - } - return null; - } - - @Override - public void unassignIpAddress(String ipAddress) { - IPAddressVO address = createForUpdate(); - address.setAccountId(null); - address.setDomainId(null); - address.setAllocated(null); - address.setSourceNat(false); - update(ipAddress, address); - } - - @Override - public void unassignIpAsSourceNat(String ipAddress) { - IPAddressVO address = createForUpdate(); - address.setSourceNat(false); - update(ipAddress, address); - } - - @Override - public List listByAccount(long accountId) { - SearchCriteria sc = AccountSearch.create(); - sc.setParameters("accountId", accountId); - return listIncludingRemovedBy(sc); - } - - public List listByDcIdIpAddress(long dcId, String ipAddress) { - SearchCriteria sc = DcIpSearch.create(); - sc.setParameters("dataCenterId", dcId); - sc.setParameters("ipAddress", ipAddress); - return listIncludingRemovedBy(sc); - } - - @Override @DB - public int countIPs(long dcId, long vlanDbId, boolean onlyCountAllocated) { - Transaction txn = Transaction.currentTxn(); - PreparedStatement pstmt = null; - int ipCount = 0; - try { - String sql = "SELECT count(*) from `cloud`.`user_ip_address` where data_center_id = " + dcId; - - if (vlanDbId != -1) { - sql += " AND vlan_db_id = " + vlanDbId; - } - - if (onlyCountAllocated) { - sql += " AND allocated IS NOT NULL"; - } - - pstmt = txn.prepareAutoCloseStatement(sql); - ResultSet rs = pstmt.executeQuery(); - - if (rs.next()) { - ipCount = rs.getInt(1); - } - - } catch (Exception e) { - s_logger.warn("Exception counting IP addresses", e); + List ipList = lockRows(sc, null, true); + List ipStringList = new ArrayList(); + + for (IPAddressVO ip : ipList) { + + ip.setAllocatedToAccountId(accountId); + ip.setAllocatedTime(new Date()); + ip.setAllocatedInDomainId(domainId); + ip.setSourceNat(sourceNat); + ip.setState(State.Allocated); + + if (!update(ip.getAddress(), ip)) { + throw new CloudRuntimeException("Unable to update a locked ip address " + ip.getAddress()); + } + ipStringList.add(ip.getAddress()); } - - return ipCount; - } - - @Override @DB - public int countIPs(long dcId, Long accountId, String vlanId, String vlanGateway, String vlanNetmask) { - Transaction txn = Transaction.currentTxn(); - int ipCount = 0; - try { - String sql = "SELECT count(*) FROM user_ip_address u INNER JOIN vlan v on (u.vlan_db_id = v.id AND v.data_center_id = ? AND v.vlan_id = ? AND v.vlan_gateway = ? AND v.vlan_netmask = ? AND u.account_id = ?)"; - - - PreparedStatement pstmt = txn.prepareAutoCloseStatement(sql); - pstmt.setLong(1, dcId); - pstmt.setString(2, vlanId); - pstmt.setString(3, vlanGateway); - pstmt.setString(4, vlanNetmask); - pstmt.setLong(5, accountId); - ResultSet rs = pstmt.executeQuery(); - - if (rs.next()) { - ipCount = rs.getInt(1); - } - } catch (Exception e) { - s_logger.warn("Exception counting IP addresses", e); - } - - return ipCount; - } -} + txn.commit(); + return ipStringList; + } + + @Override + public void setIpAsSourceNat(String ipAddr) { + + IPAddressVO ip = createForUpdate(ipAddr); + ip.setSourceNat(true); + s_logger.debug("Setting " + ipAddr + " as source Nat "); + update(ipAddr, ip); + } + + @Override + @DB + public IPAddressVO assignIpAddress(long accountId, long domainId, long vlanDbId, boolean sourceNat) { + Transaction txn = Transaction.currentTxn(); + txn.start(); + + SearchCriteria sc = VlanDbIdSearchUnallocated.create(); + sc.setParameters("vlanDbId", vlanDbId); + + Filter filter = new Filter(IPAddressVO.class, "vlanId", true, 0l, 1l); + + List ips = this.lockRows(sc, filter, true); + if (ips.size() == 0) { + s_logger.info("Unable to get an ip address in " + vlanDbId); + return null; + } + + IPAddressVO ip = ips.get(0); + + ip.setAllocatedToAccountId(accountId); + ip.setAllocatedTime(new Date()); + ip.setAllocatedInDomainId(domainId); + ip.setSourceNat(sourceNat); + ip.setState(State.Allocated); + + if (!update(ip.getAddress(), ip)) { + throw new CloudRuntimeException("How can I lock the row but can't update it: " + ip.getAddress()); + } + + txn.commit(); + return ip; + } + + @Override + public void unassignIpAddress(String ipAddress) { + IPAddressVO address = createForUpdate(); + address.setAllocatedToAccountId(null); + address.setAllocatedInDomainId(null); + address.setAllocatedTime(null); + address.setSourceNat(false); + address.setOneToOneNat(false); + address.setState(State.Free); + update(ipAddress, address); + } + + @Override + public void unassignIpAsSourceNat(String ipAddress) { + IPAddressVO address = createForUpdate(); + address.setSourceNat(false); + update(ipAddress, address); + } + + @Override + public List listByAccount(long accountId) { + SearchCriteria sc = AllFieldsSearch.create(); + sc.setParameters("accountId", accountId); + return listIncludingRemovedBy(sc); + } + + @Override + public List listByDcIdIpAddress(long dcId, String ipAddress) { + SearchCriteria sc = AllFieldsSearch.create(); + sc.setParameters("dataCenterId", dcId); + sc.setParameters("ipAddress", ipAddress); + return listIncludingRemovedBy(sc); + } + + @Override + public int countIPs(long dcId, long vlanId, boolean onlyCountAllocated) { + SearchCriteria sc = onlyCountAllocated ? AllocatedIpCount.create() : AllIpCount.create(); + sc.setParameters("dc", dcId); + sc.setParameters("vlan", vlanId); + + return customSearch(sc, null).get(0); + } + + @Override + @DB + public int countIPs(long dcId, Long accountId, String vlanId, String vlanGateway, String vlanNetmask) { + Transaction txn = Transaction.currentTxn(); + int ipCount = 0; + try { + String sql = "SELECT count(*) FROM user_ip_address u INNER JOIN vlan v on (u.vlan_db_id = v.id AND v.data_center_id = ? AND v.vlan_id = ? AND v.vlan_gateway = ? AND v.vlan_netmask = ? AND u.account_id = ?)"; + + PreparedStatement pstmt = txn.prepareAutoCloseStatement(sql); + pstmt.setLong(1, dcId); + pstmt.setString(2, vlanId); + pstmt.setString(3, vlanGateway); + pstmt.setString(4, vlanNetmask); + pstmt.setLong(5, accountId); + ResultSet rs = pstmt.executeQuery(); + + if (rs.next()) { + ipCount = rs.getInt(1); + } + } catch (Exception e) { + s_logger.warn("Exception counting IP addresses", e); + } + + return ipCount; + } +} diff --git a/server/src/com/cloud/network/dao/LoadBalancerDaoImpl.java b/server/src/com/cloud/network/dao/LoadBalancerDaoImpl.java index a9dcda58557..f845d2c9c88 100644 --- a/server/src/com/cloud/network/dao/LoadBalancerDaoImpl.java +++ b/server/src/com/cloud/network/dao/LoadBalancerDaoImpl.java @@ -50,12 +50,12 @@ public class LoadBalancerDaoImpl extends GenericDaoBase im protected LoadBalancerDaoImpl() { ListByIp = createSearchBuilder(); - ListByIp.and("ipAddress", ListByIp.entity().getIpAddress(), SearchCriteria.Op.EQ); + ListByIp.and("ipAddress", ListByIp.entity().getSourceIpAddress(), SearchCriteria.Op.EQ); ListByIp.done(); IpAndPublicPortSearch = createSearchBuilder(); - IpAndPublicPortSearch.and("ipAddress", IpAndPublicPortSearch.entity().getIpAddress(), SearchCriteria.Op.EQ); - IpAndPublicPortSearch.and("publicPort", IpAndPublicPortSearch.entity().getPublicPort(), SearchCriteria.Op.EQ); + IpAndPublicPortSearch.and("ipAddress", IpAndPublicPortSearch.entity().getSourceIpAddress(), SearchCriteria.Op.EQ); + IpAndPublicPortSearch.and("publicPort", IpAndPublicPortSearch.entity().getSourcePortStart(), SearchCriteria.Op.EQ); IpAndPublicPortSearch.done(); AccountAndNameSearch = createSearchBuilder(); diff --git a/server/src/com/cloud/network/dao/LoadBalancerVMMapDao.java b/server/src/com/cloud/network/dao/LoadBalancerVMMapDao.java index 20db7c322b4..0f1ae1544f7 100644 --- a/server/src/com/cloud/network/dao/LoadBalancerVMMapDao.java +++ b/server/src/com/cloud/network/dao/LoadBalancerVMMapDao.java @@ -18,8 +18,8 @@ package com.cloud.network.dao; -import java.util.List; - +import java.util.List; + import com.cloud.network.LoadBalancerVMMapVO; import com.cloud.utils.db.GenericDao; diff --git a/server/src/com/cloud/network/dao/NetworkDao.java b/server/src/com/cloud/network/dao/NetworkDao.java index a6f92858ed3..eba82e475b6 100644 --- a/server/src/com/cloud/network/dao/NetworkDao.java +++ b/server/src/com/cloud/network/dao/NetworkDao.java @@ -28,8 +28,8 @@ public interface NetworkDao extends GenericDao { List listBy(long accountId); List listBy(long accountId, long offeringId, long dataCenterId); @Override - NetworkVO persist(NetworkVO config); - void addAccountToNetworkConfiguration(long configId, long accountId); + NetworkVO persist(NetworkVO network); + void addAccountToNetworkConfiguration(long networkId, long accountId); SearchBuilder createSearchBuilderForAccount(); List getNetworkConfigurationsForOffering(long offeringId, long dataCenterId, long accountId); List getRelatedNetworkConfigurations(long related); @@ -40,4 +40,6 @@ public interface NetworkDao extends GenericDao { * @return mac address if there is one. null if not. */ String getNextAvailableMacAddress(long networkConfigId); + + List listBy(long accountId, long networkId); } diff --git a/server/src/com/cloud/network/dao/NetworkDaoImpl.java b/server/src/com/cloud/network/dao/NetworkDaoImpl.java index 1373629b5e4..fdb6214dc29 100644 --- a/server/src/com/cloud/network/dao/NetworkDaoImpl.java +++ b/server/src/com/cloud/network/dao/NetworkDaoImpl.java @@ -25,6 +25,7 @@ import java.util.Random; import javax.ejb.Local; import javax.persistence.TableGenerator; +import com.cloud.domain.DomainVO; import com.cloud.network.NetworkAccountDaoImpl; import com.cloud.network.NetworkAccountVO; import com.cloud.network.NetworkVO; @@ -49,6 +50,7 @@ public class NetworkDaoImpl extends GenericDaoBase implements N final SearchBuilder OfferingSearch; final SearchBuilder RelatedConfigSearch; final SearchBuilder RelatedConfigsSearch; + final SearchBuilder AccountNetworkSearch; NetworkAccountDaoImpl _accountsDao = new NetworkAccountDaoImpl(); final TableGenerator _tgMacAddress; @@ -90,6 +92,14 @@ public class NetworkDaoImpl extends GenericDaoBase implements N RelatedConfigsSearch.and("related", RelatedConfigsSearch.entity().getRelated(), SearchCriteria.Op.EQ); RelatedConfigsSearch.done(); + + AccountNetworkSearch = createSearchBuilder(); + AccountNetworkSearch.and("networkId", AccountNetworkSearch.entity().getId(), SearchCriteria.Op.EQ); + SearchBuilder mapJoin = _accountsDao.createSearchBuilder(); + mapJoin.and("accountId", mapJoin.entity().getAccountId(), SearchCriteria.Op.EQ); + AccountNetworkSearch.join("networkSearch", mapJoin, AccountNetworkSearch.entity().getId(), mapJoin.entity().getNetworkId(), JoinBuilder.JoinType.INNER); + AccountNetworkSearch.done(); + _tgMacAddress = _tgs.get("macAddress"); } @@ -178,4 +188,12 @@ public class NetworkDaoImpl extends GenericDaoBase implements N seq = seq | _prefix | ((_rand.nextInt(Short.MAX_VALUE) << 16) & 0x00000000ffff0000l); return NetUtils.long2Mac(seq); } + + @Override + public List listBy(long accountId, long networkId) { + SearchCriteria sc = AccountNetworkSearch.create(); + sc.setParameters("networkId", networkId); + sc.setJoinParameters("networkSearch", "accountId", accountId); + return listBy(sc); + } } diff --git a/server/src/com/cloud/network/element/DomainRouterElement.java b/server/src/com/cloud/network/element/DomainRouterElement.java index 9acd82e6b09..aa462f6564a 100644 --- a/server/src/com/cloud/network/element/DomainRouterElement.java +++ b/server/src/com/cloud/network/element/DomainRouterElement.java @@ -17,6 +17,8 @@ */ package com.cloud.network.element; +import java.util.List; + import javax.ejb.Local; import org.apache.log4j.Logger; @@ -26,16 +28,18 @@ import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InsufficientNetworkCapacityException; import com.cloud.exception.ResourceUnavailableException; -import com.cloud.network.Networks.TrafficType; import com.cloud.network.Network; import com.cloud.network.NetworkManager; +import com.cloud.network.Networks.TrafficType; import com.cloud.network.dao.NetworkDao; import com.cloud.network.router.DomainRouterManager; +import com.cloud.network.rules.FirewallRule; import com.cloud.offering.NetworkOffering; import com.cloud.offering.NetworkOffering.GuestIpType; import com.cloud.uservm.UserVm; import com.cloud.utils.component.AdapterBase; import com.cloud.utils.component.Inject; +import com.cloud.utils.net.Ip; import com.cloud.vm.DomainRouterVO; import com.cloud.vm.NicProfile; import com.cloud.vm.ReservationContext; @@ -60,7 +64,7 @@ public class DomainRouterElement extends AdapterBase implements NetworkElement { @Override public boolean implement(Network guestConfig, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws InsufficientCapacityException, ResourceUnavailableException, ConcurrentOperationException { - if (offering.getGuestIpType() != GuestIpType.Virtualized) { + if (offering.getGuestIpType() != GuestIpType.Virtual) { s_logger.trace("Not handling guest ip type = " + offering.getGuestIpType()); return false; } @@ -114,17 +118,25 @@ public class DomainRouterElement extends AdapterBase implements NetworkElement { return _routerMgr.stopRouter(router.getId(), 1); } - @Override - public boolean addRule() { - return false; - } - - @Override - public boolean revokeRule() { - return false; - } - protected DomainRouterElement() { super(); } + + @Override + public boolean applyRules(Network config, List rules) throws ResourceUnavailableException { + + return false; + } + + @Override + public boolean associate(Network network, Ip ipAddress) throws ResourceUnavailableException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean disassociate(Network network, Ip ipAddress) throws ResourceUnavailableException { + // TODO Auto-generated method stub + return false; + } } diff --git a/core/src/com/cloud/agent/api/routing/RoutingCommand.java b/server/src/com/cloud/network/lb/LoadBalancingRulesManager.java similarity index 80% rename from core/src/com/cloud/agent/api/routing/RoutingCommand.java rename to server/src/com/cloud/network/lb/LoadBalancingRulesManager.java index 36cc89e58dc..db77dd2d9b9 100644 --- a/core/src/com/cloud/agent/api/routing/RoutingCommand.java +++ b/server/src/com/cloud/network/lb/LoadBalancingRulesManager.java @@ -15,12 +15,10 @@ * along with this program. If not, see . * */ -package com.cloud.agent.api.routing; +package com.cloud.network.lb; -import com.cloud.agent.api.Command; +import com.cloud.utils.net.Ip; -public abstract class RoutingCommand extends Command { - protected RoutingCommand() { - super(); - } +public interface LoadBalancingRulesManager extends LoadBalancingRulesService { + boolean removeAllLoadBalanacers(Ip ip); } diff --git a/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java b/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java new file mode 100644 index 00000000000..3292eb55070 --- /dev/null +++ b/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java @@ -0,0 +1,1194 @@ +/** + * 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.security.InvalidParameterException; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.ejb.Local; +import javax.naming.ConfigurationException; + +import org.apache.log4j.Logger; + +import com.cloud.api.commands.ListLoadBalancerRuleInstancesCmd; +import com.cloud.api.commands.ListLoadBalancerRulesCmd; +import com.cloud.api.commands.UpdateLoadBalancerRuleCmd; +import com.cloud.dc.dao.VlanDao; +import com.cloud.event.EventTypes; +import com.cloud.event.EventVO; +import com.cloud.event.dao.EventDao; +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.exception.NetworkRuleConflictException; +import com.cloud.exception.PermissionDeniedException; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.network.IPAddressVO; +import com.cloud.network.LoadBalancerVMMapVO; +import com.cloud.network.LoadBalancerVO; +import com.cloud.network.NetworkManager; +import com.cloud.network.dao.FirewallRulesDao; +import com.cloud.network.dao.IPAddressDao; +import com.cloud.network.dao.LoadBalancerDao; +import com.cloud.network.dao.LoadBalancerVMMapDao; +import com.cloud.network.rules.FirewallRule; +import com.cloud.network.rules.LoadBalancer; +import com.cloud.network.rules.RulesManager; +import com.cloud.user.AccountManager; +import com.cloud.user.UserContext; +import com.cloud.uservm.UserVm; +import com.cloud.utils.component.Inject; +import com.cloud.utils.component.Manager; +import com.cloud.utils.db.DB; +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.Nic; +import com.cloud.vm.State; +import com.cloud.vm.UserVmVO; +import com.cloud.vm.dao.UserVmDao; + +@Local(value = { LoadBalancingRulesManager.class, LoadBalancingRulesService.class }) +public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesManager, LoadBalancingRulesService, Manager { + private static final Logger s_logger = Logger.getLogger(LoadBalancingRulesManagerImpl.class); + + String _name; + + @Inject + NetworkManager _networkMgr; + @Inject + RulesManager _rulesMgr; + @Inject + AccountManager _accountMgr; + @Inject + IPAddressDao _ipAddressDao; + @Inject + FirewallRulesDao _rulesDao; + @Inject + LoadBalancerDao _lbDao; + @Inject + VlanDao _vlanDao; + @Inject + EventDao _eventDao; + @Inject + LoadBalancerVMMapDao _lb2VmMapDao; + @Inject UserVmDao _vmDao; + + @Override @DB + public boolean assignToLoadBalancer(long loadBalancerId, List instanceIds) { + UserContext caller = UserContext.current(); + + LoadBalancerVO loadBalancer = _lbDao.findById(loadBalancerId); + if (loadBalancer == null) { + throw new InvalidParameterValueException("Failed to assign to load balancer " + loadBalancerId + ", the load balancer was not found."); + } + + _accountMgr.checkAccess(caller.getAccount(), loadBalancer); + + List mappedInstances = _lb2VmMapDao.listByLoadBalancerId(loadBalancerId, false); + Set mappedInstanceIds = new HashSet(); + for (LoadBalancerVMMapVO mappedInstance : mappedInstances) { + mappedInstanceIds.add(Long.valueOf(mappedInstance.getInstanceId())); + } + + List vmsToAdd = new ArrayList(); + + for (Long instanceId : instanceIds) { + if (mappedInstanceIds.contains(instanceId)) { + s_logger.debug("VM " + instanceId + " is already mapped to load balancer."); + continue; + } + + UserVm vm = _vmDao.findById(instanceId); + if (vm == null || vm.getState() == State.Destroyed || vm.getState() == State.Expunging) { + throw new InvalidParameterValueException("Invalid instance id: " + instanceId); + } + + _accountMgr.checkAccess(caller.getAccount(), vm); + + if (vm.getAccountId() != loadBalancer.getAccountId()) { + throw new PermissionDeniedException("Cannot add virtual machines that do not belong to the same owner."); + } + + // Let's check to make sure the vm has a nic in the same network as the load balancing rule. + List nics = _networkMgr.getNics(vm); + Nic nicInSameNetwork = null; + for (Nic nic : nics) { + if (nic.getNetworkId() == loadBalancer.getNetworkId()) { + nicInSameNetwork = nic; + break; + } + } + + if (nicInSameNetwork == null) { + throw new InvalidParameterValueException("VM " + instanceId + " cannot be added because it doesn't belong in the same network."); + } + + if (s_logger.isDebugEnabled()) { + s_logger.debug("Adding " + vm + " to the load balancer pool"); + } + vmsToAdd.add(vm); + } + + Transaction txn = Transaction.currentTxn(); + txn.start(); + for (UserVm vm : vmsToAdd) { + LoadBalancerVMMapVO map = new LoadBalancerVMMapVO(loadBalancer.getId(), vm.getId(), true); + map = _lb2VmMapDao.persist(map); + } + + txn.commit(); + return true; + } + + + @Override @DB + public boolean removeFromLoadBalancer(long loadBalancerId, List instanceIds) { + UserContext caller = UserContext.current(); + + LoadBalancerVO loadBalancer = _lbDao.findById(Long.valueOf(loadBalancerId)); + if (loadBalancer == null) { + throw new InvalidParameterException("Invalid load balancer value: " + loadBalancerId); + } + + _accountMgr.checkAccess(caller.getAccount(), loadBalancer); + + _lb2VmMapDao.remove(loadBalancerId, instanceIds, null); + return true; + } + + @Override + public boolean deleteLoadBalancerRule(long loadBalancerId, boolean apply) { + UserContext caller = UserContext.current(); + + LoadBalancerVO lb = _lbDao.findById(loadBalancerId); + if (lb == null) { + throw new InvalidParameterException("Invalid load balancer value: " + loadBalancerId); + } + + _accountMgr.checkAccess(caller.getAccount(), lb); + + lb.setState(FirewallRule.State.Revoke); + + if (apply) { + try { + applyLoadBalancerConfig(loadBalancerId); + } catch (ResourceUnavailableException e) { + s_logger.warn("Unable to apply the load balancer config because resource is unavaliable.", e); + return false; + } + } + return true; + } + + @Override + public LoadBalancer createLoadBalancerRule(LoadBalancer lb) throws NetworkRuleConflictException { + UserContext caller = UserContext.current(); + + Ip srcIp = lb.getSourceIpAddress(); + + // make sure ip address exists + IPAddressVO ipAddr = _ipAddressDao.findById(srcIp.addr()); + if (ipAddr == null || ipAddr.getAllocatedTime() == null || ipAddr.getAllocatedToAccountId() == null) { + throw new InvalidParameterValueException("Unable to create load balancer rule, invalid IP address " + srcIp); + } + + int srcPortStart = lb.getSourcePortStart(); + int srcPortEnd = lb.getSourcePortEnd(); + int defPortStart = lb.getDefaultPortStart(); + int defPortEnd = lb.getDefaultPortEnd(); + + if (!NetUtils.isValidPort(srcPortStart)) { + throw new InvalidParameterValueException("publicPort is an invalid value: " + srcPortStart); + } + if (!NetUtils.isValidPort(srcPortEnd)) { + throw new InvalidParameterValueException("Public port range is an invalid value: " + srcPortEnd); + } + if (srcPortStart > srcPortEnd) { + throw new InvalidParameterValueException("Public port range is an invalid value: " + srcPortStart + "-" + srcPortEnd); + } + if (!NetUtils.isValidPort(defPortStart)) { + throw new InvalidParameterValueException("privatePort is an invalid value: " + defPortStart); + } + if (!NetUtils.isValidPort(defPortEnd)) { + throw new InvalidParameterValueException("privatePort is an invalid value: " + defPortEnd); + } + if (defPortStart > defPortEnd) { + throw new InvalidParameterValueException("private port range is invalid: " + defPortStart + "-" + defPortEnd); + } + if ((lb.getAlgorithm() == null) || !NetUtils.isValidAlgorithm(lb.getAlgorithm())) { + throw new InvalidParameterValueException("Invalid algorithm: " + lb.getAlgorithm()); + } + + LoadBalancerVO newRule = new LoadBalancerVO(lb.getXid(), lb.getName(), lb.getDescription(), lb.getSourceIpAddress(), lb.getSourcePortEnd(), + lb.getDefaultPortStart(), lb.getAlgorithm(), lb.getNetworkId(), lb.getAccountId(), lb.getDomainId()); + + newRule = _lbDao.persist(newRule); + + boolean success = false; + try { + _rulesMgr.detectRulesConflict(newRule, ipAddr); + if (!_rulesDao.setStateToAdd(newRule)) { + throw new CloudRuntimeException("Unable to update the state to add for " + newRule); + } + + success = true; + return newRule; + } catch (Exception e) { + _lbDao.remove(newRule.getId()); + if (e instanceof NetworkRuleConflictException) { + throw (NetworkRuleConflictException) e; + } + + throw new CloudRuntimeException("Unable to add rule for " + newRule.getSourceIpAddress(), e); + } finally { + long userId = caller.getUserId(); + + EventVO event = new EventVO(); + event.setUserId(userId); + event.setAccountId(ipAddr.getAllocatedToAccountId()); + event.setType(EventTypes.EVENT_LOAD_BALANCER_CREATE); + + if (!success) { + event.setDescription("Failed to create load balancer " + lb.getName() + " on ip address " + srcIp + "[" + srcPortStart + "->" + + defPortStart + "]"); + event.setLevel(EventVO.LEVEL_ERROR); + } else { + event.setDescription("Successfully created load balancer " + lb.getName() + " on ip address " + srcIp + "[" + srcPortStart + "->" + + defPortStart + "]"); + String params = "id=" + newRule.getId() + "\ndcId=" + ipAddr.getDataCenterId(); + event.setParameters(params); + event.setLevel(EventVO.LEVEL_INFO); + } + _eventDao.persist(event); + } + } + + @Override + public boolean applyLoadBalancerConfig(long lbRuleId) throws ResourceUnavailableException { + return false; + } + + @Override + public boolean removeAllLoadBalanacers(Ip ip) { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean configure(String name, Map params) throws ConfigurationException { + _name = name; + return true; + } + + @Override + public boolean start() { + return true; + } + + @Override + public boolean stop() { + return true; + } + + @Override + public String getName() { + return _name; + } + + @Override + public LoadBalancer updateLoadBalancerRule(UpdateLoadBalancerRuleCmd cmd) { + // TODO Auto-generated method stub + return null; + } + +// @Override @DB +// public boolean removeFromLoadBalancer(RemoveFromLoadBalancerRuleCmd cmd) throws InvalidParameterValueException { +// +// Long userId = UserContext.current().getUserId(); +// Account account = UserContext.current().getAccount(); +// Long loadBalancerId = cmd.getId(); +// Long vmInstanceId = cmd.getVirtualMachineId(); +// List instanceIds = cmd.getVirtualMachineIds(); +// +// if ((vmInstanceId == null) && (instanceIds == null)) { +// throw new ServerApiException(BaseCmd.PARAM_ERROR, "No virtual machine id specified."); +// } +// +// // if a single instanceId was given, add it to the list so we can always just process the list if instanceIds +// if (instanceIds == null) { +// instanceIds = new ArrayList(); +// instanceIds.add(vmInstanceId); +// } +// +// if (userId == null) { +// userId = Long.valueOf(1); +// } +// +// LoadBalancerVO loadBalancer = _loadBalancerDao.findById(Long.valueOf(loadBalancerId)); +// +// if (loadBalancer == null) { +// throw new ServerApiException(BaseCmd.PARAM_ERROR, "Unable to find load balancer rule with id " + loadBalancerId); +// } else if (account != null) { +// if (!isAdmin(account.getType()) && (loadBalancer.getAccountId() != account.getId())) { +// throw new ServerApiException(BaseCmd.PARAM_ERROR, "Account " + account.getAccountName() + " does not own load balancer rule " + loadBalancer.getName() + +// " (id:" + loadBalancer.getId() + ")"); +// } else if (!_domainDao.isChildDomain(account.getDomainId(), loadBalancer.getDomainId())) { +// throw new ServerApiException(BaseCmd.PARAM_ERROR, "Invalid load balancer rule id (" + loadBalancer.getId() + ") given, unable to remove virtual machine instances."); +// } +// } +// +// Transaction txn = Transaction.currentTxn(); +// LoadBalancerVO loadBalancerLock = null; +// boolean success = true; +// try { +// +// IPAddressVO ipAddress = _ipAddressDao.findById(loadBalancer.getIpAddress()); +// if (ipAddress == null) { +// return false; +// } +// +// DomainRouterVO router = _routerMgr.getRouter(ipAddress.getAccountId(), ipAddress.getDataCenterId()); +// if (router == null) { +// return false; +// } +// +// txn.start(); +// for (Long instanceId : instanceIds) { +// UserVm userVm = _userVmDao.findById(instanceId); +// if (userVm == null) { +// s_logger.warn("Unable to find virtual machine with id " + instanceId); +// throw new InvalidParameterValueException("Unable to find virtual machine with id " + instanceId); +// } +// PortForwardingRuleVO fwRule = _rulesDao.findByGroupAndPrivateIp(loadBalancerId, userVm.getGuestIpAddress(), false); +// if (fwRule != null) { +// fwRule.setEnabled(false); +// _rulesDao.update(fwRule.getId(), fwRule); +// } +// } +// +// List allLbRules = new ArrayList(); +// IPAddressVO ipAddr = _ipAddressDao.findById(loadBalancer.getIpAddress()); +// List ipAddrs = listPublicIpAddressesInVirtualNetwork(loadBalancer.getAccountId(), ipAddr.getDataCenterId(), null); +// for (IPAddressVO ipv : ipAddrs) { +// List rules = _rulesDao.listIPForwarding(ipv.getAddress(), false); +// allLbRules.addAll(rules); +// } +// +// updateFirewallRules(loadBalancer.getIpAddress(), allLbRules, router); +// +// // firewall rules are updated, lock the load balancer as mappings are updated +// loadBalancerLock = _loadBalancerDao.acquireInLockTable(loadBalancerId); +// if (loadBalancerLock == null) { +// s_logger.warn("removeFromLoadBalancer: failed to lock load balancer " + loadBalancerId + ", deleting mappings anyway..."); +// } +// +// // remove all the loadBalancer->VM mappings +// _loadBalancerVMMapDao.remove(loadBalancerId, instanceIds, Boolean.FALSE); +// +// // Save and create the event +// String description; +// String type = EventTypes.EVENT_NET_RULE_DELETE; +// String level = EventVO.LEVEL_INFO; +// +// for (PortForwardingRuleVO updatedRule : allLbRules) { +// if (!updatedRule.isEnabled()) { +// _rulesDao.remove(updatedRule.getId()); +// +// description = "deleted load balancer rule [" + updatedRule.getSourceIpAddress() + ":" + updatedRule.getSourcePort() + "]->[" +// + updatedRule.getDestinationIpAddress() + ":" + updatedRule.getDestinationPort() + "]" + " " + updatedRule.getProtocol(); +// +// EventUtils.saveEvent(userId, loadBalancer.getAccountId(), level, type, description); +// } +// } +// txn.commit(); +// } catch (Exception ex) { +// s_logger.warn("Failed to delete load balancing rule with exception: ", ex); +// success = false; +// txn.rollback(); +// } finally { +// if (loadBalancerLock != null) { +// _loadBalancerDao.releaseFromLockTable(loadBalancerId); +// } +// } +// return success; +// } +// +// @Override @DB +// public boolean deleteLoadBalancerRule(DeleteLoadBalancerRuleCmd cmd) throws InvalidParameterValueException, PermissionDeniedException{ +// Long loadBalancerId = cmd.getId(); +// Long userId = UserContext.current().getUserId(); +// Account account = UserContext.current().getAccount(); +// +// ///verify input parameters +// LoadBalancerVO loadBalancer = _loadBalancerDao.findById(loadBalancerId); +// if (loadBalancer == null) { +// throw new InvalidParameterValueException ("Unable to find load balancer rule with id " + loadBalancerId); +// } +// +// if (account != null) { +// if (!isAdmin(account.getType())) { +// if (loadBalancer.getAccountId() != account.getId()) { +// throw new PermissionDeniedException("Account " + account.getAccountName() + " does not own load balancer rule " + loadBalancer.getName() + " (id:" + loadBalancerId + "), permission denied"); +// } +// } else if (!_domainDao.isChildDomain(account.getDomainId(), loadBalancer.getDomainId())) { +// throw new PermissionDeniedException("Unable to delete load balancer rule " + loadBalancer.getName() + " (id:" + loadBalancerId + "), permission denied."); +// } +// } +// +// if (userId == null) { +// userId = Long.valueOf(1); +// } +// +// Transaction txn = Transaction.currentTxn(); +// LoadBalancerVO loadBalancerLock = null; +// try { +// +// IPAddressVO ipAddress = _ipAddressDao.findById(loadBalancer.getIpAddress()); +// if (ipAddress == null) { +// return false; +// } +// +// DomainRouterVO router = _routerMgr.getRouter(ipAddress.getAccountId(), ipAddress.getDataCenterId()); +// List fwRules = _firewallRulesDao.listByLoadBalancerId(loadBalancerId); +// +// txn.start(); +// +// if ((fwRules != null) && !fwRules.isEmpty()) { +// for (PortForwardingRuleVO fwRule : fwRules) { +// fwRule.setEnabled(false); +// _firewallRulesDao.update(fwRule.getId(), fwRule); +// } +// +// List allLbRules = new ArrayList(); +// List ipAddrs = listPublicIpAddressesInVirtualNetwork(loadBalancer.getAccountId(), ipAddress.getDataCenterId(), null); +// for (IPAddressVO ipv : ipAddrs) { +// List rules = _firewallRulesDao.listIPForwarding(ipv.getAddress(), false); +// allLbRules.addAll(rules); +// } +// +// updateFirewallRules(loadBalancer.getIpAddress(), allLbRules, router); +// +// // firewall rules are updated, lock the load balancer as the mappings are updated +// loadBalancerLock = _loadBalancerDao.acquireInLockTable(loadBalancerId); +// if (loadBalancerLock == null) { +// s_logger.warn("deleteLoadBalancer: failed to lock load balancer " + loadBalancerId + ", deleting mappings anyway..."); +// } +// +// // remove all loadBalancer->VM mappings +// List lbVmMap = _loadBalancerVMMapDao.listByLoadBalancerId(loadBalancerId); +// if (lbVmMap != null && !lbVmMap.isEmpty()) { +// for (LoadBalancerVMMapVO lb : lbVmMap) { +// _loadBalancerVMMapDao.remove(lb.getId()); +// } +// } +// +// // Save and create the event +// String description; +// String type = EventTypes.EVENT_NET_RULE_DELETE; +// String ruleName = "load balancer"; +// String level = EventVO.LEVEL_INFO; +// Account accountOwner = _accountDao.findById(loadBalancer.getAccountId()); +// +// for (PortForwardingRuleVO updatedRule : fwRules) { +// _firewallRulesDao.remove(updatedRule.getId()); +// +// description = "deleted " + ruleName + " rule [" + updatedRule.getSourceIpAddress() + ":" + updatedRule.getSourcePort() + "]->[" +// + updatedRule.getDestinationIpAddress() + ":" + updatedRule.getDestinationPort() + "]" + " " + updatedRule.getProtocol(); +// +// EventUtils.saveEvent(userId, accountOwner.getId(), level, type, description); +// } +// } +// +// txn.commit(); +// } catch (Exception ex) { +// txn.rollback(); +// s_logger.error("Unexpected exception deleting load balancer " + loadBalancerId, ex); +// return false; +// } finally { +// if (loadBalancerLock != null) { +// _loadBalancerDao.releaseFromLockTable(loadBalancerId); +// } +// } +// +// boolean success = _loadBalancerDao.remove(loadBalancerId); +// +// // save off an event for removing the load balancer +// EventVO event = new EventVO(); +// event.setUserId(userId); +// event.setAccountId(loadBalancer.getAccountId()); +// event.setType(EventTypes.EVENT_LOAD_BALANCER_DELETE); +// if (success) { +// event.setLevel(EventVO.LEVEL_INFO); +// String params = "id="+loadBalancer.getId(); +// event.setParameters(params); +// event.setDescription("Successfully deleted load balancer " + loadBalancer.getName() + " (id:" + loadBalancer.getId() + ")"); +// } else { +// event.setLevel(EventVO.LEVEL_ERROR); +// event.setDescription("Failed to delete load balancer " + loadBalancer.getName() + " (id:" + loadBalancer.getId() + ")"); +// } +// _eventDao.persist(event); +// return success; +// } +// @Override @DB +// public boolean assignToLoadBalancer(AssignToLoadBalancerRuleCmd cmd) throws NetworkRuleConflictException { +// Long loadBalancerId = cmd.getLoadBalancerId(); +// Long instanceIdParam = cmd.getVirtualMachineId(); +// List instanceIds = cmd.getVirtualMachineIds(); +// +// if ((instanceIdParam == null) && (instanceIds == null)) { +// throw new InvalidParameterValueException("Unable to assign to load balancer " + loadBalancerId + ", no instance id is specified."); +// } +// +// if ((instanceIds == null) && (instanceIdParam != null)) { +// instanceIds = new ArrayList(); +// instanceIds.add(instanceIdParam); +// } +// +// // FIXME: We should probably lock the load balancer here to prevent multiple updates... +// LoadBalancerVO loadBalancer = _loadBalancerDao.findById(loadBalancerId); +// if (loadBalancer == null) { +// throw new InvalidParameterValueException("Failed to assign to load balancer " + loadBalancerId + ", the load balancer was not found."); +// } +// +// +// // Permission check... +// Account account = UserContext.current().getAccount(); +// if (account != null) { +// if (account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) { +// if (!_domainDao.isChildDomain(account.getDomainId(), loadBalancer.getDomainId())) { +// throw new PermissionDeniedException("Failed to assign to load balancer " + loadBalancerId + ", permission denied."); +// } +// } else if (account.getType() != Account.ACCOUNT_TYPE_ADMIN && account.getId() != loadBalancer.getAccountId()) { +// throw new PermissionDeniedException("Failed to assign to load balancer " + loadBalancerId + ", permission denied."); +// } +// } +// +// Transaction txn = Transaction.currentTxn(); +// List firewallRulesToApply = new ArrayList(); +// long accountId = 0; +// DomainRouterVO router = null; +// +// List mappedInstances = _loadBalancerVMMapDao.listByLoadBalancerId(loadBalancerId, false); +// Set mappedInstanceIds = new HashSet(); +// if (mappedInstances != null) { +// for (LoadBalancerVMMapVO mappedInstance : mappedInstances) { +// mappedInstanceIds.add(Long.valueOf(mappedInstance.getInstanceId())); +// } +// } +// +// List finalInstanceIds = new ArrayList(); +// for (Long instanceId : instanceIds) { +// if (mappedInstanceIds.contains(instanceId)) { +// continue; +// } else { +// finalInstanceIds.add(instanceId); +// } +// +// UserVmVO userVm = _vmDao.findById(instanceId); +// if (userVm == null) { +// s_logger.warn("Unable to find virtual machine with id " + instanceId); +// throw new InvalidParameterValueException("Unable to find virtual machine with id " + instanceId); +// } else { +// // sanity check that the vm can be applied to the load balancer +// ServiceOfferingVO offering = _serviceOfferingDao.findById(userVm.getServiceOfferingId()); +// if ((offering == null) || !GuestIpType.Virtualized.equals(offering.getGuestIpType())) { +// // we previously added these instanceIds to the loadBalancerVMMap, so remove them here as we are rejecting the API request +// // without actually modifying the load balancer +// _loadBalancerVMMapDao.remove(loadBalancerId, instanceIds, Boolean.TRUE); +// +// if (s_logger.isDebugEnabled()) { +// s_logger.debug("Unable to add virtual machine " + userVm.toString() + " to load balancer " + loadBalancerId + ", bad network type (" + ((offering == null) ? "null" : offering.getGuestIpType()) + ")"); +// } +// +// throw new InvalidParameterValueException("Unable to add virtual machine " + userVm.toString() + " to load balancer " + loadBalancerId + ", bad network type (" + ((offering == null) ? "null" : offering.getGuestIpType()) + ")"); +// } +// } +// +// if (accountId == 0) { +// accountId = userVm.getAccountId(); +// } else if (accountId != userVm.getAccountId()) { +// s_logger.warn("guest vm " + userVm.getHostName() + " (id:" + userVm.getId() + ") belongs to account " + userVm.getAccountId() +// + ", previous vm in list belongs to account " + accountId); +// throw new InvalidParameterValueException("guest vm " + userVm.getHostName() + " (id:" + userVm.getId() + ") belongs to account " + userVm.getAccountId() +// + ", previous vm in list belongs to account " + accountId); +// } +// +// DomainRouterVO nextRouter = null; +// if (userVm.getDomainRouterId() != null) { +// nextRouter = _routerMgr.getRouter(userVm.getDomainRouterId()); +// } +// if (nextRouter == null) { +// s_logger.warn("Unable to find router (" + userVm.getDomainRouterId() + ") for virtual machine with id " + instanceId); +// throw new InvalidParameterValueException("Unable to find router (" + userVm.getDomainRouterId() + ") for virtual machine with id " + instanceId); +// } +// +// if (router == null) { +// router = nextRouter; +// +// // Make sure owner of router is owner of load balancer. Since we are already checking that all VMs belong to the same router, by checking router +// // ownership once we'll make sure all VMs belong to the owner of the load balancer. +// if (router.getAccountId() != loadBalancer.getAccountId()) { +// throw new InvalidParameterValueException("guest vm " + userVm.getHostName() + " (id:" + userVm.getId() + ") does not belong to the owner of load balancer " + +// loadBalancer.getName() + " (owner is account id " + loadBalancer.getAccountId() + ")"); +// } +// } else if (router.getId() != nextRouter.getId()) { +// throw new InvalidParameterValueException("guest vm " + userVm.getHostName() + " (id:" + userVm.getId() + ") belongs to router " + nextRouter.getHostName() +// + ", previous vm in list belongs to router " + router.getHostName()); +// } +// +// // check for ip address/port conflicts by checking exising forwarding and loadbalancing rules +// String ipAddress = loadBalancer.getIpAddress(); +// String privateIpAddress = userVm.getGuestIpAddress(); +// List existingRulesOnPubIp = _rulesDao.listIPForwarding(ipAddress); +// +// if (existingRulesOnPubIp != null) { +// for (PortForwardingRuleVO 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.getSourcePort().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.getDestinationIpAddress().equals(privateIpAddress) && fwRule.getDestinationPort().equals(loadBalancer.getPrivatePort()) && fwRule.isEnabled()) { +// // for the current load balancer, don't add the same instance to the load balancer more than once +// continue; +// } +// } +// } +// +// PortForwardingRuleVO newFwRule = new PortForwardingRuleVO(); +// newFwRule.setAlgorithm(loadBalancer.getAlgorithm()); +// newFwRule.setEnabled(true); +// newFwRule.setForwarding(false); +// newFwRule.setPrivatePort(loadBalancer.getPrivatePort()); +// newFwRule.setPublicPort(loadBalancer.getPublicPort()); +// newFwRule.setPublicIpAddress(loadBalancer.getIpAddress()); +// newFwRule.setPrivateIpAddress(userVm.getGuestIpAddress()); +// newFwRule.setGroupId(loadBalancer.getId()); +// +// firewallRulesToApply.add(newFwRule); +// } +// +// // if there's no work to do, bail out early rather than reconfiguring the proxy with the existing rules +// if (firewallRulesToApply.isEmpty()) { +// return true; +// } +// +// //Sync on domR +// if(router == null){ +// throw new InvalidParameterValueException("Failed to assign to load balancer " + loadBalancerId + ", the domain router was not found at " + loadBalancer.getIpAddress()); +// } +// else{ +// cmd.synchronizeCommand("Router", router.getId()); +// } +// +// IPAddressVO ipAddr = _ipAddressDao.findById(loadBalancer.getIpAddress()); +// List ipAddrs = listPublicIpAddressesInVirtualNetwork(accountId, ipAddr.getDataCenterId(), null); +// for (IPAddressVO ipv : ipAddrs) { +// List rules = _rulesDao.listIpForwardingRulesForLoadBalancers(ipv.getAddress()); +// firewallRulesToApply.addAll(rules); +// } +// +// txn.start(); +// +// List updatedRules = null; +// if (router.getState().equals(State.Starting)) { +// // Starting is a special case...if the router is starting that means the IP address hasn't yet been assigned to the domR and the update firewall rules script will fail. +// // In this case, just store the rules and they will be applied when the router state is resent (after the router is started). +// updatedRules = firewallRulesToApply; +// } else { +// updatedRules = updateFirewallRules(loadBalancer.getIpAddress(), firewallRulesToApply, router); +// } +// +// // Save and create the event +// String description; +// String type = EventTypes.EVENT_NET_RULE_ADD; +// String ruleName = "load balancer"; +// String level = EventVO.LEVEL_INFO; +// +// LoadBalancerVO loadBalancerLock = null; +// try { +// loadBalancerLock = _loadBalancerDao.acquireInLockTable(loadBalancerId); +// if (loadBalancerLock == null) { +// s_logger.warn("assignToLoadBalancer: Failed to lock load balancer " + loadBalancerId + ", proceeding with updating loadBalancerVMMappings..."); +// } +// if ((updatedRules != null) && (updatedRules.size() == firewallRulesToApply.size())) { +// // flag the instances as mapped to the load balancer +// for (Long addedInstanceId : finalInstanceIds) { +// LoadBalancerVMMapVO mappedVM = new LoadBalancerVMMapVO(loadBalancerId, addedInstanceId); +// _loadBalancerVMMapDao.persist(mappedVM); +// } +// +// /* We used to add these instances as pending when the API command is received on the server, and once they were applied, +// * the pending status was removed. In the 2.2 API framework, this is no longer done and instead the new mappings just +// * need to be persisted +// List pendingMappedVMs = _loadBalancerVMMapDao.listByLoadBalancerId(loadBalancerId, true); +// for (LoadBalancerVMMapVO pendingMappedVM : pendingMappedVMs) { +// if (instanceIds.contains(pendingMappedVM.getInstanceId())) { +// LoadBalancerVMMapVO pendingMappedVMForUpdate = _loadBalancerVMMapDao.createForUpdate(); +// pendingMappedVMForUpdate.setPending(false); +// _loadBalancerVMMapDao.update(pendingMappedVM.getId(), pendingMappedVMForUpdate); +// } +// } +// */ +// +// for (PortForwardingRuleVO updatedRule : updatedRules) { +// _rulesDao.persist(updatedRule); +// +// description = "created new " + ruleName + " rule [" + updatedRule.getSourceIpAddress() + ":" +// + updatedRule.getSourcePort() + "]->[" + updatedRule.getDestinationIpAddress() + ":" +// + updatedRule.getDestinationPort() + "]" + " " + updatedRule.getProtocol(); +// +// EventUtils.saveEvent(UserContext.current().getUserId(), loadBalancer.getAccountId(), level, type, description); +// } +// txn.commit(); +// return true; +// } else { +// // Remove the instanceIds from the load balancer since there was a failure. Make sure to commit the +// // transaction here, otherwise the act of throwing the internal error exception will cause this +// // remove operation to be rolled back. +// _loadBalancerVMMapDao.remove(loadBalancerId, instanceIds, null); +// txn.commit(); +// +// s_logger.warn("Failed to apply load balancer " + loadBalancer.getName() + " (id:" + loadBalancerId + ") to guest virtual machines " + StringUtils.join(instanceIds, ",")); +// throw new CloudRuntimeException("Failed to apply load balancer " + loadBalancer.getName() + " (id:" + loadBalancerId + ") to guest virtual machine " + StringUtils.join(instanceIds, ",")); +// } +// } finally { +// if (loadBalancerLock != null) { +// _loadBalancerDao.releaseFromLockTable(loadBalancerId); +// } +// } +// } + + +// @Override @DB +// public LoadBalancer createLoadBalancerRule(CreateLoadBalancerRuleCmd cmd) throws InvalidParameterValueException, PermissionDeniedException { +// String publicIp = cmd.getPublicIp(); +// +// // make sure ip address exists +// IPAddressVO ipAddr = _ipAddressDao.findById(cmd.getPublicIp()); +// if (ipAddr == null) { +// throw new InvalidParameterValueException("Unable to create load balancer rule, invalid IP address " + publicIp); +// } +// +// VlanVO vlan = _vlanDao.findById(ipAddr.getVlanDbId()); +// if (vlan != null) { +// if (!VlanType.VirtualNetwork.equals(vlan.getVlanType())) { +// throw new InvalidParameterValueException("Unable to create load balancer rule for IP address " + publicIp + ", only VirtualNetwork type IP addresses can be used for load balancers."); +// } +// } // else ERROR? +// +// // Verify input parameters +// if ((ipAddr.getAccountId() == null) || (ipAddr.getAllocated() == null)) { +// throw new InvalidParameterValueException("Unable to create load balancer rule, cannot find account owner for ip " + publicIp); +// } +// +// Account account = UserContext.current().getAccount(); +// if (account != null) { +// if ((account.getType() == Account.ACCOUNT_TYPE_ADMIN) || (account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN)) { +// if (!_domainDao.isChildDomain(account.getDomainId(), ipAddr.getDomainId())) { +// throw new PermissionDeniedException("Unable to create load balancer rule on IP address " + publicIp + ", permission denied."); +// } +// } else if (account.getId() != ipAddr.getAccountId().longValue()) { +// throw new PermissionDeniedException("Unable to create load balancer rule, account " + account.getAccountName() + " doesn't own ip address " + publicIp); +// } +// } +// +// String loadBalancerName = cmd.getLoadBalancerRuleName(); +// LoadBalancerVO existingLB = _loadBalancerDao.findByAccountAndName(ipAddr.getAccountId(), loadBalancerName); +// if (existingLB != null) { +// throw new InvalidParameterValueException("Unable to create load balancer rule, an existing load balancer rule with name " + loadBalancerName + " already exists."); +// } +// +// // validate params +// String publicPort = cmd.getPublicPort(); +// String privatePort = cmd.getPrivatePort(); +// String algorithm = cmd.getAlgorithm(); +// +// if (!NetUtils.isValidPort(publicPort)) { +// throw new InvalidParameterValueException("publicPort is an invalid value"); +// } +// if (!NetUtils.isValidPort(privatePort)) { +// throw new InvalidParameterValueException("privatePort is an invalid value"); +// } +// if ((algorithm == null) || !NetUtils.isValidAlgorithm(algorithm)) { +// throw new InvalidParameterValueException("Invalid algorithm"); +// } +// +// boolean locked = false; +// try { +// LoadBalancerVO exitingLB = _loadBalancerDao.findByIpAddressAndPublicPort(publicIp, publicPort); +// if (exitingLB != null) { +// throw new InvalidParameterValueException("IP Address/public port already load balanced by an existing load balancer rule"); +// } +// +// List existingFwRules = _rulesDao.listIPForwarding(publicIp, publicPort, true); +// if ((existingFwRules != null) && !existingFwRules.isEmpty()) { +// throw new InvalidParameterValueException("IP Address (" + publicIp + ") and port (" + publicPort + ") already in use"); +// } +// +// ipAddr = _ipAddressDao.acquireInLockTable(publicIp); +// if (ipAddr == null) { +// throw new PermissionDeniedException("User does not own ip address " + publicIp); +// } +// +// locked = true; +// +// LoadBalancerVO loadBalancer = new LoadBalancerVO(loadBalancerName, cmd.getDescription(), ipAddr.getAccountId(), publicIp, publicPort, privatePort, algorithm); +// loadBalancer = _loadBalancerDao.persist(loadBalancer); +// Long id = loadBalancer.getId(); +// +// // Save off information for the event that the security group was applied +// Long userId = UserContext.current().getUserId(); +// if (userId == null) { +// userId = Long.valueOf(User.UID_SYSTEM); +// } +// +// EventVO event = new EventVO(); +// event.setUserId(userId); +// event.setAccountId(ipAddr.getAccountId()); +// event.setType(EventTypes.EVENT_LOAD_BALANCER_CREATE); +// +// if (id == null) { +// event.setDescription("Failed to create load balancer " + loadBalancer.getName() + " on ip address " + publicIp + "[" + publicPort + "->" + privatePort + "]"); +// event.setLevel(EventVO.LEVEL_ERROR); +// } else { +// event.setDescription("Successfully created load balancer " + loadBalancer.getName() + " on ip address " + publicIp + "[" + publicPort + "->" + privatePort + "]"); +// String params = "id="+loadBalancer.getId()+"\ndcId="+ipAddr.getDataCenterId(); +// event.setParameters(params); +// event.setLevel(EventVO.LEVEL_INFO); +// } +// _eventDao.persist(event); +// +// return _loadBalancerDao.findById(id); +// } finally { +// if (locked) { +// _ipAddressDao.releaseFromLockTable(publicIp); +// } +// } +// } + +// @Override +// public boolean updateLoadBalancerRules(final List fwRules, final DomainRouterVO router, Long hostId) { +// +// for (PortForwardingRuleVO rule : fwRules) { +// // Determine the the VLAN ID and netmask of the rule's public IP address +// IPAddressVO ip = _ipAddressDao.findById(rule.getSourceIpAddress()); +// VlanVO vlan = _vlanDao.findById(new Long(ip.getVlanDbId())); +// String vlanNetmask = vlan.getVlanNetmask(); +// +// rule.setVlanNetmask(vlanNetmask); +// } +// +// final LoadBalancerConfigurator cfgrtr = new HAProxyConfigurator(); +// final String [] cfg = cfgrtr.generateConfiguration(fwRules); +// final String [][] addRemoveRules = cfgrtr.generateFwRules(fwRules); +// final LoadBalancerCfgCommand cmd = new LoadBalancerCfgCommand(cfg, addRemoveRules, router.getInstanceName(), router.getPrivateIpAddress()); +// final Answer ans = _agentMgr.easySend(hostId, cmd); +// if (ans == null) { +// return false; +// } else { +// return ans.getResult(); +// } +// } +// @Override @DB +// public LoadBalancerVO updateLoadBalancerRule(UpdateLoadBalancerRuleCmd cmd) throws InvalidParameterValueException, PermissionDeniedException{ +// Long loadBalancerId = cmd.getId(); +// String privatePort = cmd.getPrivatePort(); +// String algorithm = cmd.getAlgorithm(); +// String name = cmd.getLoadBalancerName(); +// String description = cmd.getDescription(); +// Account account = UserContext.current().getAccount(); +// +// //Verify input parameters +// LoadBalancerVO loadBalancer = _loadBalancerDao.findById(loadBalancerId); +// if (loadBalancer == null) { +// throw new InvalidParameterValueException("Unable to find load balancer rule " + loadBalancerId + " for update."); +// } +// +// // make sure the name's not already in use +// if (name != null) { +// LoadBalancerVO existingLB = _loadBalancerDao.findByAccountAndName(loadBalancer.getAccountId(), name); +// if ((existingLB != null) && (existingLB.getId() != loadBalancer.getId())) { +// throw new InvalidParameterValueException("Unable to update load balancer " + loadBalancer.getName() + " with new name " + name + ", the name is already in use."); +// } +// } +// +// Account lbOwner = _accountDao.findById(loadBalancer.getAccountId()); +// if (lbOwner == null) { +// throw new InvalidParameterValueException("Unable to update load balancer rule, cannot find owning account"); +// } +// +// Long accountId = lbOwner.getId(); +// if (account != null) { +// if (!isAdmin(account.getType())) { +// if (account.getId() != accountId.longValue()) { +// throw new PermissionDeniedException("Unable to update load balancer rule, permission denied"); +// } +// } else if (!_domainDao.isChildDomain(account.getDomainId(), lbOwner.getDomainId())) { +// throw new PermissionDeniedException("Unable to update load balancer rule, permission denied."); +// } +// } +// +// String updatedPrivatePort = ((privatePort == null) ? loadBalancer.getPrivatePort() : privatePort); +// String updatedAlgorithm = ((algorithm == null) ? loadBalancer.getAlgorithm() : algorithm); +// String updatedName = ((name == null) ? loadBalancer.getName() : name); +// String updatedDescription = ((description == null) ? loadBalancer.getDescription() : description); +// +// Transaction txn = Transaction.currentTxn(); +// try { +// txn.start(); +// loadBalancer.setPrivatePort(updatedPrivatePort); +// loadBalancer.setAlgorithm(updatedAlgorithm); +// loadBalancer.setName(updatedName); +// loadBalancer.setDescription(updatedDescription); +// _loadBalancerDao.update(loadBalancer.getId(), loadBalancer); +// +// List fwRules = _firewallRulesDao.listByLoadBalancerId(loadBalancer.getId()); +// if ((fwRules != null) && !fwRules.isEmpty()) { +// for (PortForwardingRuleVO fwRule : fwRules) { +// fwRule.setPrivatePort(updatedPrivatePort); +// fwRule.setAlgorithm(updatedAlgorithm); +// _firewallRulesDao.update(fwRule.getId(), fwRule); +// } +// } +// txn.commit(); +// } catch (RuntimeException ex) { +// s_logger.warn("Unhandled exception trying to update load balancer rule", ex); +// txn.rollback(); +// throw ex; +// } finally { +// txn.close(); +// } +// +// // now that the load balancer has been updated, reconfigure the HA Proxy on the router with all the LB rules +// List allLbRules = new ArrayList(); +// IPAddressVO ipAddress = _ipAddressDao.findById(loadBalancer.getIpAddress()); +// List ipAddrs = listPublicIpAddressesInVirtualNetwork(loadBalancer.getAccountId(), ipAddress.getDataCenterId(), null); +// for (IPAddressVO ipv : ipAddrs) { +// List rules = _firewallRulesDao.listIPForwarding(ipv.getAddress(), false); +// allLbRules.addAll(rules); +// } +// +// IPAddressVO ip = _ipAddressDao.findById(loadBalancer.getIpAddress()); +// DomainRouterVO router = _routerMgr.getRouter(ip.getAccountId(), ip.getDataCenterId()); +// updateFirewallRules(loadBalancer.getIpAddress(), allLbRules, router); +// return _loadBalancerDao.findById(loadBalancer.getId()); +// } + + @Override + public List listLoadBalancerInstances(ListLoadBalancerRuleInstancesCmd cmd) throws PermissionDeniedException { +// Account account = UserContext.current().getAccount(); +// Long loadBalancerId = cmd.getId(); +// Boolean applied = cmd.isApplied(); +// +// if (applied == null) { +// applied = Boolean.TRUE; +// } +// +// LoadBalancerVO loadBalancer = _loadBalancerDao.findById(loadBalancerId); +// if (loadBalancer == null) { +// return null; +// } +// +// if (account != null) { +// long lbAcctId = loadBalancer.getAccountId(); +// if (isAdmin(account.getType())) { +// Account userAccount = _accountDao.findById(lbAcctId); +// if (!_domainDao.isChildDomain(account.getDomainId(), userAccount.getDomainId())) { +// throw new PermissionDeniedException("Invalid load balancer rule id (" + loadBalancerId + ") given, unable to list load balancer instances."); +// } +// } else if (account.getId() != lbAcctId) { +// throw new PermissionDeniedException("Unable to list load balancer instances, account " + account.getAccountName() + " does not own load balancer rule " + loadBalancer.getName()); +// } +// } +// +// List loadBalancerInstances = new ArrayList(); +// List vmLoadBalancerMappings = null; +// if (applied) { +// // List only the instances that have actually been applied to the load balancer (pending is false). +// vmLoadBalancerMappings = _loadBalancerVMMapDao.listByLoadBalancerId(loadBalancerId, false); +// } else { +// // List all instances applied, even pending ones that are currently being assigned, so that the semantics +// // of "what instances can I apply to this load balancer" are maintained. +// vmLoadBalancerMappings = _loadBalancerVMMapDao.listByLoadBalancerId(loadBalancerId); +// } +// List appliedInstanceIdList = new ArrayList(); +// if ((vmLoadBalancerMappings != null) && !vmLoadBalancerMappings.isEmpty()) { +// for (LoadBalancerVMMapVO vmLoadBalancerMapping : vmLoadBalancerMappings) { +// appliedInstanceIdList.add(vmLoadBalancerMapping.getInstanceId()); +// } +// } +// +// IPAddressVO addr = _publicIpAddressDao.findById(loadBalancer.getIpAddress()); +// List userVms = _userVmDao.listVirtualNetworkInstancesByAcctAndZone(loadBalancer.getAccountId(), addr.getDataCenterId()); +// +// for (UserVmVO userVm : userVms) { +// // if the VM is destroyed, being expunged, in an error state, or in an unknown state, skip it +// switch (userVm.getState()) { +// case Destroyed: +// case Expunging: +// case Error: +// case Unknown: +// continue; +// } +// +// boolean isApplied = appliedInstanceIdList.contains(userVm.getId()); +// if (!applied && !isApplied) { +// loadBalancerInstances.add(userVm); +// } else if (applied && isApplied) { +// loadBalancerInstances.add(userVm); +// } +// } +// +// return loadBalancerInstances; + return null; + } + + @Override + public List searchForLoadBalancers(ListLoadBalancerRulesCmd cmd) throws InvalidParameterValueException, PermissionDeniedException { + // do some parameter validation +// Account account = UserContext.current().getAccount(); +// String accountName = cmd.getAccountName(); +// Long domainId = cmd.getDomainId(); +// Long accountId = null; +// Account ipAddressOwner = null; +// String ipAddress = cmd.getPublicIp(); +// +// if (ipAddress != null) { +// IPAddressVO ipAddressVO = _publicIpAddressDao.findById(ipAddress); +// if (ipAddressVO == null) { +// throw new InvalidParameterValueException("Unable to list load balancers, IP address " + ipAddress + " not found."); +// } else { +// Long ipAddrAcctId = ipAddressVO.getAccountId(); +// if (ipAddrAcctId == null) { +// throw new InvalidParameterValueException("Unable to list load balancers, IP address " + ipAddress + " is not associated with an account."); +// } +// ipAddressOwner = _accountDao.findById(ipAddrAcctId); +// } +// } +// +// if ((account == null) || isAdmin(account.getType())) { +// // validate domainId before proceeding +// if (domainId != null) { +// if ((account != null) && !_domainDao.isChildDomain(account.getDomainId(), domainId)) { +// throw new PermissionDeniedException("Unable to list load balancers for domain id " + domainId + ", permission denied."); +// } +// if (accountName != null) { +// Account userAccount = _accountDao.findActiveAccount(accountName, domainId); +// if (userAccount != null) { +// accountId = userAccount.getId(); +// } else { +// throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain " + domainId); +// } +// } +// } else if (ipAddressOwner != null) { +// if ((account != null) && !_domainDao.isChildDomain(account.getDomainId(), ipAddressOwner.getDomainId())) { +// throw new PermissionDeniedException("Unable to list load balancer rules for IP address " + ipAddress + ", permission denied."); +// } +// } else { +// domainId = ((account == null) ? DomainVO.ROOT_DOMAIN : account.getDomainId()); +// } +// } else { +// accountId = account.getId(); +// } +// +// Filter searchFilter = new Filter(LoadBalancerVO.class, "ipAddress", true, cmd.getStartIndex(), cmd.getPageSizeVal()); +// +// Object id = cmd.getId(); +// Object name = cmd.getLoadBalancerRuleName(); +// Object keyword = cmd.getKeyword(); +// Object instanceId = cmd.getVirtualMachineId(); +// +// SearchBuilder sb = _loadBalancerDao.createSearchBuilder(); +// sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); +// sb.and("nameEQ", sb.entity().getName(), SearchCriteria.Op.EQ); +// sb.and("accountId", sb.entity().getAccountId(), SearchCriteria.Op.EQ); +// sb.and("ipAddress", sb.entity().getIpAddress(), SearchCriteria.Op.EQ); +// +// if ((accountId == null) && (domainId != null)) { +// // if accountId isn't specified, we can do a domain match for the admin case +// SearchBuilder domainSearch = _domainDao.createSearchBuilder(); +// domainSearch.and("path", domainSearch.entity().getPath(), SearchCriteria.Op.LIKE); +// sb.join("domainSearch", domainSearch, sb.entity().getDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER); +// } +// +// if (instanceId != null) { +// SearchBuilder lbVMSearch = _loadBalancerVMMapDao.createSearchBuilder(); +// lbVMSearch.and("instanceId", lbVMSearch.entity().getInstanceId(), SearchCriteria.Op.EQ); +// sb.join("lbVMSearch", lbVMSearch, sb.entity().getId(), lbVMSearch.entity().getLoadBalancerId(), JoinBuilder.JoinType.INNER); +// } +// +// SearchCriteria sc = sb.create(); +// if (keyword != null) { +// SearchCriteria ssc = _loadBalancerDao.createSearchCriteria(); +// ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%"); +// ssc.addOr("description", SearchCriteria.Op.LIKE, "%" + keyword + "%"); +// +// sc.addAnd("name", SearchCriteria.Op.SC, ssc); +// } +// +// if (name != null) { +// sc.setParameters("nameEQ", name); +// } +// +// if (id != null) { +// sc.setParameters("id", id); +// } +// +// if (ipAddress != null) { +// sc.setParameters("ipAddress", ipAddress); +// } +// +// if (accountId != null) { +// sc.setParameters("accountId", accountId); +// } else if (domainId != null) { +// DomainVO domain = _domainDao.findById(domainId); +// sc.setJoinParameters("domainSearch", "path", domain.getPath() + "%"); +// } +// +// if (instanceId != null) { +// sc.setJoinParameters("lbVMSearch", "instanceId", instanceId); +// } +// +// return _loadBalancerDao.search(sc, searchFilter); + return null; + } + +// @Override +// public LoadBalancerVO findLoadBalancer(Long accountId, String name) { +// SearchCriteria sc = _loadBalancerDao.createSearchCriteria(); +// sc.addAnd("accountId", SearchCriteria.Op.EQ, accountId); +// sc.addAnd("name", SearchCriteria.Op.EQ, name); +// List loadBalancers = _loadBalancerDao.search(sc, null); +// if ((loadBalancers != null) && !loadBalancers.isEmpty()) { +// return loadBalancers.get(0); +// } +// return null; +// } + + +} diff --git a/server/src/com/cloud/network/router/DomainRouterManagerImpl.java b/server/src/com/cloud/network/router/DomainRouterManagerImpl.java index 1206f070a56..3bc81f488f3 100644 --- a/server/src/com/cloud/network/router/DomainRouterManagerImpl.java +++ b/server/src/com/cloud/network/router/DomainRouterManagerImpl.java @@ -105,7 +105,6 @@ import com.cloud.host.dao.HostDao; import com.cloud.hypervisor.Hypervisor; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.network.DomainRouterService; -import com.cloud.network.FirewallRuleVO; import com.cloud.network.IPAddressVO; import com.cloud.network.Network; import com.cloud.network.NetworkManager; @@ -123,6 +122,7 @@ import com.cloud.network.dao.NetworkRuleConfigDao; import com.cloud.network.dao.RemoteAccessVpnDao; import com.cloud.network.dao.VpnUserDao; import com.cloud.network.router.VirtualRouter.Role; +import com.cloud.network.rules.PortForwardingRuleVO; import com.cloud.offering.NetworkOffering; import com.cloud.offerings.NetworkOfferingVO; import com.cloud.offerings.dao.NetworkOfferingDao; @@ -272,10 +272,11 @@ public class DomainRouterManagerImpl implements DomainRouterManager, DomainRoute ModifySshKeysCommand cmd = new ModifySshKeysCommand(pubKey, prvKey); final Answer answer = _agentMgr.easySend(hostId, cmd); - if (answer != null) - return true; - else - return false; + if (answer != null) { + return true; + } else { + return false; + } } @Override @@ -297,8 +298,9 @@ public class DomainRouterManagerImpl implements DomainRouterManager, DomainRoute if (pod == null) { throw new ConcurrentOperationException("Unable to acquire lock on pod " + podId ); } - if(s_logger.isDebugEnabled()) - s_logger.debug("Lock on pod " + podId + " is acquired"); + if(s_logger.isDebugEnabled()) { + s_logger.debug("Lock on pod " + podId + " is acquired"); + } final long id = _routerDao.getNextInSequence(Long.class, "id"); final String[] macAddresses = _dcDao.getNextAvailableMacAddressPair(dc.getId()); @@ -314,7 +316,7 @@ public class DomainRouterManagerImpl implements DomainRouterManager, DomainRoute return rtrs.get(0); } String mgmtNetmask = NetUtils.getCidrNetmask(pod.getCidrSize()); - final String guestIp = _ipAddressDao.assignIpAddress(accountIdForDHCPServer, domainIdForDHCPServer, guestVlan.getId(), false); + final String guestIp = _ipAddressDao.assignIpAddress(accountIdForDHCPServer, domainIdForDHCPServer, guestVlan.getId(), false).getAddress(); router = new DomainRouterVO(id, @@ -379,7 +381,7 @@ public class DomainRouterManagerImpl implements DomainRouterManager, DomainRoute _eventDao.persist(event); throw new ExecutionException("Unable to create DHCP Server"); } - _routerDao.updateIf(router, VirtualMachine.Event.OperationSucceeded, null); + _itMgr.stateTransitTo(router, VirtualMachine.Event.OperationSucceeded, null); s_logger.info("DHCP server created: id=" + router.getId() + "; name=" + router.getHostName() + "; vlan=" + guestVlan.getVlanId() + "; pod=" + pod.getName()); @@ -407,8 +409,9 @@ public class DomainRouterManagerImpl implements DomainRouterManager, DomainRoute _routerDao.releaseFromLockTable(id); } if (pod != null) { - if(s_logger.isDebugEnabled()) - s_logger.debug("Releasing lock on pod " + podId); + if(s_logger.isDebugEnabled()) { + s_logger.debug("Releasing lock on pod " + podId); + } _podDao.releaseFromLockTable(pod.getId()); } } @@ -432,8 +435,9 @@ public class DomainRouterManagerImpl implements DomainRouterManager, DomainRoute throw new ConcurrentOperationException("Unable to acquire account " + accountId); } - if(s_logger.isDebugEnabled()) - s_logger.debug("lock on account " + accountId + " for createRouter is acquired"); + if(s_logger.isDebugEnabled()) { + s_logger.debug("lock on account " + accountId + " for createRouter is acquired"); + } final Transaction txn = Transaction.currentTxn(); DomainRouterVO router = null; @@ -484,7 +488,7 @@ public class DomainRouterManagerImpl implements DomainRouterManager, DomainRoute // Find the VLAN ID, VLAN gateway, and VLAN netmask for publicIpAddress IPAddressVO ipVO = _ipAddressDao.findById(publicIpAddress); - VlanVO vlan = _vlanDao.findById(ipVO.getVlanDbId()); + VlanVO vlan = _vlanDao.findById(ipVO.getVlanId()); String vlanId = vlan.getVlanId(); String vlanGateway = vlan.getVlanGateway(); String vlanNetmask = vlan.getVlanNetmask(); @@ -547,7 +551,7 @@ public class DomainRouterManagerImpl implements DomainRouterManager, DomainRoute _eventDao.persist(event); throw new ExecutionException("Unable to create DomainRouter"); } - _routerDao.updateIf(router, VirtualMachine.Event.OperationSucceeded, null); + _itMgr.stateTransitTo(router, VirtualMachine.Event.OperationSucceeded, null); s_logger.debug("Router created: id=" + router.getId() + "; name=" + router.getHostName()); @@ -574,8 +578,9 @@ public class DomainRouterManagerImpl implements DomainRouterManager, DomainRoute return null; } finally { if (account != null) { - if(s_logger.isDebugEnabled()) - s_logger.debug("Releasing lock on account " + account.getId() + " for createRouter"); + if(s_logger.isDebugEnabled()) { + s_logger.debug("Releasing lock on account " + account.getId() + " for createRouter"); + } _accountDao.releaseFromLockTable(account.getId()); } if(!success){ @@ -627,13 +632,14 @@ public class DomainRouterManagerImpl implements DomainRouterManager, DomainRoute return false; } router = _routerDao.findById(routerId); - if (!_routerDao.updateIf(router, VirtualMachine.Event.DestroyRequested, router.getHostId())) { + if (! _itMgr.stateTransitTo(router, VirtualMachine.Event.DestroyRequested, router.getHostId())) { s_logger.debug("VM " + router.toString() + " is not in a state to be destroyed."); return false; } } finally { - if (s_logger.isDebugEnabled()) + if (s_logger.isDebugEnabled()) { s_logger.debug("Release lock on router " + routerId + " for stop"); + } _routerDao.releaseFromLockTable(routerId); } @@ -699,10 +705,11 @@ public class DomainRouterManagerImpl implements DomainRouterManager, DomainRoute } router.setServiceOfferingId(serviceOfferingId); - if (_routerDao.update(routerId, router)) - return _routerDao.findById(routerId); - else + if (_routerDao.update(routerId, router)) { + return _routerDao.findById(routerId); + } else { throw new CloudRuntimeException("Unable to upgrade router " + routerId); + } } @@ -781,8 +788,9 @@ public class DomainRouterManagerImpl implements DomainRouterManager, DomainRoute AsyncJobExecutor asyncExecutor = BaseAsyncJobExecutor.getCurrentExecutor(); if (asyncExecutor != null) { AsyncJobVO job = asyncExecutor.getJob(); - if (s_logger.isInfoEnabled()) + if (s_logger.isInfoEnabled()) { s_logger.info("Start router " + routerId + ", update async job-" + job.getId()); + } _asyncMgr.updateAsyncJobAttachment(job.getId(), "domain_router", routerId); } @@ -792,8 +800,9 @@ public class DomainRouterManagerImpl implements DomainRouterManager, DomainRoute return router; } - if(s_logger.isDebugEnabled()) - s_logger.debug("Lock on router " + routerId + " is acquired"); + if(s_logger.isDebugEnabled()) { + s_logger.debug("Lock on router " + routerId + " is acquired"); + } boolean started = false; String vnet = null; @@ -846,7 +855,7 @@ public class DomainRouterManagerImpl implements DomainRouterManager, DomainRoute return null; } - if (!_routerDao.updateIf(router, VirtualMachine.Event.StartRequested, routingHost.getId())) { + if (! _itMgr.stateTransitTo(router, VirtualMachine.Event.StartRequested, routingHost.getId())) { s_logger.debug("Unable to start router " + router.toString() + " because it is not in a startable state"); throw new ConcurrentOperationException("Someone else is starting the router: " + router.toString()); } @@ -955,7 +964,7 @@ public class DomainRouterManagerImpl implements DomainRouterManager, DomainRoute } router.setDomain(networkDomain); - _routerDao.updateIf(router, VirtualMachine.Event.OperationRetry, routingHost.getId()); + _itMgr.stateTransitTo(router, VirtualMachine.Event.OperationRetry, routingHost.getId()); List vols = _storageMgr.prepare(router, routingHost); if (vols == null) { @@ -1024,10 +1033,11 @@ public class DomainRouterManagerImpl implements DomainRouterManager, DomainRoute router.setPrivateIpAddress(null); - if(_defaultHypervisorType == null || !_defaultHypervisorType.equalsIgnoreCase(Hypervisor.HypervisorType.VmWare.toString())) - _dcDao.releaseLinkLocalIpAddress(privateIpAddress, router.getDataCenterId(), router.getId()); - else - _dcDao.releasePrivateIpAddress(privateIpAddress, router.getDataCenterId(), router.getId()); + if(_defaultHypervisorType == null || !_defaultHypervisorType.equalsIgnoreCase(Hypervisor.HypervisorType.VmWare.toString())) { + _dcDao.releaseLinkLocalIpAddress(privateIpAddress, router.getDataCenterId(), router.getId()); + } else { + _dcDao.releasePrivateIpAddress(privateIpAddress, router.getDataCenterId(), router.getId()); + } _storageMgr.unshare(router, vols, routingHost); } while (--retry > 0 && (routingHost = (HostVO)_agentMgr.findHost(Host.Type.Routing, dc, pod, sp, offering, template, router, null, avoid)) != null); @@ -1037,7 +1047,7 @@ public class DomainRouterManagerImpl implements DomainRouterManager, DomainRoute throw new ExecutionException("Couldn't find a routingHost"); } - _routerDao.updateIf(router, VirtualMachine.Event.OperationSucceeded, routingHost.getId()); + _itMgr.stateTransitTo(router, VirtualMachine.Event.OperationSucceeded, routingHost.getId()); if (s_logger.isDebugEnabled()) { s_logger.debug("Router " + router.toString() + " is now started on " + routingHost.toString()); } @@ -1078,7 +1088,7 @@ public class DomainRouterManagerImpl implements DomainRouterManager, DomainRoute } - if (_routerDao.updateIf(router, VirtualMachine.Event.OperationFailed, null)) { + if ( _itMgr.stateTransitTo(router, VirtualMachine.Event.OperationFailed, null)) { txn.commit(); } @@ -1093,8 +1103,9 @@ public class DomainRouterManagerImpl implements DomainRouterManager, DomainRoute } if (router != null) { - if(s_logger.isDebugEnabled()) - s_logger.debug("Releasing lock on router " + routerId); + if(s_logger.isDebugEnabled()) { + s_logger.debug("Releasing lock on router " + routerId); + } _routerDao.releaseFromLockTable(routerId); } @@ -1138,17 +1149,17 @@ public class DomainRouterManagerImpl implements DomainRouterManager, DomainRoute return false; } } - final List fwRules = new ArrayList(); - for (final IPAddressVO ipVO : ipAddrs) { - //We need only firewall rules that are either forwarding or for load balancers - fwRules.addAll(_rulesDao.listIPForwarding(ipVO.getAddress(), true)); - fwRules.addAll(_rulesDao.listIpForwardingRulesForLoadBalancers(ipVO.getAddress())); - } - final List result = _networkMgr.updateFirewallRules(router - .getPublicIpAddress(), fwRules, router); - if (result.size() != fwRules.size()) { - return false; - } + final List fwRules = new ArrayList(); +//FIXME: for (final IPAddressVO ipVO : ipAddrs) { +// //We need only firewall rules that are either forwarding or for load balancers +// fwRules.addAll(_rulesDao.listIPForwarding(ipVO.getAddress(), true)); +// fwRules.addAll(_rulesDao.listIpForwardingRulesForLoadBalancers(ipVO.getAddress())); +// } +// final List result = _networkMgr.updateFirewallRules(router +// .getPublicIpAddress(), fwRules, router); +// if (result.size() != fwRules.size()) { +// return false; +// } } return resendDhcpEntries(router) && resendVpnServerData(router); @@ -1158,8 +1169,9 @@ public class DomainRouterManagerImpl implements DomainRouterManager, DomainRoute final List vms = _vmDao.listBy(router.getId(), State.Creating, State.Starting, State.Running, State.Stopping, State.Stopped, State.Migrating); Commands cmds = new Commands(OnError.Continue); for (UserVmVO vm: vms) { - if (vm.getGuestIpAddress() == null || vm.getGuestMacAddress() == null || vm.getHostName() == null) - continue; + if (vm.getGuestIpAddress() == null || vm.getGuestMacAddress() == null || vm.getHostName() == null) { + continue; + } DhcpEntryCommand decmd = new DhcpEntryCommand(vm.getGuestMacAddress(), vm.getGuestIpAddress(), router.getPrivateIpAddress(), vm.getHostName()); cmds.addCommand(decmd); } @@ -1248,8 +1260,9 @@ public class DomainRouterManagerImpl implements DomainRouterManager, DomainRoute if (asyncExecutor != null) { AsyncJobVO job = asyncExecutor.getJob(); - if (s_logger.isInfoEnabled()) + if (s_logger.isInfoEnabled()) { s_logger.info("Stop router " + routerId + ", update async job-" + job.getId()); + } _asyncMgr.updateAsyncJobAttachment(job.getId(), "domain_router", routerId); } @@ -1365,8 +1378,9 @@ public class DomainRouterManagerImpl implements DomainRouterManager, DomainRoute if (asyncExecutor != null) { AsyncJobVO job = asyncExecutor.getJob(); - if (s_logger.isInfoEnabled()) + if (s_logger.isInfoEnabled()) { s_logger.info("Reboot router " + routerId + ", update async job-" + job.getId()); + } _asyncMgr.updateAsyncJobAttachment(job.getId(), "domain_router", routerId); } @@ -1428,10 +1442,11 @@ public class DomainRouterManagerImpl implements DomainRouterManager, DomainRoute } long eventId = EventUtils.saveScheduledEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM, EventTypes.EVENT_ROUTER_REBOOT, "rebooting Router with Id: "+routerId); - if (rebootRouter(routerId, eventId)) - return _routerDao.findById(routerId); - else - throw new CloudRuntimeException("Fail to reboot router " + routerId); + if (rebootRouter(routerId, eventId)) { + return _routerDao.findById(routerId); + } else { + throw new CloudRuntimeException("Fail to reboot router " + routerId); + } } @Override @@ -1502,7 +1517,7 @@ public class DomainRouterManagerImpl implements DomainRouterManager, DomainRoute String multicastRateStr = _configDao.getValue("multicast.throttling.rate"); _networkRate = ((networkRateStr == null) ? 200 : Integer.parseInt(networkRateStr)); _multicastRate = ((multicastRateStr == null) ? 10 : Integer.parseInt(multicastRateStr)); - _offering = new ServiceOfferingVO("System Offering For Software Router", 1, _routerRamSize, 0, 0, 0, false, null, NetworkOffering.GuestIpType.Virtualized, useLocalStorage, true, null, true); + _offering = new ServiceOfferingVO("System Offering For Software Router", 1, _routerRamSize, 256, 0, 0, false, null, NetworkOffering.GuestIpType.Virtual, useLocalStorage, true, null, true); _offering.setUniqueName("Cloud.Com-SoftwareRouter"); _offering = _serviceOfferingDao.persistSystemServiceOffering(_offering); _template = _templateDao.findRoutingTemplate(); @@ -1555,7 +1570,7 @@ public class DomainRouterManagerImpl implements DomainRouterManager, DomainRoute @Override public void completeStartCommand(final DomainRouterVO router) { - _routerDao.updateIf(router, VirtualMachine.Event.AgentReportRunning, router.getHostId()); + _itMgr.stateTransitTo(router, VirtualMachine.Event.AgentReportRunning, router.getHostId()); } @Override @@ -1579,14 +1594,15 @@ public class DomainRouterManagerImpl implements DomainRouterManager, DomainRoute String privateIpAddress = router.getPrivateIpAddress(); if (privateIpAddress != null) { - if(_defaultHypervisorType == null || !_defaultHypervisorType.equalsIgnoreCase(Hypervisor.HypervisorType.VmWare.toString())) - _dcDao.releaseLinkLocalIpAddress(privateIpAddress, router.getDataCenterId(), router.getId()); - else - _dcDao.releasePrivateIpAddress(privateIpAddress, router.getDataCenterId(), router.getId()); + if(_defaultHypervisorType == null || !_defaultHypervisorType.equalsIgnoreCase(Hypervisor.HypervisorType.VmWare.toString())) { + _dcDao.releaseLinkLocalIpAddress(privateIpAddress, router.getDataCenterId(), router.getId()); + } else { + _dcDao.releasePrivateIpAddress(privateIpAddress, router.getDataCenterId(), router.getId()); + } } router.setPrivateIpAddress(null); - if (!_routerDao.updateIf(router, ev, null)) { + if (! _itMgr.stateTransitTo(router, ev, null)) { s_logger.debug("Router is not updated"); return; } @@ -1661,8 +1677,9 @@ public class DomainRouterManagerImpl implements DomainRouterManager, DomainRoute try { - if(s_logger.isDebugEnabled()) - s_logger.debug("Lock on router " + routerId + " for stop is acquired"); + if(s_logger.isDebugEnabled()) { + s_logger.debug("Lock on router " + routerId + " for stop is acquired"); + } if (router.getRemoved() != null) { s_logger.debug("router " + routerId + " is removed"); @@ -1682,7 +1699,7 @@ public class DomainRouterManagerImpl implements DomainRouterManager, DomainRoute event.setType(EventTypes.EVENT_ROUTER_STOP); event.setStartId(eventId); - if (!_routerDao.updateIf(router, VirtualMachine.Event.StopRequested, hostId)) { + if (! _itMgr.stateTransitTo(router, VirtualMachine.Event.StopRequested, hostId)) { s_logger.debug("VM " + router.toString() + " is not in a state to be stopped."); return false; } @@ -1717,7 +1734,7 @@ public class DomainRouterManagerImpl implements DomainRouterManager, DomainRoute event.setDescription("failed to stop Domain Router : " + router.getHostName()); event.setLevel(EventVO.LEVEL_ERROR); _eventDao.persist(event); - _routerDao.updateIf(router, VirtualMachine.Event.OperationFailed, router.getHostId()); + _itMgr.stateTransitTo(router, VirtualMachine.Event.OperationFailed, router.getHostId()); return false; } @@ -1730,8 +1747,9 @@ public class DomainRouterManagerImpl implements DomainRouterManager, DomainRoute processStopOrRebootAnswer(router, answer); } finally { - if(s_logger.isDebugEnabled()) + if(s_logger.isDebugEnabled()) { s_logger.debug("Release lock on router " + routerId + " for stop"); + } _routerDao.releaseFromLockTable(routerId); } return true; @@ -1793,7 +1811,7 @@ public class DomainRouterManagerImpl implements DomainRouterManager, DomainRoute public boolean migrate(final DomainRouterVO router, final HostVO host) { final HostVO fromHost = _hostDao.findById(router.getHostId()); - if (!_routerDao.updateIf(router, VirtualMachine.Event.MigrationRequested, router.getHostId())) { + if (! _itMgr.stateTransitTo(router, VirtualMachine.Event.MigrationRequested, router.getHostId())) { s_logger.debug("State for " + router.toString() + " has changed so migration can not take place."); return false; } @@ -1820,18 +1838,18 @@ public class DomainRouterManagerImpl implements DomainRouterManager, DomainRoute final CheckVirtualMachineAnswer answer = (CheckVirtualMachineAnswer)_agentMgr.send(host.getId(), cvm); if (answer == null || !answer.getResult()) { s_logger.debug("Unable to complete migration for " + router.getId()); - _routerDao.updateIf(router, VirtualMachine.Event.AgentReportStopped, null); + _itMgr.stateTransitTo(router, VirtualMachine.Event.AgentReportStopped, null); return false; } final State state = answer.getState(); if (state == State.Stopped) { s_logger.warn("Unable to complete migration as we can not detect it on " + host.getId()); - _routerDao.updateIf(router, VirtualMachine.Event.AgentReportStopped, null); + _itMgr.stateTransitTo(router, VirtualMachine.Event.AgentReportStopped, null); return false; } - _routerDao.updateIf(router, VirtualMachine.Event.OperationSucceeded, host.getId()); + _itMgr.stateTransitTo(router, VirtualMachine.Event.OperationSucceeded, host.getId()); return true; } @@ -2068,11 +2086,11 @@ public class DomainRouterManagerImpl implements DomainRouterManager, DomainRoute List offerings = _networkMgr.getSystemAccountNetworkOfferings(NetworkOfferingVO.SystemVmControlNetwork); NetworkOfferingVO controlOffering = offerings.get(0); - NetworkVO controlConfig = _networkMgr.setupNetworkConfiguration(_systemAcct, controlOffering, plan, null, null).get(0); + NetworkVO controlConfig = _networkMgr.setupNetworkConfiguration(_systemAcct, controlOffering, plan, null, null, false).get(0); List> networks = new ArrayList>(3); NetworkOfferingVO publicOffering = _networkMgr.getSystemAccountNetworkOfferings(NetworkOfferingVO.SystemVmPublicNetwork).get(0); - List publicConfigs = _networkMgr.setupNetworkConfiguration(_systemAcct, publicOffering, plan, null, null); + List publicConfigs = _networkMgr.setupNetworkConfiguration(_systemAcct, publicOffering, plan, null, null, false); NicProfile defaultNic = new NicProfile(); defaultNic.setDefaultNic(true); //defaultNic.setIp4Address(sourceNatIp); @@ -2427,15 +2445,15 @@ public class DomainRouterManagerImpl implements DomainRouterManager, DomainRoute return false; } } - final List fwRules = new ArrayList(); - for (final IPAddressVO ipVO : ipAddrs) { - fwRules.addAll(_rulesDao.listIPForwarding(ipVO.getAddress())); - } - final List result = _networkMgr.updateFirewallRules(router - .getPublicIpAddress(), fwRules, router); - if (result.size() != fwRules.size()) { - return false; - } +// FIXME final List fwRules = new ArrayList(); +// for (final IPAddressVO ipVO : ipAddrs) { +// fwRules.addAll(_rulesDao.listIPForwarding(ipVO.getAddress())); +// } +// final List result = _networkMgr.updateFirewallRules(router +// .getPublicIpAddress(), fwRules, router); +// if (result.size() != fwRules.size()) { +// return false; +// } } return resendDhcpEntries(router) && resendVpnServerData(router); @@ -2445,8 +2463,9 @@ public class DomainRouterManagerImpl implements DomainRouterManager, DomainRoute final List vms = _vmDao.listBy(router.getId(), State.Creating, State.Starting, State.Running, State.Stopping, State.Stopped, State.Migrating); Commands cmds = new Commands(OnError.Continue); for (UserVmVO vm: vms) { - if (vm.getGuestIpAddress() == null || vm.getGuestMacAddress() == null || vm.getHostName() == null) + if (vm.getGuestIpAddress() == null || vm.getGuestMacAddress() == null || vm.getHostName() == null) { continue; + } DhcpEntryCommand decmd = new DhcpEntryCommand(vm.getGuestMacAddress(), vm.getGuestIpAddress(), router.getPrivateIpAddress(), vm.getHostName()); cmds.addCommand(decmd); } diff --git a/server/src/com/cloud/network/rules/FirewallRuleVO.java b/server/src/com/cloud/network/rules/FirewallRuleVO.java new file mode 100644 index 00000000000..c09476c54c3 --- /dev/null +++ b/server/src/com/cloud/network/rules/FirewallRuleVO.java @@ -0,0 +1,172 @@ +/** + * 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.Date; + +import javax.persistence.Column; +import javax.persistence.DiscriminatorColumn; +import javax.persistence.DiscriminatorType; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Inheritance; +import javax.persistence.InheritanceType; +import javax.persistence.Table; + +import com.cloud.utils.db.GenericDao; +import com.cloud.utils.net.Ip; + +@Entity +@Table(name="firewall_rules") +@Inheritance(strategy=InheritanceType.JOINED) +@DiscriminatorColumn(name="purpose", discriminatorType=DiscriminatorType.STRING, length=32) +public class FirewallRuleVO implements FirewallRule { + @Id + @GeneratedValue(strategy=GenerationType.IDENTITY) + @Column(name="id") + long id; + + @GeneratedValue(strategy=GenerationType.AUTO) + @Column(name=GenericDao.XID_COLUMN) + String xId; + + @Column(name="domain_id", updatable=false) + long domainId; + + @Column(name="account_id", updatable=false) + long accountId; + + @Column(name="ip_address", updatable=false) + @Enumerated(value=EnumType.ORDINAL) + Ip sourceIpAddress; + + @Column(name="start_port", updatable=false) + int sourcePortStart; + + @Column(name="end_port", updatable=false) + int sourcePortEnd; + + @Column(name="protocol", updatable=false) + String protocol = "TCP"; + + @Enumerated(value=EnumType.STRING) + @Column(name="purpose") + Purpose purpose; + + @Enumerated(value=EnumType.STRING) + @Column(name="state") + State state; + + @Column(name=GenericDao.CREATED_COLUMN) + Date created; + + @Column(name="network_id") + long networkId; + + @Override + public long getAccountId() { + return accountId; + } + + @Override + public long getDomainId() { + return domainId; + } + + @Override + public long getId() { + return id; + } + + @Override + public String getXid() { + return xId; + } + + @Override + public Ip getSourceIpAddress() { + return sourceIpAddress; + } + + @Override + public int getSourcePortStart() { + return sourcePortStart; + } + + @Override + public int getSourcePortEnd() { + return sourcePortEnd; + } + + @Override + public String getProtocol() { + return protocol; + } + + public void setState(State state) { + this.state = state; + } + + @Override + public Purpose getPurpose() { + return purpose; + } + + @Override + public State getState() { + return state; + } + + @Override + public long getNetworkId() { + return networkId; + } + + public Date getCreated() { + return created; + } + + protected FirewallRuleVO() { + } + + public FirewallRuleVO(String xId, Ip srcIp, int portStart, int portEnd, String protocol, long networkId, long accountId, long domainId, Purpose purpose) { + this.xId = xId; + this.accountId = accountId; + this.domainId = domainId; + this.sourceIpAddress = srcIp; + this.sourcePortStart = portStart; + this.sourcePortEnd = portEnd; + this.protocol = protocol; + this.purpose = purpose; + this.networkId = networkId; + this.state = State.Staged; + } + + public FirewallRuleVO(String xId, Ip srcIp, int port, String protocol, long networkId, long accountId, long domainId, Purpose purpose) { + this(xId, srcIp, port, port, protocol, networkId, accountId, domainId, purpose); + } + + @Override + public String toString() { + return new StringBuilder("Rule[").append(id).append("-").append(purpose).append("-").append(state).append("]").toString(); + } +} diff --git a/server/src/com/cloud/network/rules/PortForwardingRuleVO.java b/server/src/com/cloud/network/rules/PortForwardingRuleVO.java new file mode 100644 index 00000000000..80344b04e3d --- /dev/null +++ b/server/src/com/cloud/network/rules/PortForwardingRuleVO.java @@ -0,0 +1,76 @@ +/** + * Copyright (C) 2010 Cloud.com, Inc. All rights reserved. + * + * This software is licensed under the GNU General Public License v3 or later. + * + * It is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +package com.cloud.network.rules; + +import javax.persistence.Column; +import javax.persistence.DiscriminatorValue; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.PrimaryKeyJoinColumn; +import javax.persistence.Table; + +import com.cloud.utils.net.Ip; + +@Entity +@Table(name=("port_forwarding_rules")) +@DiscriminatorValue(value="PortForwarding") +@PrimaryKeyJoinColumn(name="id") +public class PortForwardingRuleVO extends FirewallRuleVO implements PortForwardingRule { + + @Enumerated(value=EnumType.ORDINAL) + @Column(name="dest_ip_address") + private Ip destinationIpAddress = null; + + @Column(name="dest_port_start") + private int destinationPortStart; + + @Column(name="dest_port_end") + private int destinationPortEnd; + + public PortForwardingRuleVO() { + } + + public PortForwardingRuleVO(String xId, Ip srcIp, int srcPortStart, int srcPortEnd, Ip dstIp, int dstPortStart, int dstPortEnd, String protocol, long networkId, long accountId, long domainId) { + super(xId, srcIp, srcPortStart, srcPortEnd, protocol, networkId, accountId, domainId, Purpose.PortForwarding); + this.destinationIpAddress = dstIp; + this.destinationPortStart = dstPortStart; + this.destinationPortEnd = dstPortEnd; + } + + public PortForwardingRuleVO(String xId, Ip srcIp, int srcPort, Ip dstIp, int dstPort, String protocol, long networkId, long accountId, long domainId) { + this(xId, srcIp, srcPort, srcPort, dstIp, dstPort, dstPort, protocol, networkId, accountId, domainId); + } + + @Override + public Ip getDestinationIpAddress() { + return destinationIpAddress; + } + + @Override + public int getDestinationPortStart() { + return destinationPortStart; + } + + @Override + public int getDestinationPortEnd() { + return destinationPortEnd; + } +} + diff --git a/server/src/com/cloud/network/rules/RulesManager.java b/server/src/com/cloud/network/rules/RulesManager.java index e0800c84c76..f275e7ffe4b 100644 --- a/server/src/com/cloud/network/rules/RulesManager.java +++ b/server/src/com/cloud/network/rules/RulesManager.java @@ -17,113 +17,44 @@ */ package com.cloud.network.rules; -import java.util.List; - -import com.cloud.api.commands.AddVpnUserCmd; -import com.cloud.api.commands.AssignToLoadBalancerRuleCmd; -import com.cloud.api.commands.CreateLoadBalancerRuleCmd; -import com.cloud.api.commands.CreatePortForwardingRuleCmd; -import com.cloud.api.commands.CreateRemoteAccessVpnCmd; -import com.cloud.api.commands.DeleteLoadBalancerRuleCmd; -import com.cloud.api.commands.DeleteRemoteAccessVpnCmd; -import com.cloud.api.commands.ListPortForwardingRulesCmd; -import com.cloud.api.commands.RemoveFromLoadBalancerRuleCmd; -import com.cloud.api.commands.RemoveVpnUserCmd; -import com.cloud.api.commands.UpdateLoadBalancerRuleCmd; -import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.NetworkRuleConflictException; import com.cloud.exception.PermissionDeniedException; import com.cloud.exception.ResourceUnavailableException; -import com.cloud.network.FirewallRuleVO; -import com.cloud.network.LoadBalancerVO; -import com.cloud.network.RemoteAccessVpnVO; -import com.cloud.network.VpnUserVO; -import com.cloud.vm.DomainRouterVO; +import com.cloud.network.IpAddress; +import com.cloud.user.Account; +import com.cloud.uservm.UserVm; +import com.cloud.utils.net.Ip; -public interface RulesManager { + +/** + * Rules Manager manages the network rules created for different networks. + */ +public interface RulesManager extends RulesService { + PortForwardingRule revokePortForwardingRule(String ruleId, Account caller); + + boolean applyPortForwardingRules(Ip ip, boolean continueOnError); /** - * @param fwRules list of rules to be updated - * @param router router where the rules have to be updated - * @return list of rules successfully updated - */ - List 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 - */ - boolean updateLoadBalancerRules(List fwRules, DomainRouterVO router, Long hostId); + * detectRulesConflict finds conflicts in networking rules. It checks for + * conflicts between the following types of netowrking rules; + * 1. one to one nat ip forwarding + * 2. port forwarding + * 3. load balancing + * + * It is possible for two conflicting rules to be added at the same time + * and conflicts are detected between those two rules. In this case, it + * is possible for both rules to be rolled back when, technically, we should + * only roll back one of the rules. However, the chances of that is low + * and the user can simply re-add one of the rules themselves. + * + * @param newRule the new rule created. + * @param ipAddress ip address that back up the new rule. + * @throws NetworkRuleConflictException + */ + void detectRulesConflict(FirewallRule newRule, IpAddress ipAddress) throws NetworkRuleConflictException; - /** - * @param publicIpAddress ip address associated with the fwRules - * @param fwRules list of rules to be updated - * @param router router where the rules have to be updated - * @return list of rules successfully updated - */ - List updateFirewallRules(String publicIpAddress, List fwRules, DomainRouterVO router); - - /** - * Create a port forwarding rule from the given ipAddress/port to the given virtual machine/port. - * @param cmd the command specifying the ip address, port, protocol, private port, and virtual machine id. - * @return the newly created FirewallRuleVO if successful, null otherwise. - */ - FirewallRuleVO createPortForwardingRule(CreatePortForwardingRuleCmd cmd) throws NetworkRuleConflictException; - - /** - * List port forwarding rules assigned to an ip address - * @param cmd the command object holding the criteria for listing port forwarding rules (the ipAddress) - * @return list of port forwarding rules on the given address, empty list if no rules exist - */ - List listPortForwardingRules(ListPortForwardingRulesCmd cmd); - - /** - * Create a load balancer rule from the given ipAddress/port to the given private port - * @param cmd the command specifying the ip address, port, protocol, private port, and algorithm - * @return the newly created LoadBalancerVO if successful, null otherwise - */ - LoadBalancerVO createLoadBalancerRule(CreateLoadBalancerRuleCmd cmd); - - boolean updateFirewallRule(FirewallRuleVO fwRule, String oldPrivateIP, String oldPrivatePort); - - /** - * Assign a virtual machine, or list of virtual machines, to a load balancer. - */ - boolean assignToLoadBalancer(AssignToLoadBalancerRuleCmd cmd) throws NetworkRuleConflictException; - - boolean removeFromLoadBalancer(RemoveFromLoadBalancerRuleCmd cmd); + void checkIpAndUserVm(IpAddress ipAddress, UserVm userVm, Account caller) throws InvalidParameterValueException, PermissionDeniedException; - boolean deleteLoadBalancerRule(DeleteLoadBalancerRuleCmd cmd); - LoadBalancerVO updateLoadBalancerRule(UpdateLoadBalancerRuleCmd cmd); - - RemoteAccessVpnVO createRemoteAccessVpn(CreateRemoteAccessVpnCmd cmd) throws ConcurrentOperationException, InvalidParameterValueException, PermissionDeniedException; - - /** - * Start a remote access vpn for the given ip address and client ip range - * @param cmd the command specifying the ip address, ip range - * @return the RemoteAccessVpnVO if successful, null otherwise - * @throws ConcurrentOperationException - * @throws ResourceUnavailableException - */ - RemoteAccessVpnVO startRemoteAccessVpn(CreateRemoteAccessVpnCmd cmd) throws ConcurrentOperationException, ResourceUnavailableException; - - /** - * Destroy a previously created remote access VPN - * @param cmd the command specifying the account and zone - * @return success if successful, false otherwise - * @throws ConcurrentOperationException - */ - boolean destroyRemoteAccessVpn(DeleteRemoteAccessVpnCmd cmd) throws ConcurrentOperationException; - - VpnUserVO addVpnUser(AddVpnUserCmd cmd) throws ConcurrentOperationException; - - boolean removeVpnUser(RemoveVpnUserCmd cmd) throws ConcurrentOperationException; - - FirewallRuleVO createIpForwardingRuleInDb(String ipAddr, Long virtualMachineId); - - boolean deletePortForwardingRule(Long id, boolean sysContext); - - boolean deleteIpForwardingRule(Long id); + boolean revokeAllRules(Ip ip, long userId) throws ResourceUnavailableException; } diff --git a/server/src/com/cloud/network/rules/RulesManagerImpl.java b/server/src/com/cloud/network/rules/RulesManagerImpl.java index e9cf03553a5..a0be9c2e827 100644 --- a/server/src/com/cloud/network/rules/RulesManagerImpl.java +++ b/server/src/com/cloud/network/rules/RulesManagerImpl.java @@ -23,32 +23,402 @@ import java.util.Map; import javax.ejb.Local; import javax.naming.ConfigurationException; -import com.cloud.api.commands.AddVpnUserCmd; -import com.cloud.api.commands.AssignToLoadBalancerRuleCmd; -import com.cloud.api.commands.CreateLoadBalancerRuleCmd; -import com.cloud.api.commands.CreatePortForwardingRuleCmd; -import com.cloud.api.commands.CreateRemoteAccessVpnCmd; -import com.cloud.api.commands.DeleteLoadBalancerRuleCmd; -import com.cloud.api.commands.DeleteRemoteAccessVpnCmd; +import org.apache.log4j.Logger; + import com.cloud.api.commands.ListPortForwardingRulesCmd; -import com.cloud.api.commands.RemoveFromLoadBalancerRuleCmd; -import com.cloud.api.commands.RemoveVpnUserCmd; -import com.cloud.api.commands.UpdateLoadBalancerRuleCmd; -import com.cloud.exception.ConcurrentOperationException; +import com.cloud.event.EventTypes; +import com.cloud.event.EventUtils; +import com.cloud.event.EventVO; +import com.cloud.event.dao.EventDao; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.NetworkRuleConflictException; import com.cloud.exception.PermissionDeniedException; import com.cloud.exception.ResourceUnavailableException; -import com.cloud.network.FirewallRuleVO; -import com.cloud.network.LoadBalancerVO; -import com.cloud.network.RemoteAccessVpnVO; -import com.cloud.network.VpnUserVO; +import com.cloud.network.IPAddressVO; +import com.cloud.network.IpAddress; +import com.cloud.network.Network; +import com.cloud.network.NetworkManager; +import com.cloud.network.dao.FirewallRulesDao; +import com.cloud.network.dao.IPAddressDao; +import com.cloud.network.rules.FirewallRule.Purpose; +import com.cloud.network.rules.FirewallRule.State; +import com.cloud.network.rules.dao.PortForwardingRulesDao; +import com.cloud.offering.NetworkOffering.GuestIpType; +import com.cloud.user.Account; +import com.cloud.user.AccountManager; +import com.cloud.user.UserContext; +import com.cloud.uservm.UserVm; +import com.cloud.utils.Pair; +import com.cloud.utils.component.Inject; import com.cloud.utils.component.Manager; -import com.cloud.vm.DomainRouterVO; +import com.cloud.utils.db.DB; +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.Nic; +import com.cloud.vm.UserVmVO; +import com.cloud.vm.dao.UserVmDao; -@Local(value=RulesManager.class) -public class RulesManagerImpl implements RulesManager, Manager { +@Local(value={RulesManager.class, RulesService.class}) +public class RulesManagerImpl implements RulesManager, RulesService, Manager { + private static final Logger s_logger = Logger.getLogger(RulesManagerImpl.class); String _name; + + @Inject PortForwardingRulesDao _forwardingDao; + @Inject FirewallRulesDao _firewallDao; + @Inject IPAddressDao _ipAddressDao; + @Inject UserVmDao _vmDao; + @Inject AccountManager _accountMgr; + @Inject NetworkManager _networkMgr; + @Inject EventDao _eventDao; + + @Override + public void detectRulesConflict(FirewallRule newRule, IpAddress ipAddress) throws NetworkRuleConflictException { + assert newRule.getSourceIpAddress().equals(ipAddress.getAddress()) : "You passed in an ip address that doesn't match the address in the new rule"; + + List rules = _firewallDao.listByIpAndNotRevoked(newRule.getSourceIpAddress()); + assert (rules.size() >= 1) : "For network rules, we now always first persist the rule and then check for network conflicts so we should at least have one rule at this point."; + + if (ipAddress.isOneToOneNat() && rules.size() > 1) { + throw new NetworkRuleConflictException("There are already rules in existence for the " + newRule.getSourceIpAddress()); + } + + for (FirewallRuleVO rule : rules) { + if (rule.getId() == newRule.getId()) { + continue; // Skips my own rule. + } + if (rule.getNetworkId() != newRule.getNetworkId() && rule.getState() != State.Revoke) { + throw new NetworkRuleConflictException("New rule is for a different network than what's specified in rule " + rule.getXid()); + } + if (rule.getProtocol().equals(NetUtils.NAT_PROTO)) { + throw new NetworkRuleConflictException("There is already a one to one NAT specified for " + newRule.getSourceIpAddress()); + } + if ((rule.getSourcePortStart() <= newRule.getSourcePortStart() && rule.getSourcePortEnd() >= newRule.getSourcePortStart()) || + (rule.getSourcePortStart() <= newRule.getSourcePortEnd() && rule.getSourcePortEnd() >= newRule.getSourcePortEnd()) || + (newRule.getSourcePortStart() <= rule.getSourcePortStart() && newRule.getSourcePortEnd() >= rule.getSourcePortStart()) || + (newRule.getSourcePortStart() <= rule.getSourcePortEnd() && newRule.getSourcePortEnd() >= rule.getSourcePortEnd())) { + throw new NetworkRuleConflictException("The range specified, " + newRule.getSourcePortStart() + "-" + newRule.getSourcePortEnd() + ", conflicts with rule " + rule.getId() + " which has " + rule.getSourcePortStart() + "-" + rule.getSourcePortEnd()); + } + } + + if (s_logger.isDebugEnabled()) { + s_logger.debug("No network rule conflicts detected for " + newRule + " against " + (rules.size() - 1) + " existing rules"); + } + + } + + @Override + public void checkIpAndUserVm(IpAddress ipAddress, UserVm userVm, Account caller) throws InvalidParameterValueException, PermissionDeniedException { + if (ipAddress == null || ipAddress.getAllocatedTime() == null || ipAddress.getAllocatedToAccountId() == null) { + throw new InvalidParameterValueException("Unable to create ip forwarding rule on address " + ipAddress + ", invalid IP address specified."); + } + + if (userVm == null) { + return; + } + + if (userVm.getState() == com.cloud.vm.State.Destroyed || userVm.getState() == com.cloud.vm.State.Expunging) { + throw new InvalidParameterValueException("Invalid user vm: " + userVm.getId()); + } + + _accountMgr.checkAccess(caller, userVm); + + // validate that IP address and userVM belong to the same account + if (ipAddress.getAllocatedToAccountId().longValue() != userVm.getAccountId()) { + throw new InvalidParameterValueException("Unable to create ip forwarding rule, IP address " + ipAddress + " owner is not the same as owner of virtual machine " + userVm.toString()); + } + + // validate that userVM is in the same availability zone as the IP address + if (ipAddress.getDataCenterId() != userVm.getDataCenterId()) { + throw new InvalidParameterValueException("Unable to create ip forwarding rule, IP address " + ipAddress + " is not in the same availability zone as virtual machine " + userVm.toString()); + } + + } + + @Override @DB + public PortForwardingRule createPortForwardingRule(PortForwardingRule rule, Long vmId) throws NetworkRuleConflictException { + UserContext ctx = UserContext.current(); + Account caller = ctx.getAccount(); + + String ipAddr = rule.getSourceIpAddress().addr(); + + IPAddressVO ipAddress = _ipAddressDao.findById(ipAddr); + + Ip dstIp = rule.getDestinationIpAddress(); + long networkId; + UserVmVO vm = null; + Network network = null; + if (vmId != null) { + // validate user VM exists + vm = _vmDao.findById(vmId); + if (vm == null) { + throw new InvalidParameterValueException("Unable to create ip forwarding rule on address " + ipAddress + ", invalid virtual machine id specified (" + vmId + ")."); + } + + dstIp = null; + List nics = _networkMgr.getNics(vm); + for (Nic nic : nics) { + Network ntwk = _networkMgr.getNetwork(nic.getNetworkId()); + if (ntwk.getGuestType() == GuestIpType.Virtual) { + network = ntwk; + dstIp = new Ip(nic.getIp4Address()); + break; + } + } + + if (network == null) { + throw new CloudRuntimeException("Unable to find ip address to map to in " + vmId); + } + } else { + network = _networkMgr.getNetwork(rule.getNetworkId()); + if (network == null) { + throw new InvalidParameterValueException("Unable to get the network " + rule.getNetworkId()); + } + } + + _accountMgr.checkAccess(caller, network); + + networkId = network.getId(); + long accountId = network.getAccountId(); + long domainId = network.getDomainId(); + + checkIpAndUserVm(ipAddress, vm, caller); + boolean isNat = NetUtils.NAT_PROTO.equals(rule.getProtocol()); + if (isNat && (ipAddress.isSourceNat() || ipAddress.isOneToOneNat())) { + throw new NetworkRuleConflictException("Can't do one to one NAT on ip address: " + ipAddress.getAddress()); + } + + Transaction txn = Transaction.currentTxn(); + txn.start(); + PortForwardingRuleVO newRule = + new PortForwardingRuleVO(rule.getXid(), + rule.getSourceIpAddress(), + rule.getSourcePortStart(), + rule.getSourcePortEnd(), + dstIp, + rule.getDestinationPortStart(), + rule.getDestinationPortEnd(), + rule.getProtocol(), + networkId, + accountId, + domainId); + newRule = _forwardingDao.persist(newRule); + + if (isNat) { + ipAddress.setOneToOneNat(true); + _ipAddressDao.update(ipAddress.getAddress(), ipAddress); + } + txn.commit(); + + boolean success = false; + try { + detectRulesConflict(newRule, ipAddress); + if (!_firewallDao.setStateToAdd(newRule)) { + throw new CloudRuntimeException("Unable to update the state to add for " + newRule); + } + + success = true; + return newRule; + } catch (Exception e) { + txn.start(); + _forwardingDao.remove(newRule.getId()); + if (isNat) { + ipAddress.setOneToOneNat(false); + _ipAddressDao.update(ipAddress.getAddress(), ipAddress); + } + txn.commit(); + if (e instanceof NetworkRuleConflictException) { + throw (NetworkRuleConflictException)e; + } + + throw new CloudRuntimeException("Unable to add rule for " + newRule.getSourceIpAddress(), e); + } finally { + // Save and create the event + String description; + String ruleName = "ip forwarding"; + String level = EventVO.LEVEL_INFO; + + if (success == true) { + description = "created new " + ruleName + " rule [" + newRule.getSourceIpAddress() + ":" + newRule.getSourcePortStart() + "]->[" + + newRule.getDestinationIpAddress() + ":" + newRule.getDestinationPortStart() + "]" + " " + newRule.getProtocol(); + } else { + level = EventVO.LEVEL_ERROR; + description = "failed to create new " + ruleName + " rule [" + newRule.getSourceIpAddress() + ":" + newRule.getSourcePortStart() + "]->[" + + newRule.getDestinationIpAddress() + ":" + newRule.getDestinationPortStart() + "]" + " " + newRule.getProtocol(); + } + + EventUtils.saveEvent(UserContext.current().getUserId(), vm.getAccountId(), level, EventTypes.EVENT_NET_RULE_ADD, description); + } + } + + protected Pair getUserVmGuestIpAddress(UserVm vm) { + Ip dstIp = null; + List nics = _networkMgr.getNics(vm); + for (Nic nic : nics) { + Network ntwk = _networkMgr.getNetwork(nic.getNetworkId()); + if (ntwk.getGuestType() == GuestIpType.Virtual) { + dstIp = new Ip(nic.getIp4Address()); + return new Pair(ntwk, dstIp); + } + } + + throw new CloudRuntimeException("Unable to find ip address to map to in " + vm.getId()); + } + + @DB + protected void revokeRule(FirewallRuleVO rule, Account caller, long userId) { + if (caller != null) { + _accountMgr.checkAccess(caller, rule); + } + + Transaction txn = Transaction.currentTxn(); + txn.start(); + if (rule.getState() == State.Staged) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("Found a rule that is still in stage state so just removing it: " + rule); + } + _firewallDao.remove(rule.getId()); + } else if (rule.getState() == State.Add) { + rule.setState(State.Revoke); + _firewallDao.update(rule.getId(), rule); + } + if (NetUtils.NAT_PROTO.equals(rule.protocol) && rule.getSourcePortStart() == -1) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("Removing one to one nat so setting the ip back to one to one nat is false: " + rule.getSourceIpAddress()); + } + IPAddressVO ipAddress = _ipAddressDao.findById(rule.getSourceIpAddress().addr()); + ipAddress.setOneToOneNat(false); + _ipAddressDao.update(ipAddress.getAddress(), ipAddress); + } + + // Save and create the event + String ruleName = rule.getPurpose() == Purpose.Firewall ? "Firewall" : (rule.getProtocol().equals(NetUtils.NAT_PROTO) ? "ip forwarding" : "port forwarding"); + StringBuilder description = new StringBuilder("deleted ").append(ruleName).append(" rule [").append(rule.getSourceIpAddress()).append(":").append(rule.getSourcePortStart()).append("-").append(rule.getSourcePortEnd()).append("]"); + if (rule.getPurpose() == Purpose.PortForwarding) { + PortForwardingRuleVO pfRule = (PortForwardingRuleVO)rule; + description.append("->[").append(pfRule.getDestinationIpAddress()).append(":").append(pfRule.getDestinationPortStart()).append("-").append(pfRule.getDestinationPortEnd()).append("]"); + } + description.append(" ").append(rule.getProtocol()); + + // save off an event for removing the network rule + EventVO event = new EventVO(); + event.setUserId(userId); + event.setAccountId(rule.getAccountId()); + event.setType(EventTypes.EVENT_NET_RULE_DELETE); + event.setDescription(description.toString()); + event.setLevel(EventVO.LEVEL_INFO); + _eventDao.persist(event); + } + + @Override + public PortForwardingRule revokePortForwardingRule(long ruleId, boolean apply) { + UserContext ctx = UserContext.current(); + Account caller = ctx.getAccount(); + + PortForwardingRuleVO rule = _forwardingDao.findById(ruleId); + if (rule == null) { + throw new InvalidParameterValueException("Unable to find " + ruleId); + } + + _accountMgr.checkAccess(caller, rule); + revokeRule(rule, caller, ctx.getUserId()); + + if (apply) { + applyPortForwardingRules(rule.getSourceIpAddress(), true); + } + return rule; + } + + @Override + public PortForwardingRule revokePortForwardingRule(String ruleId, Account caller) { + // FIXME: Not working yet. + return null; + } + + @Override + public List listPortForwardingRules(ListPortForwardingRulesCmd cmd) { + Ip ipAddress = new Ip(cmd.getIpAddress()); + Account caller = UserContext.current().getAccount(); + + IPAddressVO ipAddressVO = _ipAddressDao.findById(ipAddress.addr()); + if (ipAddressVO == null || ipAddressVO.getAllocatedTime() == null) { + throw new InvalidParameterValueException("Unable to find IP address " + ipAddress); + } + + List rules = _forwardingDao.listByIpAndNotRevoked(ipAddress); + _accountMgr.checkAccess(caller, rules.toArray(new PortForwardingRuleVO[rules.size()])); + + return rules; + } + + @Override + public boolean applyPortForwardingRules(Ip ip, boolean continueOnError) { + try { + return applyPortForwardingRules(ip, continueOnError, null); + } catch (ResourceUnavailableException e) { + s_logger.warn("Unable to reapply port forwarding rules for " + ip); + return false; + } + } + + protected boolean applyPortForwardingRules(Ip ip, boolean continueOnError, Account caller) throws ResourceUnavailableException { + List rules = _forwardingDao.listForApplication(ip); + if (rules.size() == 0) { + s_logger.debug("There are no rules to apply for " + ip); + return true; + } + + if (caller != null) { + _accountMgr.checkAccess(caller, rules.toArray(new PortForwardingRuleVO[rules.size()])); + } + + if (!_networkMgr.applyRules(ip, rules, continueOnError)) { + s_logger.debug("Rules are not completely applied"); + return false; + } + + for (PortForwardingRuleVO rule : rules) { + if (rule.getState() == FirewallRule.State.Revoke) { + _forwardingDao.remove(rule.getId()); + } + } + + return true; + } + + @Override + public List searchForIpForwardingRules(Ip ip, Long start, Long size) { + return _forwardingDao.searchNatRules(ip, start, size); + } + + @Override + public boolean applyPortForwardingRules(Ip ip, Account caller) throws ResourceUnavailableException { + return applyPortForwardingRules(ip, false, caller); + } + + @Override @DB + public boolean revokeAllRules(Ip ip, long userId) throws ResourceUnavailableException { + List rules = _forwardingDao.listByIpAndNotRevoked(ip); + if (s_logger.isDebugEnabled()) { + s_logger.debug("Releasing " + rules.size() + " rules for " + ip); + } + + for (PortForwardingRuleVO rule : rules) { + revokeRule(rule, null, userId); + } + + applyPortForwardingRules(ip, true, null); + + // Now we check again in case more rules have been inserted. + rules = _forwardingDao.listByIpAndNotRevoked(ip); + + if (s_logger.isDebugEnabled()) { + s_logger.debug("Successfully released rules for " + ip + " and # of rules now = " + rules.size()); + } + + return rules.size() == 0; + } @Override public boolean configure(String name, Map params) throws ConfigurationException { @@ -70,119 +440,663 @@ public class RulesManagerImpl implements RulesManager, Manager { public String getName() { return _name; } +// @Override +// public boolean updateFirewallRule(final PortForwardingRuleVO rule, String oldPrivateIP, String oldPrivatePort) { +// +// final IPAddressVO ipVO = _ipAddressDao.findById(rule.getSourceIpAddress()); +// 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 (PortForwardingRuleVO rule : fwRules) { +// // Determine the VLAN ID and netmask of the rule's public IP address +// IPAddressVO ip = _ipAddressDao.findById(rule.getSourceIpAddress()); +// 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, false); +// 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 PortForwardingRuleVO 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 PortForwardingRuleVO rule, final DomainRouterVO router, Long hostId, String oldPrivateIP, String oldPrivatePort) { +// IPAddressVO ip = _ipAddressDao.findById(rule.getSourceIpAddress()); +// 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 PortForwardingRuleVO rule: fwRules) { +// IPAddressVO ip = _ipAddressDao.findById(rule.getSourceIpAddress()); +// 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 PortForwardingRuleVO rule:fwdRules){ +// final Answer ans = answers[i++]; +// if (ans != null) { +// if (ans.getResult()) { +// result.add(rule); +// } +// } +// } +// return result; +// } +// +// @Override +// public PortForwardingRuleVO 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 (PortForwardingRuleVO fwRule : existingRulesOnPubIp) { +// Ternary> portMappings = mappedPublicPorts.get(fwRule.getSourcePort()); +// List protocolList = null; +// if (portMappings == null) { +// protocolList = new ArrayList(); +// } else { +// protocolList = portMappings.third(); +// } +// protocolList.add(fwRule.getProtocol()); +// mappedPublicPorts.put(fwRule.getSourcePort(), new Ternary>(fwRule.getDestinationIpAddress(), fwRule.getDestinationPort(), 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 + "."); +// } +// } +// +// PortForwardingRuleVO newFwRule = new PortForwardingRuleVO(); +// 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.getSourceIpAddress() + ":" + newFwRule.getSourcePort() + "]->[" +// + newFwRule.getDestinationIpAddress() + ":" + newFwRule.getDestinationPort() + "]" + " " + newFwRule.getProtocol(); +// } else { +// level = EventVO.LEVEL_ERROR; +// description = "failed to create new " + ruleName + " rule [" + newFwRule.getSourceIpAddress() + ":" + newFwRule.getSourcePort() + "]->[" +// + newFwRule.getDestinationIpAddress() + ":" + newFwRule.getDestinationPort() + "]" + " " + newFwRule.getProtocol(); +// } +// +// EventUtils.saveEvent(UserContext.current().getUserId(), userVM.getAccountId(), level, EventTypes.EVENT_NET_RULE_ADD, description); +// +// return newFwRule; +// } +// +// @Override @DB +// public PortForwardingRule createIpForwardingRuleOnDomr(long ruleId) { +// Transaction txn = Transaction.currentTxn(); +// txn.start(); +// boolean success = false; +// PortForwardingRuleVO rule = null; +// IPAddressVO ipAddress = null; +// boolean locked = false; +// try { +// //get the rule +// rule = _rulesDao.findById(ruleId); +// +// if(rule == null){ +// throw new PermissionDeniedException("Cannot create ip forwarding rule in db"); +// } +// +// //get ip address +// ipAddress = _ipAddressDao.findById(rule.getSourceIpAddress()); +// if (ipAddress == null) { +// throw new InvalidParameterValueException("Unable to create ip forwarding rule on address " + ipAddress + ", invalid IP address specified."); +// } +// +// //sync point +// ipAddress = _ipAddressDao.acquireInLockTable(ipAddress.getAddress()); +// +// if(ipAddress == null){ +// s_logger.warn("Unable to acquire lock on ipAddress for creating 1-1 NAT rule"); +// return rule; +// }else{ +// locked = true; +// } +// +// //get the domain router object +// DomainRouterVO router = _routerMgr.getRouter(ipAddress.getAccountId(), ipAddress.getDataCenterId()); +// success = createOrDeleteIpForwardingRuleOnDomr(rule,router,rule.getDestinationIpAddress(),true); //true +> create +// +// if(!success){ +// //corner case; delete record from db as domR rule creation failed +// _rulesDao.remove(ruleId); +// throw new PermissionDeniedException("Cannot create ip forwarding rule on domr, hence deleting created record in db"); +// } +// +// //update the user_ip_address record +// ipAddress.setOneToOneNat(true); +// _ipAddressDao.update(ipAddress.getAddress(),ipAddress); +// +// // Save and create the event +// String description; +// String ruleName = "ip forwarding"; +// String level = EventVO.LEVEL_INFO; +// +// description = "created new " + ruleName + " rule [" + rule.getSourceIpAddress() + "]->[" +// + rule.getDestinationIpAddress() + "]" + ":" + rule.getProtocol(); +// +// EventUtils.saveEvent(UserContext.current().getUserId(), ipAddress.getAccountId(), level, EventTypes.EVENT_NET_RULE_ADD, description); +// txn.commit(); +// } catch (Exception e) { +// txn.rollback(); +// throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage()); +// }finally{ +// if(locked){ +// _ipAddressDao.releaseFromLockTable(ipAddress.getAddress()); +// } +// } +// return rule; +// } +// +// @Override @DB +// public PortForwardingRule createIpForwardingRuleInDb(String ipAddr, long virtualMachineId) { +// +// Transaction txn = Transaction.currentTxn(); +// txn.start(); +// UserVmVO userVM = null; +// PortForwardingRuleVO newFwRule = null; +// boolean locked = false; +// try { +// // validate IP Address exists +// IPAddressVO ipAddress = _ipAddressDao.findById(ipAddr); +// if (ipAddress == null) { +// throw new InvalidParameterValueException("Unable to create ip forwarding rule on address " + ipAddress + ", invalid IP address specified."); +// } +// +// // validate user VM exists +// userVM = _vmDao.findById(virtualMachineId); +// if (userVM == null) { +// throw new InvalidParameterValueException("Unable to create ip forwarding rule on address " + ipAddress + ", invalid virtual machine id specified (" + virtualMachineId + ")."); +// } +// +// //sync point; cannot lock on rule ; hence sync on vm +// userVM = _vmDao.acquireInLockTable(userVM.getId()); +// +// if(userVM == null){ +// s_logger.warn("Unable to acquire lock on user vm for creating 1-1 NAT rule"); +// return newFwRule; +// }else{ +// locked = true; +// } +// +// // validate that IP address and userVM belong to the same account +// if ((ipAddress.getAccountId() == null) || (ipAddress.getAccountId().longValue() != userVM.getAccountId())) { +// throw new InvalidParameterValueException("Unable to create ip forwarding rule, IP address " + ipAddress + " owner is not the same as owner of virtual machine " + userVM.toString()); +// } +// +// // validate that userVM is in the same availability zone as the IP address +// if (ipAddress.getDataCenterId() != userVM.getDataCenterId()) { +// throw new InvalidParameterValueException("Unable to create ip forwarding rule, IP address " + ipAddress + " is not in the same availability zone as virtual machine " + userVM.toString()); +// } +// +// // if an admin account was passed in, or no account was passed in, make sure we honor the accountName/domainId parameters +// Account account = UserContext.current().getAccount(); +// if (account != null) { +// if ((account.getType() == Account.ACCOUNT_TYPE_ADMIN) || (account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN)) { +// if (!_domainDao.isChildDomain(account.getDomainId(), userVM.getDomainId())) { +// throw new PermissionDeniedException("Unable to create ip forwarding rule, IP address " + ipAddress + " to virtual machine " + virtualMachineId + ", permission denied."); +// } +// } else if (account.getId() != userVM.getAccountId()) { +// throw new PermissionDeniedException("Unable to create ip forwarding rule, IP address " + ipAddress + " to virtual machine " + virtualMachineId + ", permission denied."); +// } +// } +// +// // check for ip address/port conflicts by checking existing forwarding and load balancing rules +// List existingNatRules = _rulesDao.findByPublicIpPrivateIpForNatRule(ipAddr, userVM.getGuestIpAddress()); +// +// if(existingNatRules.size() > 0){ +// throw new NetworkRuleConflictException("The specified rule for public ip:"+ipAddr+" vm id:"+virtualMachineId+" already exists"); +// } +// +// //if given ip address is already source nat, return error +// if(ipAddress.isSourceNat()){ +// throw new PermissionDeniedException("Cannot create a static nat rule for the ip:"+ipAddress.getAddress()+" ,this is already a source nat ip address"); +// } +// +// //if given ip address is already static nat, return error +// if(ipAddress.isOneToOneNat()){ +// throw new PermissionDeniedException("Cannot create a static nat rule for the ip:"+ipAddress.getAddress()+" ,this is already a static nat ip address"); +// } +// +// newFwRule = new PortForwardingRuleVO(); +// newFwRule.setEnabled(true); +// newFwRule.setForwarding(true); +// newFwRule.setPrivatePort(null); +// newFwRule.setProtocol(NetUtils.NAT_PROTO);//protocol cannot be null; adding this as a NAT +// newFwRule.setPublicPort(null); +// newFwRule.setPublicIpAddress(ipAddress.getAddress()); +// newFwRule.setPrivateIpAddress(userVM.getGuestIpAddress()); +// newFwRule.setGroupId(null); +// +// _rulesDao.persist(newFwRule); +// txn.commit(); +// } catch (Exception e) { +// s_logger.warn("Unable to create new firewall rule for 1:1 NAT"); +// txn.rollback(); +// throw new ServerApiException(BaseCmd.INTERNAL_ERROR,"Unable to create new firewall rule for 1:1 NAT:"+e.getMessage()); +// }finally{ +// if(locked) { +// _vmDao.releaseFromLockTable(userVM.getId()); +// } +// } +// +// return newFwRule; +// } +// +// @Override @DB +// public boolean deleteIpForwardingRule(Long id) { +// Long ruleId = id; +// Long userId = UserContext.current().getUserId(); +// Account account = UserContext.current().getAccount(); +// +// //verify input parameters here +// PortForwardingRuleVO rule = _firewallRulesDao.findById(ruleId); +// if (rule == null) { +// throw new InvalidParameterValueException("Unable to find port forwarding rule " + ruleId); +// } +// +// String publicIp = rule.getSourceIpAddress(); +// +// +// IPAddressVO ipAddress = _ipAddressDao.findById(publicIp); +// if (ipAddress == null) { +// throw new InvalidParameterValueException("Unable to find IP address for ip forwarding rule " + ruleId); +// } +// +// // although we are not writing these values to the DB, we will check +// // them out of an abundance +// // of caution (may not be warranted) +// +// Account ruleOwner = _accountDao.findById(ipAddress.getAccountId()); +// if (ruleOwner == null) { +// throw new InvalidParameterValueException("Unable to find owning account for ip forwarding rule " + ruleId); +// } +// +// // if an admin account was passed in, or no account was passed in, make sure we honor the accountName/domainId parameters +// if (account != null) { +// if (isAdmin(account.getType())) { +// if (!_domainDao.isChildDomain(account.getDomainId(), ruleOwner.getDomainId())) { +// throw new PermissionDeniedException("Unable to delete ip forwarding rule " + ruleId + ", permission denied."); +// } +// } else if (account.getId() != ruleOwner.getId()) { +// throw new PermissionDeniedException("Unable to delete ip forwarding rule " + ruleId + ", permission denied."); +// } +// } +// +// Transaction txn = Transaction.currentTxn(); +// boolean locked = false; +// boolean success = false; +// try { +// +// ipAddress = _ipAddressDao.acquireInLockTable(publicIp); +// if (ipAddress == null) { +// throw new PermissionDeniedException("Unable to obtain lock on record for deletion"); +// } +// +// locked = true; +// txn.start(); +// +// final DomainRouterVO router = _routerMgr.getRouter(ipAddress.getAccountId(), ipAddress.getDataCenterId()); +// success = createOrDeleteIpForwardingRuleOnDomr(rule, router, rule.getDestinationIpAddress(), false); +// _firewallRulesDao.remove(ruleId); +// +// //update the ip_address record +// ipAddress.setOneToOneNat(false); +// _ipAddressDao.persist(ipAddress); +// +// String description; +// String type = EventTypes.EVENT_NET_RULE_DELETE; +// String level = EventVO.LEVEL_INFO; +// String ruleName = rule.isForwarding() ? "ip forwarding" : "load balancer"; +// +// if (success) { +// description = "deleted " + ruleName + " rule [" + publicIp +"]->[" + rule.getDestinationIpAddress() + "] " + rule.getProtocol(); +// } else { +// level = EventVO.LEVEL_ERROR; +// description = "Error while deleting " + ruleName + " rule [" + publicIp + "]->[" + rule.getDestinationIpAddress() +"] " + rule.getProtocol(); +// } +// EventUtils.saveEvent(userId, ipAddress.getAccountId(), level, type, description); +// txn.commit(); +// }catch (Exception ex) { +// txn.rollback(); +// s_logger.error("Unexpected exception deleting port forwarding rule " + ruleId, ex); +// return false; +// }finally { +// if (locked) { +// _ipAddressDao.releaseFromLockTable(publicIp); +// } +// txn.close(); +// } +// return success; +// } +// +// private boolean createOrDeleteIpForwardingRuleOnDomr(PortForwardingRuleVO fwRule, DomainRouterVO router, String guestIp, boolean create){ +// +// Commands cmds = new Commands(OnError.Continue); +// final SetFirewallRuleCommand cmd = new SetFirewallRuleCommand(router.getInstanceName(), router.getPrivateIpAddress(),fwRule, create); +// cmds.addCommand(cmd); +// try { +// _agentMgr.send(router.getHostId(), cmds); +// } catch (final AgentUnavailableException e) { +// s_logger.warn("agent unavailable", e); +// } catch (final OperationTimedoutException e) { +// s_logger.warn("Timed Out", e); +// } +// Answer[] answers = cmds.getAnswers(); +// if (answers == null || answers[0].getResult() == false ){ +// return false; +// }else{ +// return true; +// } +// } +// @Override +// public PortForwardingRuleVO updatePortForwardingRule(UpdatePortForwardingRuleCmd cmd) throws InvalidParameterValueException, PermissionDeniedException{ +// String publicIp = cmd.getPublicIp(); +// String privateIp = cmd.getPrivateIp(); +// String privatePort = cmd.getPrivatePort(); +// String publicPort = cmd.getPublicPort(); +// String protocol = cmd.getProtocol(); +// Long vmId = cmd.getVirtualMachineId(); +// Long userId = UserContext.current().getUserId(); +// Account account = UserContext.current().getAccount(); +// UserVmVO userVM = null; +// +// if (userId == null) { +// userId = Long.valueOf(User.UID_SYSTEM); +// } +// +// IPAddressVO ipAddressVO = findIPAddressById(publicIp); +// if (ipAddressVO == null) { +// throw new InvalidParameterValueException("Unable to find IP address " + publicIp); +// } +// +// if (ipAddressVO.getAccountId() == null) { +// throw new InvalidParameterValueException("Unable to update port forwarding rule, owner of IP address " + publicIp + " not found."); +// } +// +// if (privateIp != null) { +// if (!NetUtils.isValidIp(privateIp)) { +// throw new InvalidParameterValueException("Invalid private IP address specified: " + privateIp); +// } +// Criteria c = new Criteria(); +// c.addCriteria(Criteria.ACCOUNTID, new Object[] {ipAddressVO.getAccountId()}); +// c.addCriteria(Criteria.DATACENTERID, ipAddressVO.getDataCenterId()); +// c.addCriteria(Criteria.IPADDRESS, privateIp); +// List userVMs = searchForUserVMs(c); +// if ((userVMs == null) || userVMs.isEmpty()) { +// throw new ServerApiException(BaseCmd.PARAM_ERROR, "Invalid private IP address specified: " + privateIp + ", no virtual machine instances running with that address."); +// } +// userVM = userVMs.get(0); +// } else if (vmId != null) { +// userVM = findUserVMInstanceById(vmId); +// if (userVM == null) { +// throw new InvalidParameterValueException("Unable to find virtual machine with id " + vmId); +// } +// +// if ((ipAddressVO.getAccountId() == null) || (ipAddressVO.getAccountId().longValue() != userVM.getAccountId())) { +// throw new PermissionDeniedException("Unable to update port forwarding rule on IP address " + publicIp + ", permission denied."); +// } +// +// if (ipAddressVO.getDataCenterId() != userVM.getDataCenterId()) { +// throw new PermissionDeniedException("Unable to update port forwarding rule, IP address " + publicIp + " is not in the same availability zone as virtual machine " + userVM.toString()); +// } +// +// privateIp = userVM.getGuestIpAddress(); +// } else { +// throw new InvalidParameterValueException("No private IP address (privateip) or virtual machine instance id (virtualmachineid) specified, unable to update port forwarding rule"); +// } +// +// // if an admin account was passed in, or no account was passed in, make sure we honor the accountName/domainId parameters +// if (account != null) { +// if (isAdmin(account.getType())) { +// if (!_domainDao.isChildDomain(account.getDomainId(), ipAddressVO.getDomainId())) { +// throw new PermissionDeniedException("Unable to update port forwarding rule on IP address " + publicIp + ", permission denied."); +// } +// } else if (account.getId() != ipAddressVO.getAccountId()) { +// throw new PermissionDeniedException("Unable to update port forwarding rule on IP address " + publicIp + ", permission denied."); +// } +// } +// +// List fwRules = _firewallRulesDao.listIPForwardingForUpdate(publicIp, publicPort, protocol); +// if ((fwRules != null) && (fwRules.size() == 1)) { +// PortForwardingRuleVO fwRule = fwRules.get(0); +// String oldPrivateIP = fwRule.getDestinationIpAddress(); +// String oldPrivatePort = fwRule.getDestinationPort(); +// fwRule.setPrivateIpAddress(privateIp); +// fwRule.setPrivatePort(privatePort); +// _firewallRulesDao.update(fwRule.getId(), fwRule); +// _networkMgr.updateFirewallRule(fwRule, oldPrivateIP, oldPrivatePort); +// return fwRule; +// }else{ +// s_logger.warn("Unable to find the rule to be updated for public ip:public port"+publicIp+":"+publicPort+ "private ip:private port:"+privateIp+":"+privatePort); +// throw new InvalidParameterValueException("Unable to find the rule to be updated for public ip:public port"+publicIp+":"+publicPort+ " private ip:private port:"+privateIp+":"+privatePort); +// } +// } +// +// @Override +// public PortForwardingRuleVO findForwardingRuleById(Long ruleId) { +// return _firewallRulesDao.findById(ruleId); +// } - @Override - public List updatePortForwardingRules(List fwRules, DomainRouterVO router, Long hostId) { - // TODO Auto-generated method stub - return null; - } - @Override - public boolean updateLoadBalancerRules(List fwRules, DomainRouterVO router, Long hostId) { - // TODO Auto-generated method stub - return false; - } - - @Override - public List updateFirewallRules(String publicIpAddress, List fwRules, DomainRouterVO router) { - // TODO Auto-generated method stub - return null; - } - - @Override - public FirewallRuleVO createPortForwardingRule(CreatePortForwardingRuleCmd cmd) throws NetworkRuleConflictException { - // TODO Auto-generated method stub - return null; - } - - @Override - public List listPortForwardingRules(ListPortForwardingRulesCmd cmd) { - // TODO Auto-generated method stub - return null; - } - - @Override - public LoadBalancerVO createLoadBalancerRule(CreateLoadBalancerRuleCmd cmd) { - // TODO Auto-generated method stub - return null; - } - - @Override - public boolean updateFirewallRule(FirewallRuleVO fwRule, String oldPrivateIP, String oldPrivatePort) { - // TODO Auto-generated method stub - return false; - } - - @Override - public boolean assignToLoadBalancer(AssignToLoadBalancerRuleCmd cmd) throws NetworkRuleConflictException { - // TODO Auto-generated method stub - return false; - } - - @Override - public boolean removeFromLoadBalancer(RemoveFromLoadBalancerRuleCmd cmd) { - // TODO Auto-generated method stub - return false; - } - - @Override - public boolean deleteLoadBalancerRule(DeleteLoadBalancerRuleCmd cmd) { - // TODO Auto-generated method stub - return false; - } - - @Override - public LoadBalancerVO updateLoadBalancerRule(UpdateLoadBalancerRuleCmd cmd) { - // TODO Auto-generated method stub - return null; - } - - @Override - public RemoteAccessVpnVO createRemoteAccessVpn(CreateRemoteAccessVpnCmd cmd) throws ConcurrentOperationException, InvalidParameterValueException, - PermissionDeniedException { - // TODO Auto-generated method stub - return null; - } - - @Override - public RemoteAccessVpnVO startRemoteAccessVpn(CreateRemoteAccessVpnCmd cmd) throws ConcurrentOperationException, ResourceUnavailableException { - // TODO Auto-generated method stub - return null; - } - - @Override - public boolean destroyRemoteAccessVpn(DeleteRemoteAccessVpnCmd cmd) throws ConcurrentOperationException { - // TODO Auto-generated method stub - return false; - } - - @Override - public VpnUserVO addVpnUser(AddVpnUserCmd cmd) throws ConcurrentOperationException { - // TODO Auto-generated method stub - return null; - } - - @Override - public boolean removeVpnUser(RemoveVpnUserCmd cmd) throws ConcurrentOperationException { - // TODO Auto-generated method stub - return false; - } - - @Override - public FirewallRuleVO createIpForwardingRuleInDb(String ipAddr, Long virtualMachineId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public boolean deletePortForwardingRule(Long id, boolean sysContext) { - // TODO Auto-generated method stub - return false; - } - - @Override - public boolean deleteIpForwardingRule(Long id) { - // TODO Auto-generated method stub - return false; - } } diff --git a/server/src/com/cloud/network/rules/dao/PortForwardingRulesDao.java b/server/src/com/cloud/network/rules/dao/PortForwardingRulesDao.java new file mode 100644 index 00000000000..83db875deaa --- /dev/null +++ b/server/src/com/cloud/network/rules/dao/PortForwardingRulesDao.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.network.rules.dao; + +import java.util.List; + +import com.cloud.network.rules.PortForwardingRuleVO; +import com.cloud.utils.db.GenericDao; +import com.cloud.utils.net.Ip; + +public interface PortForwardingRulesDao extends GenericDao { + List listForApplication(Ip ip); + + /** + * Find all port forwarding rules that have not been revoked. + * + * @param ip ip address + * @return List of PortForwardingRuleVO + */ + List listByIpAndNotRevoked(Ip ip); + + List searchNatRules(Ip ip, Long startIndex, Long pageSize); +} diff --git a/server/src/com/cloud/network/rules/dao/PortForwardingRulesDaoImpl.java b/server/src/com/cloud/network/rules/dao/PortForwardingRulesDaoImpl.java new file mode 100644 index 00000000000..2aaefecb3c2 --- /dev/null +++ b/server/src/com/cloud/network/rules/dao/PortForwardingRulesDaoImpl.java @@ -0,0 +1,93 @@ +/** + * 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.dao; + +import java.util.List; + +import javax.ejb.Local; + +import com.cloud.network.rules.FirewallRule.State; +import com.cloud.network.rules.PortForwardingRuleVO; +import com.cloud.utils.db.Filter; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; +import com.cloud.utils.db.SearchCriteria.Op; +import com.cloud.utils.net.Ip; +import com.cloud.utils.net.NetUtils; + +@Local(value=PortForwardingRulesDao.class) +public class PortForwardingRulesDaoImpl extends GenericDaoBase implements PortForwardingRulesDao { + + protected final SearchBuilder AllFieldsSearch; + protected final SearchBuilder ApplicationSearch; + protected final SearchBuilder ActiveRulesSearch; + + protected PortForwardingRulesDaoImpl() { + super(); + AllFieldsSearch = createSearchBuilder(); + AllFieldsSearch.and("id", AllFieldsSearch.entity().getId(), Op.EQ); + AllFieldsSearch.and("state", AllFieldsSearch.entity().getState(), Op.EQ); + AllFieldsSearch.and("ip", AllFieldsSearch.entity().getSourceIpAddress(), Op.EQ); + AllFieldsSearch.and("proto", AllFieldsSearch.entity().getProtocol(), Op.EQ); + AllFieldsSearch.done(); + + ApplicationSearch = createSearchBuilder(); + ApplicationSearch.and("ip", ApplicationSearch.entity().getSourceIpAddress(), Op.EQ); + ApplicationSearch.and("state", ApplicationSearch.entity().getState(), Op.NEQ); + + ActiveRulesSearch = createSearchBuilder(); + ActiveRulesSearch.and("ip", ActiveRulesSearch.entity().getSourceIpAddress(), Op.EQ); + ActiveRulesSearch.and("state", ActiveRulesSearch.entity().getState(), Op.NEQ); + ActiveRulesSearch.done(); + } + + @Override + public List listForApplication(Ip ip) { + SearchCriteria sc = ApplicationSearch.create(); + sc.setParameters("ip", ip); + sc.setParameters("state", State.Staged); + + return listBy(sc, null); + } + + @Override + public List listByIpAndNotRevoked(Ip ip) { + SearchCriteria sc = ActiveRulesSearch.create(); + sc.setParameters("ip", ip); + sc.setParameters("state", State.Revoke); + + return listBy(sc, null); + } + + @Override + public List searchNatRules(Ip ip, Long startIndex, Long pageSize) { + Filter searchFilter = new Filter(PortForwardingRuleVO.class, "id", true, startIndex, pageSize); + SearchCriteria sc = AllFieldsSearch.create(); + + if (ip != null) { + sc.setParameters("ip", ip); + } + + //search for rules with protocol = nat + sc.setParameters("protocol", NetUtils.NAT_PROTO); + + return listBy(sc, searchFilter); + } + +} diff --git a/server/src/com/cloud/offerings/NetworkOfferingVO.java b/server/src/com/cloud/offerings/NetworkOfferingVO.java index f758a66d658..11b35cbe854 100644 --- a/server/src/com/cloud/offerings/NetworkOfferingVO.java +++ b/server/src/com/cloud/offerings/NetworkOfferingVO.java @@ -80,10 +80,7 @@ public class NetworkOfferingVO implements NetworkOffering { @Column(name="tags") String tags; - - @Column(name="shared") - boolean isShared; - + @Column(name="default") boolean isDefault; @@ -201,15 +198,6 @@ public class NetworkOfferingVO implements NetworkOffering { this.serviceOfferingId = serviceOfferingId; } - @Override - public boolean isShared() { - return isShared; - } - - public void setShared(boolean isShared) { - this.isShared = isShared; - } - @Override public boolean isDefault() { return isDefault; @@ -224,7 +212,7 @@ public class NetworkOfferingVO implements NetworkOffering { this.created = created; } - public NetworkOfferingVO(String name, String displayText, TrafficType trafficType, GuestIpType type, boolean systemOnly, boolean specifyVlan, Integer rateMbps, Integer multicastRateMbps, Integer concurrentConnections, boolean isShared, boolean isDefault) { + public NetworkOfferingVO(String name, String displayText, TrafficType trafficType, GuestIpType type, boolean systemOnly, boolean specifyVlan, Integer rateMbps, Integer multicastRateMbps, Integer concurrentConnections, boolean isDefault) { this.name = name; this.displayText = displayText; this.guestIpType = type; @@ -235,11 +223,10 @@ public class NetworkOfferingVO implements NetworkOffering { this.systemOnly = systemOnly; this.specifyVlan = specifyVlan; this.isDefault = isDefault; - this.isShared = isShared; } public NetworkOfferingVO(ServiceOfferingVO offering) { - this("Network Offering for " + offering.getName(), "Network Offering for " + offering.getDisplayText(), TrafficType.Guest, offering.getGuestIpType(), false, false, offering.getRateMbps(), offering.getMulticastRateMbps(), null, false, false); + this("Network Offering for " + offering.getName(), "Network Offering for " + offering.getDisplayText(), TrafficType.Guest, offering.getGuestIpType(), false, false, offering.getRateMbps(), offering.getMulticastRateMbps(), null, false); this.serviceOfferingId = offering.getId(); } @@ -251,7 +238,7 @@ public class NetworkOfferingVO implements NetworkOffering { * @param type */ public NetworkOfferingVO(String name, TrafficType trafficType, GuestIpType type) { - this(name, "System Offering for " + name, trafficType, type, true, false, null, null, null, false, false); + this(name, "System Offering for " + name, trafficType, type, true, false, null, null, null, false); } @Override diff --git a/server/src/com/cloud/server/ConfigurationServerImpl.java b/server/src/com/cloud/server/ConfigurationServerImpl.java index 866e5b4e4f6..c08ee169207 100644 --- a/server/src/com/cloud/server/ConfigurationServerImpl.java +++ b/server/src/com/cloud/server/ConfigurationServerImpl.java @@ -150,11 +150,11 @@ public class ConfigurationServerImpl implements ConfigurationServer { } // Save Direct Networking service offerings - createServiceOffering(User.UID_SYSTEM, "Small Instance, Direct Networking", 1, 512, 500, "Small Instance, Direct Networking, $0.05 per hour", false, false, false, null); - createServiceOffering(User.UID_SYSTEM, "Medium Instance, Direct Networking", 1, 1024, 1000, "Medium Instance, Direct Networking, $0.10 per hour", false, false, false, null); + createServiceOffering(User.UID_SYSTEM, "Small Instance", 1, 512, 500, "Small Instance, $0.05 per hour", false, false, false, null); + createServiceOffering(User.UID_SYSTEM, "Medium Instance", 1, 1024, 1000, "Medium Instance, $0.10 per hour", false, false, false, null); // Save Virtual Networking service offerings - createServiceOffering(User.UID_SYSTEM, "Small Instance, Virtual Networking", 1, 512, 500, "Small Instance, Virtual Networking, $0.05 per hour", false, false, true, null); - createServiceOffering(User.UID_SYSTEM, "Medium Instance, Virtual Networking", 1, 1024, 1000, "Medium Instance, Virtual Networking, $0.10 per hour", false, false, true, null); + //createServiceOffering(User.UID_SYSTEM, "Small Instance", 1, 512, 500, "Small Instance, Virtual Networking, $0.05 per hour", false, false, true, null); + //createServiceOffering(User.UID_SYSTEM, "Medium Instance", 1, 1024, 1000, "Medium Instance, Virtual Networking, $0.10 per hour", false, false, true, null); // Save default disk offerings createDiskOffering(DomainVO.ROOT_DOMAIN, "Small", "Small Disk, 5 GB", 5, null); createDiskOffering(DomainVO.ROOT_DOMAIN, "Medium", "Medium Disk, 20 GB", 20, null); @@ -647,7 +647,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { 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); diff --git a/server/src/com/cloud/server/Criteria.java b/server/src/com/cloud/server/Criteria.java index 6d41b967be9..74bc4e54b84 100644 --- a/server/src/com/cloud/server/Criteria.java +++ b/server/src/com/cloud/server/Criteria.java @@ -78,6 +78,7 @@ public class Criteria { public static final String NETWORKGROUP = "networkGroup"; public static final String GROUP = "group"; public static final String EMPTY_GROUP = "emptyGroup"; + public static final String NETWORKID = "networkId"; public Criteria(String orderBy, Boolean ascending, Long offset, Long limit) { this.offset = offset; diff --git a/server/src/com/cloud/server/ManagementServer.java b/server/src/com/cloud/server/ManagementServer.java index c5a0034b556..fb9591144c4 100755 --- a/server/src/com/cloud/server/ManagementServer.java +++ b/server/src/com/cloud/server/ManagementServer.java @@ -34,14 +34,11 @@ import com.cloud.exception.InternalErrorException; import com.cloud.exception.InvalidParameterValueException; import com.cloud.host.HostVO; import com.cloud.info.ConsoleProxyInfo; -import com.cloud.network.FirewallRuleVO; import com.cloud.network.IPAddressVO; -import com.cloud.network.LoadBalancerVO; import com.cloud.network.security.NetworkGroupVO; import com.cloud.service.ServiceOfferingVO; import com.cloud.storage.DiskOfferingVO; import com.cloud.storage.GuestOSVO; -import com.cloud.storage.SnapshotPolicyVO; import com.cloud.storage.StoragePoolVO; import com.cloud.storage.StorageStats; import com.cloud.storage.VMTemplateVO; @@ -165,14 +162,6 @@ public interface ManagementServer extends ManagementService { */ boolean attachISOToVM(long vmId, long userId, long isoId, boolean attach, long startEventId); - /** - * Finds a domain router by id - * @param router id - * @return a domainRouter - */ - DomainRouterVO findDomainRouterById(long domainRouterId); - - /** * Retrieves a host by id * @param hostId @@ -331,13 +320,6 @@ public interface ManagementServer extends ManagementService { */ List searchForUserVMs(Criteria c); - /** - * Find a firewall rule by rule id - * @param ruleId - * @return - */ - FirewallRuleVO findForwardingRuleById(Long ruleId); - /** * Find an IP Address VO object by ip address string * @param ipAddress @@ -533,9 +515,6 @@ public interface ManagementServer extends ManagementService { AsyncJobVO findAsyncJobById(long jobId); - LoadBalancerVO findLoadBalancer(Long accountId, String name); - LoadBalancerVO findLoadBalancerById(long loadBalancerId); - String[] getApiConfig(); StoragePoolVO findPoolById(Long id); List searchForStoragePools(Criteria c); diff --git a/server/src/com/cloud/server/ManagementServerImpl.java b/server/src/com/cloud/server/ManagementServerImpl.java index 573153e2b2f..0652385eadd 100755 --- a/server/src/com/cloud/server/ManagementServerImpl.java +++ b/server/src/com/cloud/server/ManagementServerImpl.java @@ -36,17 +36,14 @@ import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.util.ArrayList; -import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; -import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; -import java.util.Set; import java.util.TimeZone; import java.util.UUID; import java.util.concurrent.Executors; @@ -78,8 +75,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.DeployVm2Cmd; import com.cloud.api.commands.ExtractVolumeCmd; import com.cloud.api.commands.GetCloudIdentifierCmd; import com.cloud.api.commands.ListAccountsCmd; @@ -97,10 +92,7 @@ import com.cloud.api.commands.ListGuestOsCategoriesCmd; import com.cloud.api.commands.ListGuestOsCmd; import com.cloud.api.commands.ListHostsCmd; import com.cloud.api.commands.ListHypervisorsCmd; -import com.cloud.api.commands.ListIpForwardingRulesCmd; import com.cloud.api.commands.ListIsosCmd; -import com.cloud.api.commands.ListLoadBalancerRuleInstancesCmd; -import com.cloud.api.commands.ListLoadBalancerRulesCmd; import com.cloud.api.commands.ListPodsByCmd; import com.cloud.api.commands.ListPreallocatedLunsCmd; import com.cloud.api.commands.ListPublicIpAddressesCmd; @@ -126,7 +118,6 @@ import com.cloud.api.commands.StopSystemVmCmd; import com.cloud.api.commands.UpdateDomainCmd; import com.cloud.api.commands.UpdateIsoCmd; import com.cloud.api.commands.UpdateIsoPermissionsCmd; -import com.cloud.api.commands.UpdatePortForwardingRuleCmd; import com.cloud.api.commands.UpdateTemplateCmd; import com.cloud.api.commands.UpdateTemplateOrIsoCmd; import com.cloud.api.commands.UpdateTemplateOrIsoPermissionsCmd; @@ -175,37 +166,26 @@ import com.cloud.event.EventVO; import com.cloud.event.dao.EventDao; import com.cloud.exception.AgentUnavailableException; import com.cloud.exception.CloudAuthenticationException; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientAddressCapacityException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InsufficientStorageCapacityException; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.ManagementServerException; import com.cloud.exception.OperationTimedoutException; 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.host.HostVO; import com.cloud.host.Status; import com.cloud.host.dao.HostDao; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.info.ConsoleProxyInfo; -import com.cloud.network.FirewallRuleVO; import com.cloud.network.IPAddressVO; -import com.cloud.network.LoadBalancerVMMapVO; -import com.cloud.network.LoadBalancerVO; import com.cloud.network.NetworkManager; +import com.cloud.network.NetworkVO; import com.cloud.network.RemoteAccessVpnVO; import com.cloud.network.VpnUserVO; -import com.cloud.network.dao.FirewallRulesDao; import com.cloud.network.dao.IPAddressDao; -import com.cloud.network.dao.LoadBalancerDao; -import com.cloud.network.dao.LoadBalancerVMMapDao; +import com.cloud.network.dao.NetworkDao; import com.cloud.network.dao.RemoteAccessVpnDao; import com.cloud.network.dao.VpnUserDao; -import com.cloud.network.security.NetworkGroupManager; import com.cloud.network.security.NetworkGroupVO; import com.cloud.network.security.dao.NetworkGroupDao; import com.cloud.offering.NetworkOffering; @@ -253,20 +233,16 @@ import com.cloud.user.User; import com.cloud.user.UserAccount; import com.cloud.user.UserAccountVO; import com.cloud.user.UserContext; -import com.cloud.user.UserStatisticsVO; import com.cloud.user.UserVO; import com.cloud.user.dao.AccountDao; import com.cloud.user.dao.UserAccountDao; import com.cloud.user.dao.UserDao; -import com.cloud.user.dao.UserStatisticsDao; -import com.cloud.uservm.UserVm; import com.cloud.utils.EnumUtils; import com.cloud.utils.NumbersUtil; import com.cloud.utils.Pair; import com.cloud.utils.PasswordGenerator; import com.cloud.utils.component.Adapters; import com.cloud.utils.component.ComponentLocator; -import com.cloud.utils.component.Inject; import com.cloud.utils.concurrency.NamedThreadFactory; import com.cloud.utils.db.DB; import com.cloud.utils.db.Filter; @@ -277,17 +253,16 @@ 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.exception.ExecutionException; import com.cloud.utils.net.MacAddress; import com.cloud.utils.net.NetUtils; import com.cloud.vm.ConsoleProxyVO; import com.cloud.vm.DomainRouterVO; import com.cloud.vm.InstanceGroupVMMapVO; import com.cloud.vm.InstanceGroupVO; +import com.cloud.vm.NicVO; import com.cloud.vm.SecondaryStorageVmVO; import com.cloud.vm.State; import com.cloud.vm.UserVmManager; -import com.cloud.vm.UserVmService; import com.cloud.vm.UserVmVO; import com.cloud.vm.VMInstanceVO; import com.cloud.vm.VirtualMachine; @@ -295,6 +270,7 @@ import com.cloud.vm.dao.ConsoleProxyDao; import com.cloud.vm.dao.DomainRouterDao; import com.cloud.vm.dao.InstanceGroupDao; import com.cloud.vm.dao.InstanceGroupVMMapDao; +import com.cloud.vm.dao.NicDao; import com.cloud.vm.dao.SecondaryStorageVmDao; import com.cloud.vm.dao.UserVmDao; import com.cloud.vm.dao.VMInstanceDao; @@ -305,12 +281,9 @@ public class ManagementServerImpl implements ManagementServer { private final AccountManager _accountMgr; private final AgentManager _agentMgr; private final ConfigurationManager _configMgr; - private final FirewallRulesDao _firewallRulesDao; private final NetworkGroupDao _networkSecurityGroupDao; - private final LoadBalancerDao _loadBalancerDao; private final IPAddressDao _publicIpAddressDao; private final DataCenterIpAddressDao _privateIpAddressDao; - private final LoadBalancerVMMapDao _loadBalancerVMMapDao; private final DomainRouterDao _routerDao; private final ConsoleProxyDao _consoleProxyDao; private final ClusterDao _clusterDao; @@ -324,7 +297,6 @@ public class ManagementServerImpl implements ManagementServer { private final UserDao _userDao; private final UserVmDao _userVmDao; private final ConfigurationDao _configDao; - private final NetworkManager _networkMgr; private final UserVmManager _vmMgr; private final ConsoleProxyManager _consoleProxyMgr; private final SecondaryStorageVmManager _secStorageVmMgr; @@ -343,20 +315,18 @@ public class ManagementServerImpl implements ManagementServer { private final StoragePoolDao _poolDao; private final StoragePoolHostDao _poolHostDao; private final StorageManager _storageMgr; - private final UserVmDao _vmDao; + private final NetworkDao _networkDao; + private final NicDao _nicDao; private final Adapters _userAuthenticators; private final HostPodDao _hostPodDao; - private final UserStatisticsDao _userStatsDao; private final VMInstanceDao _vmInstanceDao; private final VolumeDao _volumeDao; private final AlertManager _alertMgr; private final AsyncJobDao _jobDao; private final AsyncJobManager _asyncMgr; private final TemplateManager _tmpltMgr; - private final NetworkGroupManager _networkGroupMgr; private final int _purgeDelay; - private final boolean _directAttachNetworkExternalIpAllocator; private final PreallocatedLunDao _lunDao; private final InstanceGroupDao _vmGroupDao; private final InstanceGroupVMMapDao _groupVMMapDao; @@ -365,7 +335,7 @@ public class ManagementServerImpl implements ManagementServer { private final CertificateDao _certDao; private final RemoteAccessVpnDao _remoteAccessVpnDao; private final VpnUserDao _vpnUsersDao; - @Inject private UserVmService _userVmService; + private final ScheduledExecutorService _executor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("AccountChecker")); private final ScheduledExecutorService _eventExecutor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("EventChecker")); @@ -379,14 +349,11 @@ public class ManagementServerImpl implements ManagementServer { private final int _routerRamSize; private final int _proxyRamSize; private final int _ssRamSize; - private int _maxVolumeSizeInGb; private boolean _useNewNetworking = false; private final Map _availableIdsMap; - private boolean _networkGroupsEnabled = false; - private boolean _isHypervisorSnapshotCapable = false; private String _hashKey = null; @@ -404,21 +371,19 @@ public class ManagementServerImpl implements ManagementServer { _hostPodDao = locator.getDao(HostPodDao.class); _jobDao = locator.getDao(AsyncJobDao.class); _clusterDao = locator.getDao(ClusterDao.class); + _networkDao = locator.getDao(NetworkDao.class); + _nicDao = locator.getDao(NicDao.class); _accountMgr = locator.getManager(AccountManager.class); _agentMgr = locator.getManager(AgentManager.class); _configMgr = locator.getManager(ConfigurationManager.class); - _networkMgr = locator.getManager(NetworkManager.class); _vmMgr = locator.getManager(UserVmManager.class); _consoleProxyMgr = locator.getManager(ConsoleProxyManager.class); _secStorageVmMgr = locator.getManager(SecondaryStorageVmManager.class); _storageMgr = locator.getManager(StorageManager.class); - _firewallRulesDao = locator.getDao(FirewallRulesDao.class); _networkSecurityGroupDao = locator.getDao(NetworkGroupDao.class); - _loadBalancerDao = locator.getDao(LoadBalancerDao.class); _publicIpAddressDao = locator.getDao(IPAddressDao.class); _privateIpAddressDao = locator.getDao(DataCenterIpAddressDao.class); - _loadBalancerVMMapDao = locator.getDao(LoadBalancerVMMapDao.class); _consoleProxyDao = locator.getDao(ConsoleProxyDao.class); _secStorageVmDao = locator.getDao(SecondaryStorageVmDao.class); _userDao = locator.getDao(UserDao.class); @@ -437,7 +402,6 @@ public class ManagementServerImpl implements ManagementServer { _guestOSCategoryDao = locator.getDao(GuestOSCategoryDao.class); _poolDao = locator.getDao(StoragePoolDao.class); _poolHostDao = locator.getDao(StoragePoolHostDao.class); - _vmDao = locator.getDao(UserVmDao.class); _vmGroupDao = locator.getDao(InstanceGroupDao.class); _groupVMMapDao = locator.getDao(InstanceGroupVMMapDao.class); _uploadDao = locator.getDao(UploadDao.class); @@ -445,14 +409,12 @@ public class ManagementServerImpl implements ManagementServer { _remoteAccessVpnDao = locator.getDao(RemoteAccessVpnDao.class); _vpnUsersDao = locator.getDao(VpnUserDao.class); _configs = _configDao.getConfiguration(); - _userStatsDao = locator.getDao(UserStatisticsDao.class); _vmInstanceDao = locator.getDao(VMInstanceDao.class); _volumeDao = locator.getDao(VolumeDao.class); _alertMgr = locator.getManager(AlertManager.class); _asyncMgr = locator.getManager(AsyncJobManager.class); _tmpltMgr = locator.getManager(TemplateManager.class); - _networkGroupMgr = locator.getManager(NetworkGroupManager.class); - _uploadMonitor = locator.getManager(UploadMonitor.class); + _uploadMonitor = locator.getManager(UploadMonitor.class); _userAuthenticators = locator.getAdapters(UserAuthenticator.class); if (_userAuthenticators == null || !_userAuthenticators.isSet()) { @@ -476,9 +438,6 @@ public class ManagementServerImpl implements ManagementServer { _proxyRamSize = NumbersUtil.parseInt(_configs.get("consoleproxy.ram.size"), ConsoleProxyManager.DEFAULT_PROXY_VM_RAMSIZE); _ssRamSize = NumbersUtil.parseInt(_configs.get("secstorage.ram.size"), SecondaryStorageVmManager.DEFAULT_SS_VM_RAMSIZE); - _directAttachNetworkExternalIpAllocator = - Boolean.parseBoolean(_configs.get("direct.attach.network.externalIpAllocator.enabled")); - _statsCollector = StatsCollector.getInstance(_configs); _executor.scheduleAtFixedRate(new AccountCleanupTask(), cleanup, cleanup, TimeUnit.SECONDS); @@ -492,15 +451,6 @@ public class ManagementServerImpl implements ManagementServer { for (String id: availableIds) { _availableIdsMap.put(id, true); } - String enabled =_configDao.getValue("direct.attach.network.groups.enabled"); - if ("true".equalsIgnoreCase(enabled)) { - _networkGroupsEnabled = true; - } - - String maxVolumeSizeInGbString = _configDao.getValue("max.volume.size.gb"); - int maxVolumeSizeGb = NumbersUtil.parseInt(maxVolumeSizeInGbString, (2000));//2000 gb - _maxVolumeSizeInGb = maxVolumeSizeGb; - _useNewNetworking = Boolean.parseBoolean(_configs.get("use.new.networking")); } @@ -775,24 +725,29 @@ public class ManagementServerImpl implements ManagementServer { public List listPublicIpAddressesBy(Long accountId, boolean allocatedOnly, Long zoneId, Long vlanDbId) { SearchCriteria sc = _publicIpAddressDao.createSearchCriteria(); - if (accountId != null) + if (accountId != null) { sc.addAnd("accountId", SearchCriteria.Op.EQ, accountId); - if (zoneId != null) + } + if (zoneId != null) { sc.addAnd("dataCenterId", SearchCriteria.Op.EQ, zoneId); - if (vlanDbId != null) + } + if (vlanDbId != null) { sc.addAnd("vlanDbId", SearchCriteria.Op.EQ, vlanDbId); - if (allocatedOnly) + } + if (allocatedOnly) { sc.addAnd("allocated", SearchCriteria.Op.NNULL); + } return _publicIpAddressDao.search(sc, null); } @Override public List listPrivateIpAddressesBy(Long podId, Long zoneId) { - if (podId != null && zoneId != null) + if (podId != null && zoneId != null) { return _privateIpAddressDao.listByPodIdDcId(podId.longValue(), zoneId.longValue()); - else + } else { return new ArrayList(); + } } @Override @@ -835,511 +790,6 @@ public class ManagementServerImpl implements ManagementServer { return success; } - private boolean validPassword(String password) { - for (int i = 0; i < password.length(); i++) { - if (password.charAt(i) == ' ') { - return false; - } - } - return true; - } - - private UserVm deployVirtualMachineImpl(long userId, long accountId, long dataCenterId, long serviceOfferingId, VMTemplateVO template, Long diskOfferingId, - String domain, String password, String displayName, String group, String userData, String [] networkGroups, long startEventId, long size) throws ResourceAllocationException, - InsufficientStorageCapacityException, ExecutionException, StorageUnavailableException, ConcurrentOperationException { - - EventUtils.saveStartedEvent(userId, accountId, EventTypes.EVENT_VM_CREATE, "Deploying Vm", startEventId); - - AccountVO account = _accountDao.findById(accountId); - DataCenterVO dc = _dcDao.findById(dataCenterId); - ServiceOfferingVO offering = _offeringsDao.findById(serviceOfferingId); - - // Make sure a valid template ID was specified - if (template == null) { - throw new InvalidParameterValueException("Please specify a valid template or ISO ID."); - } - - long templateId = template.getId(); - - byte [] decodedUserData = null; - if (userData != null) { - if (userData.length() >= 2* UserVmManager.MAX_USER_DATA_LENGTH_BYTES) { - throw new InvalidParameterValueException("User data is too long"); - } - decodedUserData = org.apache.commons.codec.binary.Base64.decodeBase64(userData.getBytes()); - if (decodedUserData.length > UserVmManager.MAX_USER_DATA_LENGTH_BYTES){ - throw new InvalidParameterValueException("User data is too long"); - } - - } - - boolean isIso = Storage.ImageFormat.ISO.equals(template.getFormat()); - DiskOfferingVO diskOffering = _diskOfferingDao.findById(diskOfferingId); - - // TODO: Checks such as is the user allowed to use the template and purchase the service offering id. - - if (domain == null) { - domain = "v" + Long.toHexString(accountId) + _domain; - } - - // Check that the password was passed in and is valid - if (!template.getEnablePassword()) { - password = "saved_password"; - } - - if (password == null || password.equals("") || (!validPassword(password))) { - throw new InvalidParameterValueException("A valid password for this virtual machine was not provided."); - } - List networkGroupVOs = new ArrayList(); - if (networkGroups != null) { - for (String groupName: networkGroups) { - NetworkGroupVO networkGroupVO = _networkSecurityGroupDao.findByAccountAndName(accountId, groupName); - if (networkGroupVO == null) { - throw new InvalidParameterValueException("Network Group " + groupName + " does not exist"); - } - networkGroupVOs.add(networkGroupVO); - } - } - - UserStatisticsVO stats = _userStatsDao.findBy(account.getId(), dataCenterId); - if (stats == null) { - stats = new UserStatisticsVO(account.getId(), dataCenterId); - _userStatsDao.persist(stats); - } - - Long vmId = _vmDao.getNextInSequence(Long.class, "id"); - - // check if we are within context of async-execution - AsyncJobExecutor asyncExecutor = BaseAsyncJobExecutor.getCurrentExecutor(); - if (asyncExecutor != null) { - AsyncJobVO job = asyncExecutor.getJob(); - - if (s_logger.isInfoEnabled()) - s_logger.info("DeployVM acquired a new instance " + vmId + ", update async job-" + job.getId() + " progress status"); - - _asyncMgr.updateAsyncJobAttachment(job.getId(), "vm_instance", vmId); - _asyncMgr.updateAsyncJobStatus(job.getId(), BaseCmd.PROGRESS_INSTANCE_CREATED, vmId); - } - - HashMap avoids = new HashMap(); - - // Pod allocator now allocate VM based on a reservation style allocation, disable retry here for now - for (int retry = 0; retry < 1; retry++) { - String externalIp = null; - UserVmVO created = null; - - ArrayList a = new ArrayList(avoids.values()); - if (_directAttachNetworkExternalIpAllocator) { - try { - created = _vmMgr.createDirectlyAttachedVMExternal(vmId, userId, account, dc, offering, template, diskOffering, displayName, userData, a, networkGroupVOs, startEventId, size); - } catch (ResourceAllocationException rae) { - throw rae; - } - } else { - if (offering.getGuestIpType() == NetworkOffering.GuestIpType.Virtualized) { - try { - externalIp = _networkMgr.assignSourceNatIpAddress(account, dc, domain, offering, startEventId, template.getHypervisorType()); - } catch (ResourceAllocationException rae) { - throw rae; - } - - if (externalIp == null) { - throw new CloudRuntimeException("Unable to allocate a source nat ip address"); - } - - if (s_logger.isDebugEnabled()) { - s_logger.debug("Source Nat acquired: " + externalIp); - } - - try { - created = _vmMgr.createVirtualMachine(vmId, userId, account, dc, offering, template, diskOffering, displayName, userData, a, startEventId, size); - } catch (ResourceAllocationException rae) { - throw rae; - } - } else { - try { - created = _vmMgr.createDirectlyAttachedVM(vmId, userId, account, dc, offering, template, diskOffering, displayName, userData, a, networkGroupVOs, startEventId, size); - } catch (ResourceAllocationException rae) { - throw rae; - } - } - } - - //assign vm to the group - try{ - if (group != null) { - boolean addToGroup = _vmMgr.addInstanceToGroup(Long.valueOf(vmId), group); - if (!addToGroup) { - throw new CloudRuntimeException("Unable to assing Vm to the group " + group); - } - } - } catch (Exception ex) { - throw new CloudRuntimeException("Unable to assing Vm to the group " + group); - } - - - if (created == null) { - throw new CloudRuntimeException("Unable to create VM for account (" + accountId + "): " + account.getAccountName()); - } - - if (s_logger.isDebugEnabled()) { - s_logger.debug("VM created: " + created.getId() + "-" + created.getHostName()); - } - boolean executionExceptionFlag = false; - boolean storageUnavailableExceptionFlag = false; - boolean concurrentOperationExceptionFlag = false; - String executionExceptionMsg= ""; - String storageUnavailableExceptionMsg = ""; - String concurrentOperationExceptionMsg = ""; - UserVmVO started = null; - - if (isIso) - { - Pair isoPath = _storageMgr.getAbsoluteIsoPath(templateId, dataCenterId); - if (isoPath == null) { - s_logger.warn("Unable to get absolute path of the iso"); - throw new CloudRuntimeException("Unable to get absolute path of the iso"); - } - try - { - started = _vmMgr.startVirtualMachine(userId, created.getId(), password, isoPath.first(), startEventId); - } - catch (ExecutionException e) - { - executionExceptionFlag = true; - executionExceptionMsg = e.getMessage(); - } - catch (StorageUnavailableException e) - { - storageUnavailableExceptionFlag = true; - storageUnavailableExceptionMsg = e.getMessage(); - } - catch (ConcurrentOperationException e) - { - concurrentOperationExceptionFlag = true; - concurrentOperationExceptionMsg = e.getMessage(); - } - } - else - { - try - { - started = _vmMgr.startVirtualMachine(userId, created.getId(), password, null, startEventId); - } - catch (ExecutionException e) - { - executionExceptionFlag = true; - executionExceptionMsg = e.getMessage(); - } - catch (StorageUnavailableException e) - { - storageUnavailableExceptionFlag = true; - storageUnavailableExceptionMsg = e.getMessage(); - } - catch (ConcurrentOperationException e) - { - concurrentOperationExceptionFlag = true; - concurrentOperationExceptionMsg = e.getMessage(); - } - } - - if (started == null) { - List> disks = _storageMgr.isStoredOn(created); - // NOTE: We now destroy a VM if the deploy process fails at any step. We now - // have a lazy delete so there is still some time to figure out what's wrong. - _vmMgr.destroyVirtualMachine(userId, created.getId()); - - boolean retryCreate = true; - for (Pair disk : disks) { - if (disk.second().isLocal()) { - avoids.put(disk.second().getId(), disk.second()); - } else { - retryCreate = false; - } - } - - if (retryCreate) { - continue; - } else if(executionExceptionFlag){ - throw new ExecutionException(executionExceptionMsg); - } else if (storageUnavailableExceptionFlag){ - throw new StorageUnavailableException(storageUnavailableExceptionMsg); - }else if (concurrentOperationExceptionFlag){ - throw new ConcurrentOperationException(concurrentOperationExceptionMsg); - } - else{ - throw new CloudRuntimeException("Unable to start the VM " + created.getId() + "-" + created.getHostName()); - } - - } else { - if (isIso) { - started.setIsoId(templateId); - _userVmDao.update(started.getId(), started); - started = _userVmDao.findById(started.getId()); - } - - try { - _configMgr.associateIpAddressListToAccount(userId, accountId, dc.getId(),null); - } catch (InsufficientAddressCapacityException e) { - s_logger.debug("Unable to assign public IP address pool: " +e.getMessage()); - } - } - if (s_logger.isDebugEnabled()) { - s_logger.debug("VM started: " + started.getId() + "-" + started.getHostName()); - } - return started; - } - - return null; - } - - @Override - public UserVm deployVirtualMachine(DeployVMCmd cmd, String password) throws ResourceAllocationException, - ExecutionException, - ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException { - if (_useNewNetworking) { - UserVm vm = _userVmService.createVirtualMachine(cmd); - if (vm == null) { - return null; - } - - DeployVm2Cmd cmd2 = new DeployVm2Cmd(); - cmd2.setId(vm.getId()); - vm = _userVmService.startVirtualMachine(cmd2); - return vm; - } - Account ctxAccount = UserContext.current().getAccount(); - Long userId = UserContext.current().getUserId(); - String accountName = cmd.getAccountName(); - Long domainId = cmd.getDomainId(); - Long accountId = null; - long dataCenterId = cmd.getZoneId(); - long serviceOfferingId = cmd.getServiceOfferingId(); - long templateId = cmd.getTemplateId(); - Long diskOfferingId = cmd.getDiskOfferingId(); - String domain = null; // FIXME: this was hardcoded to null in DeployVMCmd in the old framework, do we need it? - String displayName = cmd.getDisplayName(); - String group = cmd.getGroup(); - String userData = cmd.getUserData(); - String[] networkGroups = null; - Long sizeObj = cmd.getSize(); - long size = (sizeObj == null) ? 0 : sizeObj; - Account userAccount = null; - - DataCenterVO dc = _dcDao.findById(dataCenterId); - if (dc == null) { - throw new InvalidParameterValueException("Unable to find zone: " + dataCenterId); - } - - if ((ctxAccount == null) || isAdmin(ctxAccount.getType())) { - if (domainId != null) { - if ((ctxAccount != null) && !_domainDao.isChildDomain(ctxAccount.getDomainId(), domainId)) { - throw new PermissionDeniedException("Failed to deploy VM, invalid domain id (" + domainId + ") given."); - } - if (accountName != null) { - userAccount = _accountDao.findActiveAccount(accountName, domainId); - if (userAccount == null) { - throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain " + domainId); - } - accountId = userAccount.getId(); - } - } else { - accountId = ((ctxAccount != null) ? ctxAccount.getId() : null); - } - } else { - accountId = ctxAccount.getId(); - } - - if (accountId == null) { - throw new InvalidParameterValueException("No valid account specified for deploying a virtual machine."); - } - - if(domainId == null){ - domainId = dc.getDomainId(); //get the domain id from zone - } - - if(domainId == null){ - //do nothing (public zone case) - } - else{ - if(userAccount != null){ - _configMgr.checkAccess(userAccount, dc);//user deploying his own vm - }else{ - _configMgr.checkAccess(ctxAccount, dc); - } - } - - List netGrpList = cmd.getNetworkGroupList(); - if ((netGrpList != null) && !netGrpList.isEmpty()) { - networkGroups = netGrpList.toArray(new String[netGrpList.size()]); - } - - AccountVO account = _accountDao.findById(accountId); - if (account == null) { - throw new InvalidParameterValueException("Unable to find account: " + accountId); - } - - ServiceOfferingVO offering = _offeringsDao.findById(serviceOfferingId); - if (offering == null) { - throw new InvalidParameterValueException("Unable to find service offering: " + serviceOfferingId); - } - - if(offering.getDomainId() == null){ - //do nothing as offering is public - }else{ - if(userAccount != null){ - _configMgr.checkServiceOfferingAccess(userAccount, offering);//user deploying his own vm - }else{ - _configMgr.checkServiceOfferingAccess(ctxAccount, offering); - } - } - - VMTemplateVO template = _templateDao.findById(templateId); - // Make sure a valid template ID was specified - if (template == null) { - throw new InvalidParameterValueException("Please specify a valid template or ISO ID."); - } - - boolean isIso = Storage.ImageFormat.ISO.equals(template.getFormat()); - - if (isIso && !template.isBootable()) { - throw new InvalidParameterValueException("Please specify a bootable ISO."); - } - - // If the template represents an ISO, a disk offering must be passed in, and will be used to create the root disk - // Else, a disk offering is optional, and if present will be used to create the data disk - DiskOfferingVO diskOffering = null; - - if (diskOfferingId != null) { - diskOffering = _diskOfferingDao.findById(diskOfferingId); - } - - if (isIso && diskOffering == null) { - throw new InvalidParameterValueException("Please specify a valid disk offering ID."); - } - - if(diskOffering != null){ - if(diskOffering.getDomainId() == null){ - //do nothing as offering is public - }else{ - if(userAccount != null){ - _configMgr.checkDiskOfferingAccess(userAccount, diskOffering);//user deploying his own vm - }else{ - _configMgr.checkDiskOfferingAccess(ctxAccount, diskOffering); - } - } - } - - if (isIso) { - /*iso template doesn;t have hypervisor type, temporarily set it's type as user specified, pass it to storage allocator */ - template.setHypervisorType(HypervisorType.getType(cmd.getHypervisor())); - } - - //if it is a custom disk offering,AND the size passed in here is <= 0; error out - if(diskOffering != null && diskOffering.isCustomized() && size <= 0){ - throw new InvalidParameterValueException("Please specify a valid disk size for VM creation; custom disk offering has no size set"); - } - - if(diskOffering != null && diskOffering.isCustomized() && size > _maxVolumeSizeInGb){ - throw new InvalidParameterValueException("Please specify a valid disk size for VM creation; custom disk offering max size is:"+_maxVolumeSizeInGb); - } - - // validate that the template is usable by the account - if (!template.isPublicTemplate()) { - Long templateOwner = template.getAccountId(); - if (!BaseCmd.isAdmin(account.getType()) && ((templateOwner == null) || (templateOwner.longValue() != accountId))) { - // since the current account is not the owner of the template, check the launch permissions table to see if the - // account can launch a VM from this template - LaunchPermissionVO permission = _launchPermissionDao.findByTemplateAndAccount(templateId, account.getId()); - if (permission == null) { - throw new PermissionDeniedException("Account " + account.getAccountName() + " does not have permission to launch instances from template " + template.getName()); - } - } - } - - - - byte [] decodedUserData = null; - if (userData != null) { - if (userData.length() >= 2* UserVmManager.MAX_USER_DATA_LENGTH_BYTES) { - throw new InvalidParameterValueException("User data is too long"); - } - decodedUserData = org.apache.commons.codec.binary.Base64.decodeBase64(userData.getBytes()); - if (decodedUserData.length > UserVmManager.MAX_USER_DATA_LENGTH_BYTES){ - throw new InvalidParameterValueException("User data is too long"); - } - if (decodedUserData.length < 1) { - throw new InvalidParameterValueException("User data is too short"); - } - - } - if (offering.getGuestIpType() != NetworkOffering.GuestIpType.Virtualized) { - _networkGroupMgr.createDefaultNetworkGroup(accountId); - } - - if (networkGroups != null) { - if (offering.getGuestIpType() == NetworkOffering.GuestIpType.Virtualized) { - throw new InvalidParameterValueException("Network groups are not compatible with service offering " + offering.getName()); - } - Set nameSet = new HashSet(); //handle duplicate names -- allowed - nameSet.addAll(Arrays.asList(networkGroups)); - nameSet.add(NetworkGroupManager.DEFAULT_GROUP_NAME); - networkGroups = nameSet.toArray(new String[nameSet.size()]); - List networkGroupVOs = _networkSecurityGroupDao.findByAccountAndNames(accountId, networkGroups); - if (networkGroupVOs.size() != nameSet.size()) { - throw new InvalidParameterValueException("Some network group names do not exist"); - } - } else { //create a default group if necessary - if (offering.getGuestIpType() != NetworkOffering.GuestIpType.Virtualized && _networkGroupsEnabled) { - networkGroups = new String[]{NetworkGroupManager.DEFAULT_GROUP_NAME}; - } - } - - Long eventId = cmd.getStartEventId(); - try { - return deployVirtualMachineImpl(userId, accountId, dataCenterId, serviceOfferingId, template, diskOfferingId, domain, password, displayName, group, userData, networkGroups, eventId, (1L*size*1024));//this api expects size in MB - } catch (ResourceAllocationException e) { - if(s_logger.isDebugEnabled()) - s_logger.debug("Unable to deploy VM: " + e.getMessage()); - EventUtils.saveEvent(userId, accountId, EventVO.LEVEL_ERROR, EventTypes.EVENT_VM_CREATE, "Unable to deploy VM: VM_INSUFFICIENT_CAPACITY", null, eventId); - throw e; - } catch (ExecutionException e) { - if(s_logger.isDebugEnabled()) - s_logger.debug("Unable to deploy VM: " + e.getMessage()); - EventUtils.saveEvent(userId, accountId, EventVO.LEVEL_ERROR, EventTypes.EVENT_VM_CREATE, "Unable to deploy VM: VM_HOST_LICENSE_EXPIRED", null, eventId); - throw e; - } catch (InvalidParameterValueException e) { - if(s_logger.isDebugEnabled()) - s_logger.debug("Unable to deploy VM: " + e.getMessage()); - EventUtils.saveEvent(userId, accountId, EventVO.LEVEL_ERROR, EventTypes.EVENT_VM_CREATE, "Unable to deploy VM: VM_INVALID_PARAM_ERROR", null, eventId); - throw e; - } catch (InsufficientStorageCapacityException e) { - if(s_logger.isDebugEnabled()) - s_logger.debug("Unable to deploy VM: " + e.getMessage()); - EventUtils.saveEvent(userId, accountId, EventVO.LEVEL_ERROR, EventTypes.EVENT_VM_CREATE, "Unable to deploy VM: VM_INSUFFICIENT_CAPACITY", null, eventId); - throw e; - } catch (PermissionDeniedException e) { - if(s_logger.isDebugEnabled()) - s_logger.debug("Unable to deploy VM: " + e.getMessage()); - EventUtils.saveEvent(userId, accountId, EventVO.LEVEL_ERROR, EventTypes.EVENT_VM_CREATE, "Unable to deploy VM: ACCOUNT_ERROR", null, eventId); - throw e; - } catch (ConcurrentOperationException e) { - if(s_logger.isDebugEnabled()) - s_logger.debug("Unable to deploy VM: " + e.getMessage()); - EventUtils.saveEvent(userId, accountId, EventVO.LEVEL_ERROR, EventTypes.EVENT_VM_CREATE, "Unable to deploy VM: INTERNAL_ERROR", null, eventId); - throw e; - } catch(Exception e) { - s_logger.warn("Unable to deploy VM : " + e.getMessage(), e); - EventUtils.saveEvent(userId, accountId, EventVO.LEVEL_ERROR, EventTypes.EVENT_VM_CREATE, "Unable to deploy VM: INTERNAL_ERROR", null, eventId); - throw new CloudRuntimeException("Unable to deploy VM : " + e.getMessage()); - } - } - - @Override - public DomainRouterVO findDomainRouterById(long domainRouterId) { - return _routerDao.findById(domainRouterId); - } - @Override public List listDataCenters(ListZonesByCmd cmd) { Account account = UserContext.current().getAccount(); @@ -1363,10 +813,11 @@ public class ManagementServerImpl implements ManagementServer { { while(true){ dcs.addAll(_dcDao.findZonesByDomainId(domainRecord.getId())); - if(domainRecord.getParent() != null) - domainRecord = _domainDao.findById(domainRecord.getParent()); - else - break; + if(domainRecord.getParent() != null) { + domainRecord = _domainDao.findById(domainRecord.getParent()); + } else { + break; + } } } //add all public zones too @@ -1381,10 +832,11 @@ public class ManagementServerImpl implements ManagementServer { DomainVO localRecord = domainRecord; while(true){ dcs.addAll(_dcDao.findZonesByDomainId(localRecord.getId())); - if(localRecord.getParent() != null) - localRecord = _domainDao.findById(localRecord.getParent()); - else - break; + if(localRecord.getParent() != null) { + localRecord = _domainDao.findById(localRecord.getParent()); + } else { + break; + } } } //this covers till leaf @@ -1419,8 +871,9 @@ public class ManagementServerImpl implements ManagementServer { break; } } - if (!found) + if (!found) { iter.remove(); + } } } } @@ -1607,20 +1060,24 @@ public class ManagementServerImpl implements ManagementServer { private boolean isPermissible(Long accountDomainId, Long offeringDomainId){ if(accountDomainId == offeringDomainId) - return true; // account and service offering in same domain + { + return true; // account and service offering in same domain + } DomainVO domainRecord = _domainDao.findById(accountDomainId); if(domainRecord != null){ while(true){ - if(domainRecord.getId() == offeringDomainId) - return true; + if(domainRecord.getId() == offeringDomainId) { + return true; + } //try and move on to the next domain - if(domainRecord.getParent() != null) - domainRecord = _domainDao.findById(domainRecord.getParent()); - else - break; + if(domainRecord.getParent() != null) { + domainRecord = _domainDao.findById(domainRecord.getParent()); + } else { + break; + } } } @@ -1762,10 +1219,12 @@ public class ManagementServerImpl implements ManagementServer { sol.addAll(_offeringsDao.search(sc, searchFilter)); //try and move on to the next domain - if(domainRecord.getParent() != null) - domainRecord = _domainDao.findById(domainRecord.getParent()); - else - break;//now we got all the offerings for this user/dom adm + if(domainRecord.getParent() != null) { + domainRecord = _domainDao.findById(domainRecord.getParent()); + } + else { + break;//now we got all the offerings for this user/dom adm + } } }else{ s_logger.error("Could not find the domainId for account:"+account.getAccountName()); @@ -1773,8 +1232,9 @@ public class ManagementServerImpl implements ManagementServer { } //add all the public offerings to the sol list before returning - if(includePublicOfferings) - sol.addAll(_offeringsDao.findPublicServiceOfferings()); + if(includePublicOfferings) { + sol.addAll(_offeringsDao.findPublicServiceOfferings()); + } return sol; } @@ -2235,8 +1695,9 @@ public class ManagementServerImpl implements ManagementServer { @Override public Account findAccountByName(String accountName, Long domainId) { - if (domainId == null) + if (domainId == null) { domainId = DomainVO.ROOT_DOMAIN; + } return _accountDao.findAccount(accountName, domainId); } @@ -2338,8 +1799,8 @@ public class ManagementServerImpl implements ManagementServer { @Override public Account findAccountByIpAddress(String ipAddress) { IPAddressVO address = _publicIpAddressDao.findById(ipAddress); - if ((address != null) && (address.getAccountId() != null)) { - return _accountDao.findById(address.getAccountId()); + if ((address != null) && (address.getAllocatedToAccountId() != null)) { + return _accountDao.findById(address.getAllocatedToAccountId()); } return null; } @@ -2347,8 +1808,9 @@ public class ManagementServerImpl implements ManagementServer { @Override public boolean deleteLimit(Long limitId) { // A limit ID must be passed in - if (limitId == null) + if (limitId == null) { return false; + } return _resourceLimitDao.expunge(limitId); } @@ -2538,140 +2000,7 @@ public class ManagementServerImpl implements ManagementServer { public VMTemplateVO findTemplateById(long templateId) { return _templateDao.findById(templateId); } - - @Override - public List searchForIpForwardingRules(ListIpForwardingRulesCmd cmd){ - //Note:: - //The following was decided after discussing with Will - //ListIpForwardingRules with no params lists the rules for that user ; with a listAll() for admin - //ListIpForwardingRules with accountName and domainId lists the rule for that account (provided the executing user has the right perms) - //ListIpForwardingRules with ipAddress lists the rule for that ip address (provided the executing user has the right perms) - - String ipAddress = cmd.getPublicIpAddress(); - String accountName = cmd.getAccountName(); - Long domainId = cmd.getDomainId(); - Account account = null; - - if((accountName != null && domainId == null) || (accountName == null && domainId != null)){ - throw new ServerApiException(BaseCmd.PARAM_ERROR, "Account name and domain id both have to be passed as a tuple"); - } - - if(accountName != null && domainId != null && ipAddress != null){ - throw new ServerApiException(BaseCmd.PARAM_ERROR, "Either Account name and domain id both have to be passed as a tuple; or the ip address has to be passed whilst searching"); - } - - //account and domainId both provided case - if(accountName != null && domainId != null){ - account = _accountDao.findAccount(accountName, domainId); - if(account == null) - throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, "Specified account for domainId:"+domainId+" account name:"+accountName+" doesn't exist"); - else{ - //get the ctxaccount to see if he has permissions - Account ctxAccount = UserContext.current().getAccount(); - - if(!isChildDomain(ctxAccount.getDomainId(), account.getDomainId())){ - throw new PermissionDeniedException("Unable to list ip forwarding rules for address " + ipAddress + ", permission denied for the executing account: " + ctxAccount.getId()+" to view rules for account: "+account.getId()); - } - - Filter searchFilter = new Filter(FirewallRuleVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal()); - SearchBuilder sb = _firewallRulesDao.createSearchBuilder(); - - SearchBuilder sb1 = _publicIpAddressDao.createSearchBuilder(); - sb1.and("accountId", sb1.entity().getAccountId(), SearchCriteria.Op.EQ); - sb1.and("oneToOneNat", sb1.entity().isOneToOneNat(), SearchCriteria.Op.EQ); - sb.join("sb1", sb1, sb.entity().getPublicIpAddress(),sb1.entity().getAddress(), JoinBuilder.JoinType.INNER); - - SearchCriteria sc = sb.create(); - sc.setJoinParameters("sb1","oneToOneNat", new Long(1)); - sc.setJoinParameters("sb1", "accountId", account.getId()); - - return _firewallRulesDao.search(sc, searchFilter); - } - } - if(account == null){ - account = UserContext.current().getAccount();//use user context - } - - if(account == null || account.getType() == Account.ACCOUNT_TYPE_ADMIN){ - return searchIpForwardingRulesInternal(ipAddress, cmd, null, Account.ACCOUNT_TYPE_ADMIN); - } - - if((account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN)){ - if(ipAddress != null){ - IPAddressVO ipAddressVO = _publicIpAddressDao.findById(ipAddress); - if (ipAddressVO == null) { - throw new InvalidParameterValueException("Unable to find IP address " + ipAddress); - }else{ - //check permissions - Account addrOwner = _accountDao.findById(ipAddressVO.getAccountId()); - if ((addrOwner != null) && !_domainDao.isChildDomain(account.getDomainId(), addrOwner.getDomainId())) { - throw new PermissionDeniedException("Unable to list ip forwarding rule for address " + ipAddress + ", permission denied for account " + account.getId()); - }else{ - return searchIpForwardingRulesInternal(ipAddress, cmd, null, Account.ACCOUNT_TYPE_DOMAIN_ADMIN); - } - } - }else{ - //need to list all rules visible to the domain admin - //join with the ip_address table where account_id = user's account id - return searchIpForwardingRulesInternal(ipAddress, cmd, account.getId(), Account.ACCOUNT_TYPE_DOMAIN_ADMIN); - } - } - - if(account.getType() == Account.ACCOUNT_TYPE_NORMAL){ - if(ipAddress != null){ - IPAddressVO ipAddressVO = _publicIpAddressDao.findById(ipAddress); - if (ipAddressVO == null) { - throw new InvalidParameterValueException("Unable to find IP address " + ipAddress); - }else{ - //check permissions - if ((ipAddressVO.getAccountId() == null) || (account.getId() != ipAddressVO.getAccountId().longValue())) { - throw new PermissionDeniedException("Unable to list ip forwarding rule for address " + ipAddress + ", permission denied for account " + account.getId()); - }else{ - return searchIpForwardingRulesInternal(ipAddress, cmd, null, Account.ACCOUNT_TYPE_NORMAL); - } - } - }else{ - //need to list all rules visible to the user - //join with the ip_address table where account_id = user's account id - return searchIpForwardingRulesInternal(ipAddress, cmd, account.getId(), Account.ACCOUNT_TYPE_NORMAL); - } - } - - return new ArrayList(); - } - - private List searchIpForwardingRulesInternal(String ipAddress, ListIpForwardingRulesCmd cmd, Long accountId, short accountType){ - Filter searchFilter = new Filter(FirewallRuleVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal()); - if(accountId == null){ - SearchCriteria sc = _firewallRulesDao.createSearchCriteria(); - if (ipAddress != null) { - sc.addAnd("publicIpAddress", SearchCriteria.Op.EQ, ipAddress); - } - //search for rules with protocol = nat - sc.addAnd("protocol", SearchCriteria.Op.EQ, NetUtils.NAT_PROTO); - return _firewallRulesDao.search(sc, searchFilter); - - }else{ - //accountId and accountType both given - if((accountType == Account.ACCOUNT_TYPE_NORMAL) || (accountType == Account.ACCOUNT_TYPE_DOMAIN_ADMIN)){ - SearchBuilder sb = _firewallRulesDao.createSearchBuilder(); - - SearchBuilder sb1 = _publicIpAddressDao.createSearchBuilder(); - sb1.and("accountId", sb1.entity().getAccountId(), SearchCriteria.Op.EQ); - sb1.and("oneToOneNat", sb1.entity().isOneToOneNat(), SearchCriteria.Op.EQ); - sb.join("sb1", sb1, sb.entity().getPublicIpAddress(),sb1.entity().getAddress(), JoinBuilder.JoinType.INNER); - - SearchCriteria sc = sb.create(); - sc.setJoinParameters("sb1","oneToOneNat", new Long(1)); - sc.setJoinParameters("sb1", "accountId", accountId); - - return _firewallRulesDao.search(sc, searchFilter); - } - } - - return new ArrayList(); - } @Override public List searchForUserVMs(ListVMsCmd cmd) throws InvalidParameterValueException, PermissionDeniedException { @@ -2714,6 +2043,7 @@ public class ManagementServerImpl implements ManagementServer { c.addCriteria(Criteria.DATACENTERID, cmd.getZoneId()); c.addCriteria(Criteria.GROUPID, cmd.getGroupId()); c.addCriteria(Criteria.FOR_VIRTUAL_NETWORK, cmd.getForVirtualNetwork()); + c.addCriteria(Criteria.NETWORKID, cmd.getNetworkId()); if (path != null) { c.addCriteria(Criteria.PATH, path); @@ -2759,6 +2089,7 @@ public class ManagementServerImpl implements ManagementServer { Object groupId = c.getCriteria(Criteria.GROUPID); Object useVirtualNetwork = c.getCriteria(Criteria.FOR_VIRTUAL_NETWORK); Object path = c.getCriteria(Criteria.PATH); + Object networkId = c.getCriteria(Criteria.NETWORKID); sb.and("displayName", sb.entity().getDisplayName(), SearchCriteria.Op.LIKE); sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); @@ -2792,6 +2123,17 @@ public class ManagementServerImpl implements ManagementServer { sb.join("groupSearch", groupSearch, sb.entity().getId(), groupSearch.entity().getInstanceId(), JoinBuilder.JoinType.INNER); } + if (networkId != null) { + SearchBuilder nicSearch = _nicDao.createSearchBuilder(); + nicSearch.and("networkId", nicSearch.entity().getNetworkId(), SearchCriteria.Op.EQ); + + SearchBuilder networkSearch = _networkDao.createSearchBuilder(); + networkSearch.and("networkId", networkSearch.entity().getId(), SearchCriteria.Op.EQ); + nicSearch.join("networkSearch", networkSearch, nicSearch.entity().getNetworkId(), networkSearch.entity().getId(), JoinBuilder.JoinType.INNER); + + sb.join("nicSearch", nicSearch, sb.entity().getId(), nicSearch.entity().getInstanceId(), JoinBuilder.JoinType.INNER); + } + if (useVirtualNetwork != null) { SearchBuilder serviceSearch = _offeringsDao.createSearchBuilder(); if ((Boolean)useVirtualNetwork){ @@ -2812,7 +2154,7 @@ public class ManagementServerImpl implements ManagementServer { } if (useVirtualNetwork != null) { - sc.setJoinParameters("serviceSearch", "guestIpType", NetworkOffering.GuestIpType.Virtualized.toString()); + sc.setJoinParameters("serviceSearch", "guestIpType", NetworkOffering.GuestIpType.Virtual.toString()); } if (keyword != null) { @@ -2843,6 +2185,10 @@ public class ManagementServerImpl implements ManagementServer { if (path != null) { sc.setJoinParameters("domainSearch", "path", path + "%"); } + + if (networkId != null) { + sc.setJoinParameters("nicSearch", "networkId", networkId); + } if (name != null) { sc.setParameters("name", "%" + name + "%"); @@ -2862,14 +2208,16 @@ public class ManagementServerImpl implements ManagementServer { if (zone != null) { sc.setParameters("dataCenterId", zone); - if(state == null) - sc.setParameters("stateNEQ", "Destroyed"); + if(state == null) { + sc.setParameters("stateNEQ", "Destroyed"); + } } if (pod != null) { sc.setParameters("podId", pod); - if(state == null) - sc.setParameters("stateNEQ", "Destroyed"); + if(state == null) { + sc.setParameters("stateNEQ", "Destroyed"); + } } if (hostId != null) { @@ -2897,95 +2245,6 @@ public class ManagementServerImpl implements ManagementServer { return _userVmDao.search(sc, searchFilter); } - @Override - public FirewallRuleVO updatePortForwardingRule(UpdatePortForwardingRuleCmd cmd) throws InvalidParameterValueException, PermissionDeniedException{ - String publicIp = cmd.getPublicIp(); - String privateIp = cmd.getPrivateIp(); - String privatePort = cmd.getPrivatePort(); - String publicPort = cmd.getPublicPort(); - String protocol = cmd.getProtocol(); - Long vmId = cmd.getVirtualMachineId(); - Long userId = UserContext.current().getUserId(); - Account account = UserContext.current().getAccount(); - UserVmVO userVM = null; - - if (userId == null) { - userId = Long.valueOf(User.UID_SYSTEM); - } - - IPAddressVO ipAddressVO = findIPAddressById(publicIp); - if (ipAddressVO == null) { - throw new InvalidParameterValueException("Unable to find IP address " + publicIp); - } - - if (ipAddressVO.getAccountId() == null) { - throw new InvalidParameterValueException("Unable to update port forwarding rule, owner of IP address " + publicIp + " not found."); - } - - if (privateIp != null) { - if (!NetUtils.isValidIp(privateIp)) { - throw new InvalidParameterValueException("Invalid private IP address specified: " + privateIp); - } - Criteria c = new Criteria(); - c.addCriteria(Criteria.ACCOUNTID, new Object[] {ipAddressVO.getAccountId()}); - c.addCriteria(Criteria.DATACENTERID, ipAddressVO.getDataCenterId()); - c.addCriteria(Criteria.IPADDRESS, privateIp); - List userVMs = searchForUserVMs(c); - if ((userVMs == null) || userVMs.isEmpty()) { - throw new ServerApiException(BaseCmd.PARAM_ERROR, "Invalid private IP address specified: " + privateIp + ", no virtual machine instances running with that address."); - } - userVM = userVMs.get(0); - } else if (vmId != null) { - userVM = findUserVMInstanceById(vmId); - if (userVM == null) { - throw new InvalidParameterValueException("Unable to find virtual machine with id " + vmId); - } - - if ((ipAddressVO.getAccountId() == null) || (ipAddressVO.getAccountId().longValue() != userVM.getAccountId())) { - throw new PermissionDeniedException("Unable to update port forwarding rule on IP address " + publicIp + ", permission denied."); - } - - if (ipAddressVO.getDataCenterId() != userVM.getDataCenterId()) { - throw new PermissionDeniedException("Unable to update port forwarding rule, IP address " + publicIp + " is not in the same availability zone as virtual machine " + userVM.toString()); - } - - privateIp = userVM.getGuestIpAddress(); - } else { - throw new InvalidParameterValueException("No private IP address (privateip) or virtual machine instance id (virtualmachineid) specified, unable to update port forwarding rule"); - } - - // if an admin account was passed in, or no account was passed in, make sure we honor the accountName/domainId parameters - if (account != null) { - if (isAdmin(account.getType())) { - if (!_domainDao.isChildDomain(account.getDomainId(), ipAddressVO.getDomainId())) { - throw new PermissionDeniedException("Unable to update port forwarding rule on IP address " + publicIp + ", permission denied."); - } - } else if (account.getId() != ipAddressVO.getAccountId()) { - throw new PermissionDeniedException("Unable to update port forwarding rule on IP address " + publicIp + ", permission denied."); - } - } - - List fwRules = _firewallRulesDao.listIPForwardingForUpdate(publicIp, publicPort, protocol); - if ((fwRules != null) && (fwRules.size() == 1)) { - FirewallRuleVO fwRule = fwRules.get(0); - String oldPrivateIP = fwRule.getPrivateIpAddress(); - String oldPrivatePort = fwRule.getPrivatePort(); - fwRule.setPrivateIpAddress(privateIp); - fwRule.setPrivatePort(privatePort); - _firewallRulesDao.update(fwRule.getId(), fwRule); - _networkMgr.updateFirewallRule(fwRule, oldPrivateIP, oldPrivatePort); - return fwRule; - }else{ - s_logger.warn("Unable to find the rule to be updated for public ip:public port"+publicIp+":"+publicPort+ "private ip:private port:"+privateIp+":"+privatePort); - throw new InvalidParameterValueException("Unable to find the rule to be updated for public ip:public port"+publicIp+":"+publicPort+ " private ip:private port:"+privateIp+":"+privatePort); - } - } - - @Override - public FirewallRuleVO findForwardingRuleById(Long ruleId) { - return _firewallRulesDao.findById(ruleId); - } - @Override public IPAddressVO findIPAddressById(String ipAddress) { return _publicIpAddressDao.findById(ipAddress); @@ -3067,8 +2326,9 @@ public class ManagementServerImpl implements ManagementServer { sc.addAnd("level", SearchCriteria.Op.SC, ssc); } - if (level != null) - sc.setParameters("levelEQ", level); + if (level != null) { + sc.setParameters("levelEQ", level); + } if (accountId != null) { sc.setParameters("accountId", accountId); @@ -3451,26 +2711,26 @@ public class ManagementServerImpl implements ManagementServer { Object forVirtualNetwork = cmd.isForVirtualNetwork(); SearchBuilder sb = _publicIpAddressDao.createSearchBuilder(); - sb.and("accountIdEQ", sb.entity().getAccountId(), SearchCriteria.Op.EQ); + sb.and("accountIdEQ", sb.entity().getAllocatedToAccountId(), SearchCriteria.Op.EQ); sb.and("dataCenterId", sb.entity().getDataCenterId(), SearchCriteria.Op.EQ); sb.and("address", sb.entity().getAddress(), SearchCriteria.Op.LIKE); - sb.and("vlanDbId", sb.entity().getVlanDbId(), SearchCriteria.Op.EQ); + sb.and("vlanDbId", sb.entity().getVlanId(), SearchCriteria.Op.EQ); if ((accountId == null) && (domainId != null)) { // if accountId isn't specified, we can do a domain match for the admin case SearchBuilder domainSearch = _domainDao.createSearchBuilder(); domainSearch.and("path", domainSearch.entity().getPath(), SearchCriteria.Op.LIKE); - sb.join("domainSearch", domainSearch, sb.entity().getDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER); + sb.join("domainSearch", domainSearch, sb.entity().getAllocatedInDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER); } if (forVirtualNetwork != null) { SearchBuilder vlanSearch = _vlanDao.createSearchBuilder(); vlanSearch.and("vlanType", vlanSearch.entity().getVlanType(), SearchCriteria.Op.EQ); - sb.join("vlanSearch", vlanSearch, sb.entity().getVlanDbId(), vlanSearch.entity().getId(), JoinBuilder.JoinType.INNER); + sb.join("vlanSearch", vlanSearch, sb.entity().getVlanId(), vlanSearch.entity().getId(), JoinBuilder.JoinType.INNER); } if ((isAllocated != null) && (isAllocated == true)) { - sb.and("allocated", sb.entity().getAllocated(), SearchCriteria.Op.NNULL); + sb.and("allocated", sb.entity().getAllocatedTime(), SearchCriteria.Op.NNULL); } SearchCriteria sc = sb.create(); @@ -3701,8 +2961,9 @@ public class ManagementServerImpl implements ManagementServer { VMInstanceVO vm = this.findVMInstanceById(vmId); if (vm != null) { ConsoleProxyInfo proxy = getConsoleProxy(vm.getDataCenterId(), vmId); - if (proxy != null) + if (proxy != null) { return proxy.getProxyImageUrl(); + } } return null; } @@ -3714,12 +2975,14 @@ public class ManagementServerImpl implements ManagementServer { return new Pair(null, -1); } - if(s_logger.isTraceEnabled()) - s_logger.trace("Trying to retrieve VNC port from agent about VM " + vm.getHostName()); + if(s_logger.isTraceEnabled()) { + s_logger.trace("Trying to retrieve VNC port from agent about VM " + vm.getHostName()); + } GetVncPortAnswer answer = (GetVncPortAnswer) _agentMgr.easySend(vm.getHostId(), new GetVncPortCommand(vm.getId(), vm.getInstanceName())); - if(answer != null) + if(answer != null) { return new Pair(answer.getAddress(), answer.getPort()); + } return new Pair(null, -1); } @@ -3774,7 +3037,7 @@ public class ManagementServerImpl implements ManagementServer { } if (path != null) { - sc.setParameters("path", path); + sc.setParameters("path", "%" +path+"%"); } return _domainDao.search(sc, searchFilter); @@ -3999,17 +3262,40 @@ public class ManagementServerImpl implements ManagementServer { sc.addAnd("name", SearchCriteria.Op.EQ, domainName); List domains = _domainDao.search(sc, null); if ((domains == null) || domains.isEmpty()) { - _domainDao.update(domainId, domainName); + //whilst updating a domain name, update its path and update all its children's path domain = _domainDao.findById(domainId); + String updatedDomainPath = getUpdatedDomainPath(domain.getPath(),domainName); + updateDomainChildren(domain,updatedDomainPath); + _domainDao.update(domainId, domainName, updatedDomainPath); EventUtils.saveEvent(new Long(1), domain.getAccountId(), EventVO.LEVEL_INFO, EventTypes.EVENT_DOMAIN_UPDATE, "Domain, " + domainName + " was updated"); return _domainDao.findById(domainId); } else { domain = _domainDao.findById(domainId); EventUtils.saveEvent(new Long(1), domain.getAccountId(), EventVO.LEVEL_ERROR, EventTypes.EVENT_DOMAIN_UPDATE, "Failed to update domain " + domain.getName() + " with name " + domainName + ", name in use."); s_logger.error("Domain with name " + domainName + " already exists in the system"); - throw new CloudRuntimeException("Fail to update domain " + domainId); + throw new CloudRuntimeException("Failed to update domain " + domainId); } } + + private String getUpdatedDomainPath(String oldPath, String newName){ + String[] tokenizedPath = oldPath.split("/"); + tokenizedPath[tokenizedPath.length-1] = newName; + StringBuilder finalPath = new StringBuilder(); + for(String token : tokenizedPath){ + finalPath.append(token); + finalPath.append("/"); + } + return finalPath.toString(); + } + + private void updateDomainChildren(DomainVO domain, String updatedDomainPrefix){ + List domainChildren = _domainDao.findAllChildren(domain.getPath(), domain.getId()); + //for each child, update the path + for(DomainVO dom : domainChildren){ + dom.setPath(dom.getPath().replaceFirst(domain.getPath(), updatedDomainPrefix)); + _domainDao.update(dom.getId(), dom); + } + } @Override public Long findDomainIdByAccountId(Long accountId) { @@ -4387,10 +3673,12 @@ public class ManagementServerImpl implements ManagementServer { dol.addAll(_diskOfferingDao.search(sc, searchFilter)); //try and move on to the next domain - if(domainRecord.getParent() != null) - domainRecord = _domainDao.findById(domainRecord.getParent()); - else - break;//now we got all the offerings for this user/dom adm + if(domainRecord.getParent() != null) { + domainRecord = _domainDao.findById(domainRecord.getParent()); + } + else { + break;//now we got all the offerings for this user/dom adm + } } }else{ s_logger.error("Could not find the domainId for account:"+account.getAccountName()); @@ -4398,8 +3686,9 @@ public class ManagementServerImpl implements ManagementServer { } //add all the public offerings to the sol list before returning - if(includePublicOfferings) - dol.addAll(_diskOfferingDao.findPublicDiskOfferings()); + if(includePublicOfferings) { + dol.addAll(_diskOfferingDao.findPublicDiskOfferings()); + } return dol; @@ -4500,17 +3789,19 @@ public class ManagementServerImpl implements ManagementServer { public AsyncJobResult queryAsyncJobResult(long jobId) throws PermissionDeniedException { AsyncJobVO job = _asyncMgr.getAsyncJob(jobId); if (job == null) { - if (s_logger.isDebugEnabled()) + if (s_logger.isDebugEnabled()) { s_logger.debug("queryAsyncJobResult error: Permission denied, invalid job id " + jobId); + } throw new PermissionDeniedException("Permission denied, invalid job id " + jobId); } // treat any requests from API server as trusted requests if (!UserContext.current().isApiServer() && job.getAccountId() != UserContext.current().getAccount().getId()) { - if (s_logger.isDebugEnabled()) + if (s_logger.isDebugEnabled()) { s_logger.debug("Mismatched account id in job and user context, perform further securty check. job id: " + jobId + ", job owner account: " + job.getAccountId() + ", accound id in current context: " + UserContext.current().getAccount().getId()); + } Account account = UserContext.current().getAccount(); if (account != null) { @@ -4550,200 +3841,6 @@ public class ManagementServerImpl implements ManagementServer { return _asyncMgr.getAsyncJob(jobId); } - @Override - public LoadBalancerVO findLoadBalancer(Long accountId, String name) { - SearchCriteria sc = _loadBalancerDao.createSearchCriteria(); - sc.addAnd("accountId", SearchCriteria.Op.EQ, accountId); - sc.addAnd("name", SearchCriteria.Op.EQ, name); - List loadBalancers = _loadBalancerDao.search(sc, null); - if ((loadBalancers != null) && !loadBalancers.isEmpty()) { - return loadBalancers.get(0); - } - return null; - } - - @Override - public LoadBalancerVO findLoadBalancerById(long loadBalancerId) { - return _loadBalancerDao.findById(Long.valueOf(loadBalancerId)); - } - - @Override - public List listLoadBalancerInstances(ListLoadBalancerRuleInstancesCmd cmd) throws PermissionDeniedException { - Account account = UserContext.current().getAccount(); - Long loadBalancerId = cmd.getId(); - Boolean applied = cmd.isApplied(); - - if (applied == null) { - applied = Boolean.TRUE; - } - - LoadBalancerVO loadBalancer = _loadBalancerDao.findById(loadBalancerId); - if (loadBalancer == null) { - return null; - } - - if (account != null) { - long lbAcctId = loadBalancer.getAccountId(); - if (isAdmin(account.getType())) { - Account userAccount = _accountDao.findById(lbAcctId); - if (!_domainDao.isChildDomain(account.getDomainId(), userAccount.getDomainId())) { - throw new PermissionDeniedException("Invalid load balancer rule id (" + loadBalancerId + ") given, unable to list load balancer instances."); - } - } else if (account.getId() != lbAcctId) { - throw new PermissionDeniedException("Unable to list load balancer instances, account " + account.getAccountName() + " does not own load balancer rule " + loadBalancer.getName()); - } - } - - List loadBalancerInstances = new ArrayList(); - List vmLoadBalancerMappings = null; - if (applied) { - // List only the instances that have actually been applied to the load balancer (pending is false). - vmLoadBalancerMappings = _loadBalancerVMMapDao.listByLoadBalancerId(loadBalancerId, false); - } else { - // List all instances applied, even pending ones that are currently being assigned, so that the semantics - // of "what instances can I apply to this load balancer" are maintained. - vmLoadBalancerMappings = _loadBalancerVMMapDao.listByLoadBalancerId(loadBalancerId); - } - List appliedInstanceIdList = new ArrayList(); - if ((vmLoadBalancerMappings != null) && !vmLoadBalancerMappings.isEmpty()) { - for (LoadBalancerVMMapVO vmLoadBalancerMapping : vmLoadBalancerMappings) { - appliedInstanceIdList.add(vmLoadBalancerMapping.getInstanceId()); - } - } - - IPAddressVO addr = _publicIpAddressDao.findById(loadBalancer.getIpAddress()); - List userVms = _userVmDao.listVirtualNetworkInstancesByAcctAndZone(loadBalancer.getAccountId(), addr.getDataCenterId()); - - for (UserVmVO userVm : userVms) { - // if the VM is destroyed, being expunged, in an error state, or in an unknown state, skip it - switch (userVm.getState()) { - case Destroyed: - case Expunging: - case Error: - case Unknown: - continue; - } - - boolean isApplied = appliedInstanceIdList.contains(userVm.getId()); - if (!applied && !isApplied) { - loadBalancerInstances.add(userVm); - } else if (applied && isApplied) { - loadBalancerInstances.add(userVm); - } - } - - return loadBalancerInstances; - } - - @Override - public List searchForLoadBalancers(ListLoadBalancerRulesCmd cmd) throws InvalidParameterValueException, PermissionDeniedException { - // do some parameter validation - Account account = UserContext.current().getAccount(); - String accountName = cmd.getAccountName(); - Long domainId = cmd.getDomainId(); - Long accountId = null; - Account ipAddressOwner = null; - String ipAddress = cmd.getPublicIp(); - - if (ipAddress != null) { - IPAddressVO ipAddressVO = _publicIpAddressDao.findById(ipAddress); - if (ipAddressVO == null) { - throw new InvalidParameterValueException("Unable to list load balancers, IP address " + ipAddress + " not found."); - } else { - Long ipAddrAcctId = ipAddressVO.getAccountId(); - if (ipAddrAcctId == null) { - throw new InvalidParameterValueException("Unable to list load balancers, IP address " + ipAddress + " is not associated with an account."); - } - ipAddressOwner = _accountDao.findById(ipAddrAcctId); - } - } - - if ((account == null) || isAdmin(account.getType())) { - // validate domainId before proceeding - if (domainId != null) { - if ((account != null) && !_domainDao.isChildDomain(account.getDomainId(), domainId)) { - throw new PermissionDeniedException("Unable to list load balancers for domain id " + domainId + ", permission denied."); - } - if (accountName != null) { - Account userAccount = _accountDao.findActiveAccount(accountName, domainId); - if (userAccount != null) { - accountId = userAccount.getId(); - } else { - throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain " + domainId); - } - } - } else if (ipAddressOwner != null) { - if ((account != null) && !_domainDao.isChildDomain(account.getDomainId(), ipAddressOwner.getDomainId())) { - throw new PermissionDeniedException("Unable to list load balancer rules for IP address " + ipAddress + ", permission denied."); - } - } else { - domainId = ((account == null) ? DomainVO.ROOT_DOMAIN : account.getDomainId()); - } - } else { - accountId = account.getId(); - } - - Filter searchFilter = new Filter(LoadBalancerVO.class, "ipAddress", true, cmd.getStartIndex(), cmd.getPageSizeVal()); - - Object id = cmd.getId(); - Object name = cmd.getLoadBalancerRuleName(); - Object keyword = cmd.getKeyword(); - Object instanceId = cmd.getVirtualMachineId(); - - SearchBuilder sb = _loadBalancerDao.createSearchBuilder(); - sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); - sb.and("nameEQ", sb.entity().getName(), SearchCriteria.Op.EQ); - sb.and("accountId", sb.entity().getAccountId(), SearchCriteria.Op.EQ); - sb.and("ipAddress", sb.entity().getIpAddress(), SearchCriteria.Op.EQ); - - if ((accountId == null) && (domainId != null)) { - // if accountId isn't specified, we can do a domain match for the admin case - SearchBuilder domainSearch = _domainDao.createSearchBuilder(); - domainSearch.and("path", domainSearch.entity().getPath(), SearchCriteria.Op.LIKE); - sb.join("domainSearch", domainSearch, sb.entity().getDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER); - } - - if (instanceId != null) { - SearchBuilder lbVMSearch = _loadBalancerVMMapDao.createSearchBuilder(); - lbVMSearch.and("instanceId", lbVMSearch.entity().getInstanceId(), SearchCriteria.Op.EQ); - sb.join("lbVMSearch", lbVMSearch, sb.entity().getId(), lbVMSearch.entity().getLoadBalancerId(), JoinBuilder.JoinType.INNER); - } - - SearchCriteria sc = sb.create(); - if (keyword != null) { - SearchCriteria ssc = _loadBalancerDao.createSearchCriteria(); - ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - ssc.addOr("description", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - - sc.addAnd("name", SearchCriteria.Op.SC, ssc); - } - - if (name != null) { - sc.setParameters("nameEQ", name); - } - - if (id != null) { - sc.setParameters("id", id); - } - - if (ipAddress != null) { - sc.setParameters("ipAddress", ipAddress); - } - - if (accountId != null) { - sc.setParameters("accountId", accountId); - } else if (domainId != null) { - DomainVO domain = _domainDao.findById(domainId); - sc.setJoinParameters("domainSearch", "path", domain.getPath() + "%"); - } - - if (instanceId != null) { - sc.setJoinParameters("lbVMSearch", "instanceId", instanceId); - } - - return _loadBalancerDao.search(sc, searchFilter); - } - @Override public String[] getApiConfig() { return new String[] { "commands.properties" }; @@ -4781,8 +3878,9 @@ public class ManagementServerImpl implements ManagementServer { } catch (Exception e) { s_logger.error("Exception ", e); } finally { - if(txn != null) - txn.close(); + if(txn != null) { + txn.close(); + } lock.unlock(); } @@ -5058,11 +4156,13 @@ public class ManagementServerImpl implements ManagementServer { @Override public VMInstanceVO findSystemVMById(long instanceId) { VMInstanceVO systemVm = _vmInstanceDao.findByIdTypes(instanceId, VirtualMachine.Type.ConsoleProxy, VirtualMachine.Type.SecondaryStorageVm); - if(systemVm == null) - return null; + if(systemVm == null) { + return null; + } - if(systemVm.getType() == VirtualMachine.Type.ConsoleProxy) - return _consoleProxyDao.findById(instanceId); + if(systemVm.getType() == VirtualMachine.Type.ConsoleProxy) { + return _consoleProxyDao.findById(instanceId); + } return _secStorageVmDao.findById(instanceId); } @@ -5199,8 +4299,9 @@ public class ManagementServerImpl implements ManagementServer { //verify that user exists User user = findUserById(userId); - if ((user == null) || (user.getRemoved() != null)) - throw new InvalidParameterValueException("Unable to find active user by id " + userId); + if ((user == null) || (user.getRemoved() != null)) { + throw new InvalidParameterValueException("Unable to find active user by id " + userId); + } String cloudIdentifier = _configDao.getValue("cloud.identifier"); if (cloudIdentifier == null) { @@ -5298,10 +4399,11 @@ public class ManagementServerImpl implements ManagementServer { { String value = _configs.get("use.local.storage"); - if(value!=null && value.equalsIgnoreCase("true")) - return true; - else - return false; + if(value!=null && value.equalsIgnoreCase("true")) { + return true; + } else { + return false; + } } @Override @@ -5331,8 +4433,9 @@ public class ManagementServerImpl implements ManagementServer { Map capabilities = new HashMap(); String networkGroupsEnabled = _configs.get("direct.attach.network.groups.enabled"); - if(networkGroupsEnabled == null) - networkGroupsEnabled = "false"; + if(networkGroupsEnabled == null) { + networkGroupsEnabled = "false"; + } capabilities.put("networkGroupsEnabled", networkGroupsEnabled); capabilities.put("cloudStackVersion", getVersion()); @@ -5368,10 +4471,11 @@ public class ManagementServerImpl implements ManagementServer { if(rootVolume!=null){ Status poolStatus = _poolDao.findById(rootVolume.getPoolId()).getStatus(); - if(!poolStatus.equals(Status.Up)) - return false; - else - return true; + if(!poolStatus.equals(Status.Up)) { + return false; + } else { + return true; + } } return false; @@ -5683,11 +4787,13 @@ public class ManagementServerImpl implements ManagementServer { throw new ResourceUnavailableException(msg); }else{ if(cert.getUpdated().equalsIgnoreCase("Y")){ - if(s_logger.isDebugEnabled()) - s_logger.debug("A custom certificate already exists in the DB, will replace it with the new one being uploaded"); + if(s_logger.isDebugEnabled()) { + s_logger.debug("A custom certificate already exists in the DB, will replace it with the new one being uploaded"); + } }else{ - if(s_logger.isDebugEnabled()) - s_logger.debug("No custom certificate exists in the DB, will upload a new one"); + if(s_logger.isDebugEnabled()) { + s_logger.debug("No custom certificate exists in the DB, will upload a new one"); + } } //validate if the cert follows X509 format, if not, don't persist to db @@ -5702,8 +4808,9 @@ public class ManagementServerImpl implements ManagementServer { } certVOId = _certDao.persistCustomCertToDb(certificate,cert,this.getId());//0 implies failure - if(s_logger.isDebugEnabled()) - s_logger.debug("Custom certificate persisted to the DB"); + if(s_logger.isDebugEnabled()) { + s_logger.debug("Custom certificate persisted to the DB"); + } } if (certVOId != 0) @@ -5743,8 +4850,9 @@ public class ManagementServerImpl implements ManagementServer { long eventId = saveScheduledEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM, EventTypes.EVENT_PROXY_REBOOT, "rebooting console proxy with Id: "+cp.getId()); _consoleProxyMgr.rebootProxy(cp.getId(), eventId); //when cp reboots, the context will be reinit with the new cert - if(s_logger.isDebugEnabled()) - s_logger.debug("Successfully updated custom certificate on console proxy vm id:"+cp.getId()+" ,console proxy host id:"+cpHostId); + if(s_logger.isDebugEnabled()) { + s_logger.debug("Successfully updated custom certificate on console proxy vm id:"+cp.getId()+" ,console proxy host id:"+cpHostId); + } updatedCpIdList.add(cp.getId()); } } catch (AgentUnavailableException e) { @@ -5768,11 +4876,11 @@ public class ManagementServerImpl implements ManagementServer { } }catch (Exception e) { s_logger.warn("Failed to successfully update the cert across console proxies on management server:"+this.getId()); - if(e instanceof ResourceUnavailableException) - throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, e.getMessage()); - else if(e instanceof ManagementServerException) - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage()); - else if(e instanceof IndexOutOfBoundsException){ + if(e instanceof ResourceUnavailableException) { + throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, e.getMessage()); + } else if(e instanceof ManagementServerException) { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage()); + } else if(e instanceof IndexOutOfBoundsException){ String msg = "Custom certificate record in the db deleted; this should never happen. Please create a new record in the certificate table"; s_logger.error(msg,e); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, msg); @@ -5832,7 +4940,7 @@ public class ManagementServerImpl implements ManagementServer { if (ipAddressVO == null) { throw new InvalidParameterValueException("Unable to list remote access vpns, IP address " + ipAddress + " not found."); } else { - Long ipAddrAcctId = ipAddressVO.getAccountId(); + Long ipAddrAcctId = ipAddressVO.getAllocatedToAccountId(); if (ipAddrAcctId == null) { throw new InvalidParameterValueException("Unable to list remote access vpns, IP address " + ipAddress + " is not associated with an account."); } diff --git a/server/src/com/cloud/storage/StorageManagerImpl.java b/server/src/com/cloud/storage/StorageManagerImpl.java index 5a840d2b551..f76d206bca2 100755 --- a/server/src/com/cloud/storage/StorageManagerImpl.java +++ b/server/src/com/cloud/storage/StorageManagerImpl.java @@ -112,6 +112,7 @@ import com.cloud.host.dao.DetailsDao; import com.cloud.host.dao.HostDao; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.network.NetworkManager; +import com.cloud.network.router.DomainRouterManager; import com.cloud.offering.ServiceOffering; import com.cloud.service.ServiceOfferingVO; import com.cloud.service.dao.ServiceOfferingDao; @@ -210,6 +211,7 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag @Inject protected DomainDao _domainDao; @Inject protected UserDao _userDao; @Inject protected ClusterDao _clusterDao; + @Inject protected DomainRouterManager _routerMgr; @Inject(adapter=StoragePoolAllocator.class) protected Adapters _storagePoolAllocators; @@ -971,8 +973,9 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag VMInstanceVO vmInstance = _vmInstanceDao.findById(vmId); if (vmInstance != null) { Long hostId = vmInstance.getHostId(); - if (hostId != null && !avoidHosts.contains(vmInstance.getHostId())) - return hostId; + if (hostId != null && !avoidHosts.contains(vmInstance.getHostId())) { + return hostId; + } } } /*Can't find the vm where host resides on(vm is destroyed? or volume is detached from vm), randomly choose a host to send the cmd */ @@ -1082,7 +1085,7 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag _overProvisioningFactor = Integer.parseInt(overProvisioningFactorStr); } - _retry = NumbersUtil.parseInt(configs.get(Config.StartRetry.key()), 2); + _retry = NumbersUtil.parseInt(configs.get(Config.StartRetry.key()), 10); _pingInterval = NumbersUtil.parseInt(configs.get("ping.interval"), 60); _hostRetry = NumbersUtil.parseInt(configs.get("host.retry"), 2); _storagePoolAcquisitionWaitSeconds = NumbersUtil.parseInt(configs.get("pool.acquisition.wait.seconds"), 1800); @@ -1294,9 +1297,9 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag URI uri = null; try { uri = new URI(cmd.getUrl()); - if (uri.getScheme() == null) + if (uri.getScheme() == null) { throw new ServerApiException(BaseCmd.PARAM_ERROR, "scheme is null " + cmd.getUrl() + ", add nfs:// as a prefix"); - else if (uri.getScheme().equalsIgnoreCase("nfs")) { + } else if (uri.getScheme().equalsIgnoreCase("nfs")) { String uriHost = uri.getHost(); String uriPath = uri.getPath(); if (uriHost == null || uriPath == null || uriHost.trim().isEmpty() || uriPath.trim().isEmpty()) { @@ -1525,8 +1528,9 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag StoragePoolVO lock = _storagePoolDao.acquireInLockTable(sPool.getId()); try { if (lock == null) { - if(s_logger.isDebugEnabled()) - s_logger.debug("Failed to acquire lock when deleting StoragePool with ID: " + sPool.getId()); + if(s_logger.isDebugEnabled()) { + s_logger.debug("Failed to acquire lock when deleting StoragePool with ID: " + sPool.getId()); + } return false; } @@ -1752,9 +1756,9 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag throw new InvalidParameterValueException("Invalid size for custom volume creation: " + size+" ,max volume size is:"+_maxVolumeSizeInGb); } - if(diskOffering.getDiskSize() > 0) - size = (diskOffering.getDiskSize()*1024*1024);//the disk offering size is in MB, which needs to be converted into bytes - else{ + if(diskOffering.getDiskSize() > 0) { + size = (diskOffering.getDiskSize()*1024*1024);//the disk offering size is in MB, which needs to be converted into bytes + } else{ if(!validateVolumeSizeRange(size)){ throw new InvalidParameterValueException("Invalid size for custom volume creation: " + size+" ,max volume size is:"+_maxVolumeSizeInGb); } @@ -1831,7 +1835,7 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag @Override @DB public VolumeVO createVolume(CreateVolumeCmd cmd) { - VolumeVO volume = _volsDao.findById(cmd.getId()); + VolumeVO volume = _volsDao.findById(cmd.getEntityId()); // VolumeVO createdVolume = null; Long userId = UserContext.current().getUserId(); @@ -2241,8 +2245,9 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag //if they dont, then just stop all vms on this one List upPools = _storagePoolDao.listPoolsByStatus(Status.Up); - if(upPools == null || upPools.size() == 0) - restart = false; + if(upPools == null || upPools.size() == 0) { + restart = false; + } //2. Get a list of all the volumes within this storage pool List allVolumes = _volsDao.findByPoolId(primaryStorageId); @@ -2252,8 +2257,9 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag { VMInstanceVO vmInstance = _vmInstanceDao.findById(volume.getInstanceId()); - if(vmInstance == null) - continue; + if(vmInstance == null) { + continue; + } //shut down the running vms if(vmInstance.getState().equals(State.Running) || vmInstance.getState().equals(State.Starting)) @@ -2347,7 +2353,7 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag //create a dummy event long eventId2 = saveScheduledEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM, EventTypes.EVENT_ROUTER_STOP, "stopping domain router with Id: "+vmInstance.getId()); - if(!_networkMgr.stopRouter(vmInstance.getId(), eventId2)) + if(!_routerMgr.stopRouter(vmInstance.getId(), eventId2)) { String errorMsg = "There was an error stopping the domain router id: "+vmInstance.getId()+" ,cannot enable primary storage maintenance"; s_logger.warn(errorMsg); @@ -2359,7 +2365,7 @@ public class StorageManagerImpl implements StorageManager, StorageService, Manag { //create a dummy event and restart the domr immediately long eventId = saveScheduledEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM, EventTypes.EVENT_PROXY_START, "starting domr with Id: "+vmInstance.getId()); - if(_networkMgr.startRouter(vmInstance.getId(), eventId)==null) + if(_routerMgr.startRouter(vmInstance.getId(), eventId)==null) { String errorMsg = "There was an error starting the domain router id: "+vmInstance.getId()+" on another storage pool, cannot enable primary storage maintenance"; s_logger.warn(errorMsg); diff --git a/server/src/com/cloud/storage/allocator/LocalStoragePoolAllocator.java b/server/src/com/cloud/storage/allocator/LocalStoragePoolAllocator.java index fe95cc54b34..59698337cf0 100644 --- a/server/src/com/cloud/storage/allocator/LocalStoragePoolAllocator.java +++ b/server/src/com/cloud/storage/allocator/LocalStoragePoolAllocator.java @@ -147,14 +147,14 @@ public class LocalStoragePoolAllocator extends FirstFitStoragePoolAllocator { 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, false); + so = new ServiceOfferingVO("Fake Offering For unknow system VM", 1, 128, 0, 0, 0, false, null, NetworkOffering.GuestIpType.Virtual, false, true, null, false); } long usedMemory = calcHostAllocatedCpuMemoryCapacity(vmOnHost, CapacityVO.CAPACITY_TYPE_MEMORY); @@ -244,14 +244,14 @@ public class LocalStoragePoolAllocator extends FirstFitStoragePoolAllocator { 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, false); + so = new ServiceOfferingVO("Fake Offering For unknow system VM", 1, 128, 0, 0, 0, false, null, NetworkOffering.GuestIpType.Virtual, false, true, null, false); } if(capacityType == CapacityVO.CAPACITY_TYPE_MEMORY) { diff --git a/server/src/com/cloud/storage/secondary/SecondaryStorageManagerImpl.java b/server/src/com/cloud/storage/secondary/SecondaryStorageManagerImpl.java index b93bf3c15dd..a77bc0fa650 100644 --- a/server/src/com/cloud/storage/secondary/SecondaryStorageManagerImpl.java +++ b/server/src/com/cloud/storage/secondary/SecondaryStorageManagerImpl.java @@ -244,6 +244,7 @@ public class SecondaryStorageManagerImpl implements SecondaryStorageVmManager, V private String _secHostUuid; private String _nfsShare; private String _allowedInternalSites; + private boolean _useNewNetworking; @@ -257,7 +258,7 @@ public class SecondaryStorageManagerImpl implements SecondaryStorageVmManager, V public SecondaryStorageVmVO startSecStorageVm(long secStorageVmId, long startEventId) { try { - return start(secStorageVmId, startEventId); + return start2(secStorageVmId, startEventId); } catch (StorageUnavailableException e) { s_logger.warn("Exception while trying to start secondary storage vm", e); @@ -274,6 +275,9 @@ public class SecondaryStorageManagerImpl implements SecondaryStorageVmManager, V } public SecondaryStorageVmVO start2(long secStorageVmId, long startEventId) throws ResourceUnavailableException, InsufficientCapacityException, ConcurrentOperationException { + if (!_useNewNetworking) { + return start(secStorageVmId, startEventId); + } SecondaryStorageVmVO secStorageVm = _secStorageVmDao.findById(secStorageVmId); Account systemAcct = _accountMgr.getSystemAccount(); User systemUser = _accountMgr.getSystemUser(); @@ -290,8 +294,9 @@ public class SecondaryStorageManagerImpl implements SecondaryStorageVmManager, V if (asyncExecutor != null) { AsyncJobVO job = asyncExecutor.getJob(); - if (s_logger.isInfoEnabled()) + if (s_logger.isInfoEnabled()) { s_logger.info("Start secondary storage vm " + secStorageVmId + ", update async job-" + job.getId()); + } _asyncMgr.updateAsyncJobAttachment(job.getId(), "sec_storage_vm", secStorageVmId); } @@ -311,19 +316,21 @@ public class SecondaryStorageManagerImpl implements SecondaryStorageVmManager, V State state = secStorageVm.getState(); if (state == State.Starting /* || state == State.Migrating */) { - if (s_logger.isDebugEnabled()) - s_logger.debug("Waiting secondary storage vm to be ready, secondary storage vm id : " + if (s_logger.isDebugEnabled()) { + s_logger.debug("Waiting secondary storage vm to be ready, secondary storage vm id : " + secStorageVmId + " secStorageVm VM state : " + state.toString()); + } if (secStorageVm.getPrivateIpAddress() == null || connect(secStorageVm.getPrivateIpAddress(), _secStorageVmCmdPort) != null) { - if (secStorageVm.getPrivateIpAddress() == null) - s_logger.warn("Retruning a secondary storage vm that is being started but private IP has not been allocated yet, secondary storage vm id : " + if (secStorageVm.getPrivateIpAddress() == null) { + s_logger.warn("Retruning a secondary storage vm that is being started but private IP has not been allocated yet, secondary storage vm id : " + secStorageVmId); - else - s_logger.warn("Waiting secondary storage vm to be ready timed out, secondary storage vm id : " + } else { + s_logger.warn("Waiting secondary storage vm to be ready timed out, secondary storage vm id : " + secStorageVmId); + } // TODO, it is very tricky here, if the startup process // takes too long and it timed out here, @@ -334,9 +341,10 @@ public class SecondaryStorageManagerImpl implements SecondaryStorageVmManager, V } if (state == State.Running) { - if (s_logger.isTraceEnabled()) - s_logger.trace("Secondary storage vm is already started: " + if (s_logger.isTraceEnabled()) { + s_logger.trace("Secondary storage vm is already started: " + secStorageVm.getHostName()); + } saveFailedEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM, EventTypes.EVENT_SSVM_START, "Secondary storage vm is already started", startEventId); return secStorageVm; } @@ -356,7 +364,7 @@ public class SecondaryStorageManagerImpl implements SecondaryStorageVmManager, V } } // to ensure atomic state transition to Starting state - if (!_secStorageVmDao.updateIf(secStorageVm, VirtualMachine.Event.StartRequested, routingHost.getId())) { + if (! _itMgr.stateTransitTo(secStorageVm, VirtualMachine.Event.StartRequested, routingHost.getId())) { if (s_logger.isDebugEnabled()) { SecondaryStorageVmVO temp = _secStorageVmDao.findById(secStorageVmId); s_logger.debug("Unable to start secondary storage vm " @@ -391,7 +399,7 @@ public class SecondaryStorageManagerImpl implements SecondaryStorageVmManager, V secStorageVm.setPrivateIpAddress(privateIpAddress); String guestIpAddress = _dcDao.allocateLinkLocalIpAddress(secStorageVm.getDataCenterId(), routingHost.getPodId(), secStorageVm.getId(), null); secStorageVm.setGuestIpAddress(guestIpAddress); - _secStorageVmDao.updateIf(secStorageVm, VirtualMachine.Event.OperationRetry, routingHost.getId()); + _itMgr.stateTransitTo(secStorageVm, VirtualMachine.Event.OperationRetry, routingHost.getId()); secStorageVm = _secStorageVmDao.findById(secStorageVm.getId()); List vols = _storageMgr.prepare(secStorageVm, routingHost); @@ -420,21 +428,23 @@ public class SecondaryStorageManagerImpl implements SecondaryStorageVmManager, V _multicastRate, _secStorageVmCmdPort, secStorageVm, secStorageVm.getHostName(), "", vols, _mgmt_host, _mgmt_port, _useSSlCopy, guestOSDescription); - if (s_logger.isDebugEnabled()) - s_logger.debug("Sending start command for secondary storage vm " + if (s_logger.isDebugEnabled()) { + s_logger.debug("Sending start command for secondary storage vm " + secStorageVm.getHostName() + " to " + routingHost.getName()); + } try { answer = _agentMgr.send(routingHost.getId(), cmdStart); s_logger.debug("StartSecStorageVmCommand Answer: " + (answer != null ? answer : "null")); - if (s_logger.isDebugEnabled()) - s_logger.debug("Received answer on starting secondary storage vm " + if (s_logger.isDebugEnabled()) { + s_logger.debug("Received answer on starting secondary storage vm " + secStorageVm.getHostName() + " on " + routingHost.getName()); + } if ( answer != null && answer.getResult() ) { if (s_logger.isDebugEnabled()) { @@ -504,7 +514,7 @@ public class SecondaryStorageManagerImpl implements SecondaryStorageVmManager, V "Couldn't find a routingHost to run secondary storage vm"); } - _secStorageVmDao.updateIf(secStorageVm, VirtualMachine.Event.OperationSucceeded, routingHost.getId()); + _itMgr.stateTransitTo(secStorageVm, VirtualMachine.Event.OperationSucceeded, routingHost.getId()); if (s_logger.isDebugEnabled()) { s_logger.debug("Secondary storage vm is now started, vm id : " + secStorageVm.getId()); } @@ -544,7 +554,7 @@ public class SecondaryStorageManagerImpl implements SecondaryStorageVmManager, V secStorageVm.setPrivateIpAddress(null); freePrivateIpAddress(privateIpAddress, secStorageVm.getDataCenterId(), secStorageVm.getId()); } - _secStorageVmDao.updateIf(secStorageVm, VirtualMachine.Event.OperationFailed, null); + _itMgr.stateTransitTo(secStorageVm, VirtualMachine.Event.OperationFailed, null); txn.commit(); } catch (Exception e) { s_logger.error("Caught exception during error recovery"); @@ -618,12 +628,14 @@ public class SecondaryStorageManagerImpl implements SecondaryStorageVmManager, V setupCmd.setCopyUserName(TemplateConstants.DEFAULT_HTTP_AUTH_USER); Answer answer = _agentMgr.easySend(storageHost.getId(), setupCmd); if (answer != null) { - if (s_logger.isDebugEnabled()) - s_logger.debug("Successfully programmed http auth into " + secStorageVm.getHostName()); + if (s_logger.isDebugEnabled()) { + s_logger.debug("Successfully programmed http auth into " + secStorageVm.getHostName()); + } return true; } else { - if (s_logger.isDebugEnabled()) - s_logger.debug("failed to program http auth into secondary storage vm : " + secStorageVm.getHostName()); + if (s_logger.isDebugEnabled()) { + s_logger.debug("failed to program http auth into secondary storage vm : " + secStorageVm.getHostName()); + } return false; } } @@ -649,8 +661,9 @@ public class SecondaryStorageManagerImpl implements SecondaryStorageVmManager, V SecStorageFirewallCfgCommand cpc = new SecStorageFirewallCfgCommand(); for (SecondaryStorageVmVO ssVm: alreadyRunning) { if (ssVm.getPublicIpAddress() != null) { - if (ssVm.getId() == secStorageVm.getId()) - continue; + if (ssVm.getId() == secStorageVm.getId()) { + continue; + } cpc.addPortConfig(ssVm.getPublicIpAddress(), copyPort , true, TemplateConstants.DEFAULT_TMPLT_COPY_INTF); if (_useSSlCopy){ cpc.addPortConfig(ssVm.getPublicIpAddress(), "443" , true, TemplateConstants.DEFAULT_TMPLT_COPY_INTF); @@ -659,12 +672,14 @@ public class SecondaryStorageManagerImpl implements SecondaryStorageVmManager, V } Answer answer = _agentMgr.easySend(storageHost.getId(), cpc); if (answer != null) { - if (s_logger.isDebugEnabled()) - s_logger.debug("Successfully programmed firewall rules into " + secStorageVm.getHostName()); + if (s_logger.isDebugEnabled()) { + s_logger.debug("Successfully programmed firewall rules into " + secStorageVm.getHostName()); + } return true; } else { - if (s_logger.isDebugEnabled()) - s_logger.debug("failed to program firewall rules into secondary storage vm : " + secStorageVm.getHostName()); + if (s_logger.isDebugEnabled()) { + s_logger.debug("failed to program firewall rules into secondary storage vm : " + secStorageVm.getHostName()); + } return false; } @@ -675,19 +690,22 @@ public class SecondaryStorageManagerImpl implements SecondaryStorageVmManager, V public SecondaryStorageVmVO startNew(long dataCenterId) { - if (s_logger.isDebugEnabled()) - s_logger.debug("Assign secondary storage vm from a newly started instance for request from data center : " + dataCenterId); + if (s_logger.isDebugEnabled()) { + s_logger.debug("Assign secondary storage vm from a newly started instance for request from data center : " + dataCenterId); + } - Map context = createSecStorageVmInstance(dataCenterId); + Map context = _useNewNetworking ? createSecStorageVmInstance2(dataCenterId) : createSecStorageVmInstance(dataCenterId); long secStorageVmId = (Long) context.get("secStorageVmId"); if (secStorageVmId == 0) { - if (s_logger.isTraceEnabled()) - s_logger.trace("Creating secondary storage vm instance failed, data center id : " + dataCenterId); + if (s_logger.isTraceEnabled()) { + s_logger.trace("Creating secondary storage vm instance failed, data center id : " + dataCenterId); + } // release critical system resource on failure - if (context.get("publicIpAddress") != null) - freePublicIpAddress((String) context.get("publicIpAddress"), dataCenterId, 0); + if (context.get("publicIpAddress") != null) { + freePublicIpAddress((String) context.get("publicIpAddress"), dataCenterId, 0); + } return null; } @@ -702,9 +720,10 @@ public class SecondaryStorageManagerImpl implements SecondaryStorageVmManager, V ); return secStorageVm; } else { - if (s_logger.isDebugEnabled()) - s_logger.debug("Unable to allocate secondary storage vm storage, remove the secondary storage vm record from DB, secondary storage vm id: " + if (s_logger.isDebugEnabled()) { + s_logger.debug("Unable to allocate secondary storage vm storage, remove the secondary storage vm record from DB, secondary storage vm id: " + secStorageVmId); + } SubscriptionMgr.getInstance().notifySubscribers(ALERT_SUBJECT, this, new SecStorageVmAlertEventArgs( @@ -741,9 +760,9 @@ public class SecondaryStorageManagerImpl implements SecondaryStorageVmManager, V 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)); } SecondaryStorageVmVO secStorageVm = new SecondaryStorageVmVO(id, _serviceOffering.getId(), name, _template.getId(), _template.getGuestOSId(), dataCenterId, systemAcct.getDomainId(), systemAcct.getId()); @@ -885,7 +904,7 @@ public class SecondaryStorageManagerImpl implements SecondaryStorageVmManager, V } // kick the state machine - _secStorageVmDao.updateIf(secStorageVm, VirtualMachine.Event.OperationSucceeded, null); + _itMgr.stateTransitTo(secStorageVm, VirtualMachine.Event.OperationSucceeded, null); return secStorageVm; } catch (StorageUnavailableException e) { s_logger.error("Unable to alloc storage for secondary storage vm: ", e); @@ -908,8 +927,9 @@ public class SecondaryStorageManagerImpl implements SecondaryStorageVmManager, V if (ipAndVlan == null) { s_logger.debug("Unable to get public ip address (type=Virtual) for secondary storage vm for data center : " + dcId); ipAndVlan = _vlanDao.assignPodDirectAttachIpAddress(dcId, podId, Account.ACCOUNT_ID_SYSTEM, DomainVO.ROOT_DOMAIN); - if (ipAndVlan == null) - s_logger.debug("Unable to get public ip address (type=DirectAttach) for secondary storage vm for data center : " + dcId); + if (ipAndVlan == null) { + s_logger.debug("Unable to get public ip address (type=DirectAttach) for secondary storage vm for data center : " + dcId); + } } if (ipAndVlan != null) { @@ -948,8 +968,9 @@ public class SecondaryStorageManagerImpl implements SecondaryStorageVmManager, V // for now, only one adapter is supported Enumeration it = _ssVmAllocators.enumeration(); - if (it.hasMoreElements()) - return it.nextElement(); + if (it.hasMoreElements()) { + return it.nextElement(); + } return null; } @@ -981,22 +1002,24 @@ public class SecondaryStorageManagerImpl implements SecondaryStorageVmManager, V GlobalLock secStorageVmLock = GlobalLock.getInternLock(getSecStorageVmLockName(readysecStorageVm.getId())); try { if (secStorageVmLock.lock(ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_SYNC)) { - try { - readysecStorageVm = start(readysecStorageVm.getId(), 0); + try { + readysecStorageVm = start2(readysecStorageVm.getId(), 0); } finally { secStorageVmLock.unlock(); } } else { - if (s_logger.isInfoEnabled()) - s_logger.info("Unable to acquire synchronization lock to start secondary storage vm : " + readysecStorageVm.getHostName()); + if (s_logger.isInfoEnabled()) { + s_logger.info("Unable to acquire synchronization lock to start secondary storage vm : " + readysecStorageVm.getHostName()); + } } } finally { secStorageVmLock.releaseRef(); } } } else { - if (s_logger.isInfoEnabled()) - s_logger.info("Unable to acquire synchronization lock to allocate secondary storage vm storage, wait for next turn"); + if (s_logger.isInfoEnabled()) { + s_logger.info("Unable to acquire synchronization lock to allocate secondary storage vm storage, wait for next turn"); + } } } catch (StorageUnavailableException e) { s_logger.warn("Storage unavailable", e); @@ -1004,6 +1027,8 @@ public class SecondaryStorageManagerImpl implements SecondaryStorageVmManager, V s_logger.warn("insuffiient capacity", e); } catch (ConcurrentOperationException e) { s_logger.debug("Concurrent operation: " + e.getMessage()); + } catch (ResourceUnavailableException e) { + s_logger.debug("Concurrent operation: " + e.getMessage()); } } } @@ -1026,22 +1051,26 @@ public class SecondaryStorageManagerImpl implements SecondaryStorageVmManager, V } private void reallyRun() { - if (s_logger.isTraceEnabled()) - s_logger.trace("Begin secondary storage vm capacity scan"); + if (s_logger.isTraceEnabled()) { + s_logger.trace("Begin secondary storage vm capacity scan"); + } Map zoneHostInfoMap = getZoneHostInfo(); if (isServiceReady(zoneHostInfoMap)) { - if (s_logger.isTraceEnabled()) - s_logger.trace("Sec Storage VM Service is ready, check to see if we need to allocate standby capacity"); + if (s_logger.isTraceEnabled()) { + s_logger.trace("Sec Storage VM 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()) - s_logger.trace("Sec Storage VM Capacity scan lock is used by others, skip and wait for my turn"); + if (s_logger.isTraceEnabled()) { + s_logger.trace("Sec Storage VM Capacity scan lock is used by others, skip and wait for my turn"); + } return; } - if (s_logger.isTraceEnabled()) - s_logger.trace("*** Begining secondary storage vm capacity scan... ***"); + if (s_logger.isTraceEnabled()) { + s_logger.trace("*** Begining secondary storage vm capacity scan... ***"); + } try { checkPendingSecStorageVMs(); @@ -1063,24 +1092,28 @@ public class SecondaryStorageManagerImpl implements SecondaryStorageVmManager, V } } else { - if(s_logger.isDebugEnabled()) - s_logger.debug("Zone " + dc.getId() + " is not ready to alloc secondary storage vm"); + if(s_logger.isDebugEnabled()) { + s_logger.debug("Zone " + dc.getId() + " is not ready to alloc secondary storage vm"); + } } } - if (s_logger.isTraceEnabled()) - s_logger.trace("*** Stop secondary storage vm capacity scan ***"); + if (s_logger.isTraceEnabled()) { + s_logger.trace("*** Stop secondary storage vm capacity scan ***"); + } } finally { _capacityScanLock.unlock(); } } else { - if (s_logger.isTraceEnabled()) - s_logger.trace("Secondary storage vm service is not ready for capacity preallocation, wait for next time"); + if (s_logger.isTraceEnabled()) { + s_logger.trace("Secondary storage vm service is not ready for capacity preallocation, wait for next time"); + } } - if (s_logger.isTraceEnabled()) - s_logger.trace("End of secondary storage vm capacity scan"); + if (s_logger.isTraceEnabled()) { + s_logger.trace("End of secondary storage vm capacity scan"); + } } }; } @@ -1089,8 +1122,9 @@ public class SecondaryStorageManagerImpl implements SecondaryStorageVmManager, V public SecondaryStorageVmVO assignSecStorageVmFromRunningPool(long dataCenterId) { - if (s_logger.isTraceEnabled()) - s_logger.trace("Assign secondary storage vm from running pool for request from data center : " + dataCenterId); + if (s_logger.isTraceEnabled()) { + s_logger.trace("Assign secondary storage vm from running pool for request from data center : " + dataCenterId); + } SecondaryStorageVmAllocator allocator = getCurrentAllocator(); assert (allocator != null); @@ -1098,16 +1132,18 @@ public class SecondaryStorageManagerImpl implements SecondaryStorageVmManager, V if (runningList != null && runningList.size() > 0) { if (s_logger.isTraceEnabled()) { s_logger.trace("Running secondary storage vm pool size : " + runningList.size()); - for (SecondaryStorageVmVO secStorageVm : runningList) - s_logger.trace("Running secStorageVm instance : " + secStorageVm.getHostName()); + for (SecondaryStorageVmVO secStorageVm : runningList) { + s_logger.trace("Running secStorageVm instance : " + secStorageVm.getHostName()); + } } Map loadInfo = new HashMap(); return allocator.allocSecondaryStorageVm(runningList, loadInfo, dataCenterId); } else { - if (s_logger.isTraceEnabled()) - s_logger.trace("Empty running secStorageVm pool for now in data center : " + dataCenterId); + if (s_logger.isTraceEnabled()) { + s_logger.trace("Empty running secStorageVm pool for now in data center : " + dataCenterId); + } } return null; } @@ -1116,21 +1152,24 @@ public class SecondaryStorageManagerImpl implements SecondaryStorageVmManager, V List l = _secStorageVmDao.getSecStorageVmListInStates( dataCenterId, State.Creating, State.Starting, State.Stopped, State.Migrating); - if (l != null && l.size() > 0) - return l.get(0); + if (l != null && l.size() > 0) { + return l.get(0); + } return null; } private void allocCapacity(long dataCenterId) { - if (s_logger.isTraceEnabled()) - s_logger.trace("Allocate secondary storage vm standby capacity for data center : " + dataCenterId); + if (s_logger.isTraceEnabled()) { + s_logger.trace("Allocate secondary storage vm standby capacity for data center : " + dataCenterId); + } boolean secStorageVmFromStoppedPool = false; SecondaryStorageVmVO secStorageVm = assignSecStorageVmFromStoppedPool(dataCenterId); if (secStorageVm == null) { - if (s_logger.isInfoEnabled()) - s_logger.info("No stopped secondary storage vm is available, need to allocate a new secondary storage vm"); + if (s_logger.isInfoEnabled()) { + s_logger.info("No stopped secondary storage vm is available, need to allocate a new secondary storage vm"); + } if (_allocLock.lock(ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_SYNC)) { try { @@ -1139,13 +1178,15 @@ public class SecondaryStorageManagerImpl implements SecondaryStorageVmManager, V _allocLock.unlock(); } } else { - if (s_logger.isInfoEnabled()) - s_logger.info("Unable to acquire synchronization lock to allocate secStorageVm resource for standby capacity, wait for next scan"); + if (s_logger.isInfoEnabled()) { + s_logger.info("Unable to acquire synchronization lock to allocate secStorageVm resource for standby capacity, wait for next scan"); + } return; } } else { - if (s_logger.isInfoEnabled()) - s_logger.info("Found a stopped secondary storage vm, bring it up to running pool. secStorageVm vm id : " + secStorageVm.getId()); + if (s_logger.isInfoEnabled()) { + s_logger.info("Found a stopped secondary storage vm, bring it up to running pool. secStorageVm vm id : " + secStorageVm.getId()); + } secStorageVmFromStoppedPool = true; } @@ -1160,9 +1201,10 @@ public class SecondaryStorageManagerImpl implements SecondaryStorageVmManager, V secStorageVmLock.unlock(); } } else { - if (s_logger.isInfoEnabled()) - s_logger.info("Unable to acquire synchronization lock to start secStorageVm for standby capacity, secStorageVm vm id : " + if (s_logger.isInfoEnabled()) { + s_logger.info("Unable to acquire synchronization lock to start secStorageVm for standby capacity, secStorageVm vm id : " + secStorageVm.getId()); + } return; } } finally { @@ -1170,15 +1212,18 @@ public class SecondaryStorageManagerImpl implements SecondaryStorageVmManager, V } if (secStorageVm == null) { - if (s_logger.isInfoEnabled()) - s_logger.info("Unable to start secondary storage vm for standby capacity, secStorageVm vm Id : " + if (s_logger.isInfoEnabled()) { + s_logger.info("Unable to start secondary storage vm for standby capacity, secStorageVm vm Id : " + secStorageVmId + ", will recycle it and start a new one"); + } - if (secStorageVmFromStoppedPool) - destroySecStorageVm(secStorageVmId, 0); + if (secStorageVmFromStoppedPool) { + destroySecStorageVm(secStorageVmId, 0); + } } else { - if (s_logger.isInfoEnabled()) - s_logger.info("Secondary storage vm " + secStorageVm.getHostName() + " is started"); + if (s_logger.isInfoEnabled()) { + s_logger.info("Secondary storage vm " + secStorageVm.getHostName() + " is started"); + } } } } @@ -1186,8 +1231,9 @@ public class SecondaryStorageManagerImpl implements SecondaryStorageVmManager, V public boolean isServiceReady(Map zoneHostInfoMap) { for (ZoneHostInfo zoneHostInfo : zoneHostInfoMap.values()) { if ((zoneHostInfo.getFlags() & RunningHostInfoAgregator.ZoneHostInfo.ALL_HOST_MASK) != 0){ - if (s_logger.isInfoEnabled()) - s_logger.info("Zone " + zoneHostInfo.getDcId() + " is ready to launch"); + if (s_logger.isInfoEnabled()) { + s_logger.info("Zone " + zoneHostInfo.getDcId() + " is ready to launch"); + } return true; } } @@ -1201,8 +1247,9 @@ public class SecondaryStorageManagerImpl implements SecondaryStorageVmManager, V VMTemplateVO template = _templateDao.findConsoleProxyTemplate(); HostVO secHost = _hostDao.findSecondaryStorageHost(dataCenterId); if (secHost == null) { - if (s_logger.isDebugEnabled()) - s_logger.debug("No secondary storage available in zone " + dataCenterId + ", wait until it is ready to launch secondary storage vm"); + if (s_logger.isDebugEnabled()) { + s_logger.debug("No secondary storage available in zone " + dataCenterId + ", wait until it is ready to launch secondary storage vm"); + } return false; } @@ -1219,12 +1266,14 @@ public class SecondaryStorageManagerImpl implements SecondaryStorageVmManager, V return true; } else { - if (s_logger.isDebugEnabled()) - s_logger.debug("Primary storage is not ready, wait until it is ready to launch secondary storage vm"); + if (s_logger.isDebugEnabled()) { + s_logger.debug("Primary storage is not ready, wait until it is ready to launch secondary storage vm"); + } } } else { - if (s_logger.isTraceEnabled()) - s_logger.trace("Zone host is ready, but secondary storage vm template is not ready"); + if (s_logger.isTraceEnabled()) { + s_logger.trace("Zone host is ready, but secondary storage vm template is not ready"); + } } } return false; @@ -1235,9 +1284,11 @@ public class SecondaryStorageManagerImpl implements SecondaryStorageVmManager, V List l = _hostDao.getRunningHostCounts(new Date(cutTime.getTime() - _clusterMgr.getHeartbeatThreshold())); RunningHostInfoAgregator aggregator = new RunningHostInfoAgregator(); - if (l.size() > 0) - for (RunningHostCountInfo countInfo : l) - aggregator.aggregate(countInfo); + if (l.size() > 0) { + for (RunningHostCountInfo countInfo : l) { + aggregator.aggregate(countInfo); + } + } return aggregator.getZoneHostInfoMap(); } @@ -1249,16 +1300,18 @@ public class SecondaryStorageManagerImpl implements SecondaryStorageVmManager, V @Override public boolean start() { - if (s_logger.isInfoEnabled()) - s_logger.info("Start secondary storage vm manager"); + if (s_logger.isInfoEnabled()) { + s_logger.info("Start secondary storage vm manager"); + } return true; } @Override public boolean stop() { - if (s_logger.isInfoEnabled()) - s_logger.info("Stop secondary storage vm manager"); + if (s_logger.isInfoEnabled()) { + s_logger.info("Stop secondary storage vm manager"); + } _capacityScanScheduler.shutdownNow(); try { @@ -1274,8 +1327,9 @@ public class SecondaryStorageManagerImpl implements SecondaryStorageVmManager, V @Override public boolean configure(String name, Map params) throws ConfigurationException { - if (s_logger.isInfoEnabled()) - s_logger.info("Start configuring secondary storage vm manager : " + name); + if (s_logger.isInfoEnabled()) { + s_logger.info("Start configuring secondary storage vm manager : " + name); + } _name = name; @@ -1387,12 +1441,14 @@ public class SecondaryStorageManagerImpl implements SecondaryStorageVmManager, V } _userVmDao = locator.getDao(UserVmDao.class); - if (_userVmDao == null) - throw new ConfigurationException("Unable to get " + UserVmDao.class.getName()); + if (_userVmDao == null) { + throw new ConfigurationException("Unable to get " + UserVmDao.class.getName()); + } _instanceDao = locator.getDao(VMInstanceDao.class); - if (_instanceDao == null) - throw new ConfigurationException("Unable to get " + VMInstanceDao.class.getName()); + if (_instanceDao == null) { + throw new ConfigurationException("Unable to get " + VMInstanceDao.class.getName()); + } _capacityDao = locator.getDao(CapacityDao.class); if (_capacityDao == null) { @@ -1454,6 +1510,8 @@ public class SecondaryStorageManagerImpl implements SecondaryStorageVmManager, V _itMgr.registerGuru(VirtualMachine.Type.SecondaryStorageVm, this); + _useNewNetworking = Boolean.parseBoolean(configs.get("use.new.networking")); + Adapters ipAllocators = locator.getAdapters(IpAddrAllocator.class); if (ipAllocators != null && ipAllocators.isSet()) { Enumeration it = ipAllocators.enumeration(); @@ -1466,7 +1524,7 @@ public class SecondaryStorageManagerImpl implements SecondaryStorageVmManager, V 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 Secondary Storage VM", 1, _secStorageVmRamSize, 0, 0, 0, false, null, NetworkOffering.GuestIpType.Virtualized, useLocalStorage, true, null, true); + _serviceOffering = new ServiceOfferingVO("System Offering For Secondary Storage VM", 1, _secStorageVmRamSize, 256, 0, 0, false, null, NetworkOffering.GuestIpType.Virtual, useLocalStorage, true, null, true); _serviceOffering.setUniqueName("Cloud.com-SecondaryStorage"); _serviceOffering = _offeringDao.persistSystemServiceOffering(_serviceOffering); _template = _templateDao.findConsoleProxyTemplate(); @@ -1480,8 +1538,9 @@ public class SecondaryStorageManagerImpl implements SecondaryStorageVmManager, V } String configValue = _configDao.getValue("system.vm.use.local.storage"); _useLocalStorage = Boolean.parseBoolean(configValue); - if (s_logger.isInfoEnabled()) - s_logger.info("Secondary storage vm Manager is configured."); + if (s_logger.isInfoEnabled()) { + s_logger.info("Secondary storage vm Manager is configured."); + } return true; } @@ -1502,7 +1561,7 @@ public class SecondaryStorageManagerImpl implements SecondaryStorageVmManager, V @Override public void completeStartCommand(SecondaryStorageVmVO vm) { - _secStorageVmDao.updateIf(vm, VirtualMachine.Event.AgentReportRunning, vm.getHostId()); + _itMgr.stateTransitTo(vm, VirtualMachine.Event.AgentReportRunning, vm.getHostId()); } @Override @@ -1525,7 +1584,7 @@ public class SecondaryStorageManagerImpl implements SecondaryStorageVmManager, V secStorageVm.setGuestIpAddress(null); _dcDao.releaseLinkLocalIpAddress(guestIpAddress, secStorageVm.getDataCenterId(), secStorageVm.getId()); } - if (!_secStorageVmDao.updateIf(secStorageVm, ev, null)) { + if (! _itMgr.stateTransitTo(secStorageVm, ev, null)) { s_logger.debug("Unable to update the secondary storage vm"); return; } @@ -1559,8 +1618,9 @@ public class SecondaryStorageManagerImpl implements SecondaryStorageVmManager, V if (asyncExecutor != null) { AsyncJobVO job = asyncExecutor.getJob(); - if (s_logger.isInfoEnabled()) + if (s_logger.isInfoEnabled()) { s_logger.info("Stop secondary storage vm " + secStorageVmId + ", update async job-" + job.getId()); + } _asyncMgr.updateAsyncJobAttachment(job.getId(), "secStorageVm", secStorageVmId); } long eventId = saveStartedEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM, EventTypes.EVENT_SSVM_STOP, "Stopping secondary storage Vm with Id: "+secStorageVmId, startEventId); @@ -1570,16 +1630,18 @@ public class SecondaryStorageManagerImpl implements SecondaryStorageVmManager, V SecondaryStorageVmVO secStorageVm = _secStorageVmDao.findById(secStorageVmId); if (secStorageVm == null) { String msg = "Stopping secondary storage vm failed: secondary storage vm " + secStorageVmId + " no longer exists"; - if (s_logger.isDebugEnabled()) - s_logger.debug(msg); + if (s_logger.isDebugEnabled()) { + s_logger.debug(msg); + } saveFailedEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM, EventTypes.EVENT_SSVM_STOP, msg, startEventId); return false; } try { return stop(secStorageVm, startEventId); } catch (AgentUnavailableException e) { - if (s_logger.isDebugEnabled()) - s_logger.debug("Stopping secondary storage vm " + secStorageVm.getHostName() + " faled : exception " + e.toString()); + if (s_logger.isDebugEnabled()) { + s_logger.debug("Stopping secondary storage vm " + secStorageVm.getHostName() + " faled : exception " + e.toString()); + } return false; } } @@ -1590,8 +1652,9 @@ public class SecondaryStorageManagerImpl implements SecondaryStorageVmManager, V if (asyncExecutor != null) { AsyncJobVO job = asyncExecutor.getJob(); - if (s_logger.isInfoEnabled()) + if (s_logger.isInfoEnabled()) { s_logger.info("Reboot secondary storage vm " + secStorageVmId + ", update async job-" + job.getId()); + } _asyncMgr.updateAsyncJobAttachment(job.getId(), "secstorage_vm", secStorageVmId); } @@ -1612,8 +1675,9 @@ public class SecondaryStorageManagerImpl implements SecondaryStorageVmManager, V final Answer answer = _agentMgr.easySend(secStorageVm.getHostId(), cmd); if (answer != null) { - if (s_logger.isDebugEnabled()) - s_logger.debug("Successfully reboot secondary storage vm " + secStorageVm.getHostName()); + if (s_logger.isDebugEnabled()) { + s_logger.debug("Successfully reboot secondary storage vm " + secStorageVm.getHostName()); + } SubscriptionMgr.getInstance().notifySubscribers( ALERT_SUBJECT, this, @@ -1634,8 +1698,9 @@ public class SecondaryStorageManagerImpl implements SecondaryStorageVmManager, V } else { String msg = "Rebooting Secondary Storage VM failed - " + secStorageVm.getHostName(); saveFailedEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM, EventTypes.EVENT_SSVM_REBOOT, msg, startEventId); - if (s_logger.isDebugEnabled()) - s_logger.debug(msg); + if (s_logger.isDebugEnabled()) { + s_logger.debug(msg); + } return false; } } else { @@ -1657,8 +1722,9 @@ public class SecondaryStorageManagerImpl implements SecondaryStorageVmManager, V if (asyncExecutor != null) { AsyncJobVO job = asyncExecutor.getJob(); - if (s_logger.isInfoEnabled()) + if (s_logger.isInfoEnabled()) { s_logger.info("Destroy secondary storage vm " + vmId + ", update async job-" + job.getId()); + } _asyncMgr.updateAsyncJobAttachment(job.getId(), "secstorage_vm", vmId); } @@ -1681,7 +1747,7 @@ public class SecondaryStorageManagerImpl implements SecondaryStorageVmManager, V s_logger.debug("Destroying secondary storage vm vm " + vmId); } - if (!_secStorageVmDao.updateIf(vm, VirtualMachine.Event.DestroyRequested, null)) { + if (! _itMgr.stateTransitTo(vm, VirtualMachine.Event.DestroyRequested, null)) { String msg = "Unable to destroy the vm because it is not in the correct state: " + vmId; s_logger.debug(msg); saveFailedEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM, EventTypes.EVENT_SSVM_DESTROY, msg, startEventId); @@ -1702,8 +1768,9 @@ public class SecondaryStorageManagerImpl implements SecondaryStorageVmManager, V txn.start(); // release critical system resources used by the VM before we // delete them - if (vm.getPublicIpAddress() != null) - freePublicIpAddress(vm.getPublicIpAddress(), vm.getDataCenterId(), vm.getPodId()); + if (vm.getPublicIpAddress() != null) { + freePublicIpAddress(vm.getPublicIpAddress(), vm.getDataCenterId(), vm.getPodId()); + } vm.setPublicIpAddress(null); _secStorageVmDao.remove(vm.getId()); @@ -1737,8 +1804,9 @@ public class SecondaryStorageManagerImpl implements SecondaryStorageVmManager, V SecondaryStorageVmVO secStorageVm = _secStorageVmDao.findById(vmId); if (secStorageVm != null) { - if (secStorageVm.getPublicIpAddress() != null) - freePublicIpAddress(secStorageVm.getPublicIpAddress(), secStorageVm.getDataCenterId(), secStorageVm.getPodId()); + if (secStorageVm.getPublicIpAddress() != null) { + freePublicIpAddress(secStorageVm.getPublicIpAddress(), secStorageVm.getDataCenterId(), secStorageVm.getPodId()); + } _secStorageVmDao.remove(vmId); final EventVO event = new EventVO(); @@ -1762,7 +1830,7 @@ public class SecondaryStorageManagerImpl implements SecondaryStorageVmManager, V @Override public boolean stop(SecondaryStorageVmVO secStorageVm, long startEventId) throws AgentUnavailableException { - if (!_secStorageVmDao.updateIf(secStorageVm, VirtualMachine.Event.StopRequested, secStorageVm.getHostId())) { + if (! _itMgr.stateTransitTo(secStorageVm, VirtualMachine.Event.StopRequested, secStorageVm.getHostId())) { String msg = "Unable to stop secondary storage vm: " + secStorageVm.toString(); s_logger.debug(msg); saveFailedEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM, EventTypes.EVENT_SSVM_STOP, msg, startEventId); @@ -1834,7 +1902,7 @@ public class SecondaryStorageManagerImpl implements SecondaryStorageVmManager, V public boolean migrate(SecondaryStorageVmVO secStorageVm, HostVO host) { HostVO fromHost = _hostDao.findById(secStorageVm.getId()); - if (!_secStorageVmDao.updateIf(secStorageVm, VirtualMachine.Event.MigrationRequested, secStorageVm.getHostId())) { + if (! _itMgr.stateTransitTo(secStorageVm, VirtualMachine.Event.MigrationRequested, secStorageVm.getHostId())) { s_logger.debug("State for " + secStorageVm.toString() + " has changed so migration can not take place."); return false; } @@ -1857,18 +1925,18 @@ public class SecondaryStorageManagerImpl implements SecondaryStorageVmManager, V CheckVirtualMachineAnswer answer = (CheckVirtualMachineAnswer) _agentMgr.send(host.getId(), cvm); if (!answer.getResult()) { s_logger.debug("Unable to complete migration for " + secStorageVm.getId()); - _secStorageVmDao.updateIf(secStorageVm, VirtualMachine.Event.AgentReportStopped, null); + _itMgr.stateTransitTo(secStorageVm, 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()); - _secStorageVmDao.updateIf(secStorageVm, VirtualMachine.Event.AgentReportStopped, null); + _itMgr.stateTransitTo(secStorageVm, VirtualMachine.Event.AgentReportStopped, null); return false; } - _secStorageVmDao.updateIf(secStorageVm, VirtualMachine.Event.OperationSucceeded, host.getId()); + _itMgr.stateTransitTo(secStorageVm, VirtualMachine.Event.OperationSucceeded, host.getId()); return true; } @@ -1966,8 +2034,9 @@ public class SecondaryStorageManagerImpl implements SecondaryStorageVmManager, V event.setDescription(description); event.setStartId(startEventId); event = _eventDao.persist(event); - if(event != null) - return event.getId(); + if(event != null) { + return event.getId(); + } return null; } diff --git a/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java b/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java index f53174ec99b..fb7bb279e0d 100755 --- a/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java +++ b/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java @@ -18,8 +18,6 @@ package com.cloud.storage.snapshot; -import java.sql.PreparedStatement; -import java.sql.ResultSet; import java.util.ArrayList; import java.util.Date; import java.util.List; @@ -63,12 +61,11 @@ import com.cloud.event.dao.EventDao; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.PermissionDeniedException; import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.UsageServerException; import com.cloud.host.dao.DetailsDao; import com.cloud.host.dao.HostDao; import com.cloud.storage.Snapshot; -import com.cloud.storage.Snapshot.Type; import com.cloud.storage.Snapshot.Status; +import com.cloud.storage.Snapshot.Type; import com.cloud.storage.SnapshotPolicyVO; import com.cloud.storage.SnapshotScheduleVO; import com.cloud.storage.SnapshotVO; @@ -101,10 +98,10 @@ import com.cloud.utils.component.Inject; import com.cloud.utils.component.Manager; import com.cloud.utils.db.DB; import com.cloud.utils.db.Filter; +import com.cloud.utils.db.JoinBuilder.JoinType; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.Transaction; -import com.cloud.utils.db.JoinBuilder.JoinType; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.vm.VMInstanceVO; import com.cloud.vm.dao.UserVmDao; @@ -112,8 +109,6 @@ import com.cloud.vm.dao.UserVmDao; @Local(value={SnapshotManager.class, SnapshotService.class}) public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Manager { private static final Logger s_logger = Logger.getLogger(SnapshotManagerImpl.class); - private static final String GET_LAST_ID = "SELECT id FROM cloud.snapshots ORDER BY id DESC LIMIT 1"; - private static final String UPDATE_SNAPSHOT_SEQ = "UPDATE cloud.sequence SET value=? WHERE name='snapshots_seq'"; @Inject protected HostDao _hostDao; @Inject protected UserVmDao _vmDao; @@ -315,8 +310,6 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma } return createdSnapshot; - - } @@ -361,7 +354,7 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma public SnapshotVO createSnapshot(CreateSnapshotCmd cmd) throws ResourceAllocationException { Long volumeId = cmd.getVolumeId(); Long policyId = cmd.getPolicyId(); - Long snapshotId = cmd.getId(); + Long snapshotId = cmd.getEntityId(); Long startEventId = cmd.getStartEventId(); return createSnapshotImpl(volumeId, policyId, snapshotId, startEventId); } @@ -1153,40 +1146,6 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma return _snapshotDao.getNextInSequence(Long.class, "id"); } - private Long _getLastId() { - Transaction txn = Transaction.open(Transaction.CLOUD_DB); - PreparedStatement pstmt = null; - String sql = GET_LAST_ID; - try { - pstmt = txn.prepareAutoCloseStatement(sql); - ResultSet rs = pstmt.executeQuery(); - if (rs.next()) { - return Long.valueOf(rs.getLong(1)); - } - } catch (Exception ex) { - s_logger.error("error getting last id", ex); - } - return null; - } - - private void _updateSnapshotSeq(Long seq) { - Transaction txn = Transaction.open(Transaction.CLOUD_DB); - try { - txn.start(); - String sql = UPDATE_SNAPSHOT_SEQ; - PreparedStatement pstmt = null; - pstmt = txn.prepareAutoCloseStatement(sql); - pstmt.setLong(1, seq.longValue()); - pstmt.execute(); - txn.commit(); - } catch (Exception ex) { - txn.rollback(); - String msg = "error seting snapshots_seq to " + seq; - s_logger.error(msg, ex); - throw new CloudRuntimeException(msg, ex); - } - } - @Override public boolean configure(String name, Map params) throws ConfigurationException { _name = name; @@ -1206,14 +1165,6 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma _totalRetries = NumbersUtil.parseInt(configDao.getValue("total.retries"), 4); _pauseInterval = 2*NumbersUtil.parseInt(configDao.getValue("ping.interval"), 60); - Long lastId = _getLastId(); - if ( lastId == null ) { - String msg = "Can not get last id of snapshots"; - s_logger.error(msg); - throw new CloudRuntimeException(msg); - } - s_logger.info("Set shapshot sequence to " + (lastId + 1)); - _updateSnapshotSeq( lastId + 1 ); s_logger.info("Snapshot Manager is configured."); return true; diff --git a/server/src/com/cloud/test/DatabaseConfig.java b/server/src/com/cloud/test/DatabaseConfig.java index b4845430a33..2f0b553b342 100644 --- a/server/src/com/cloud/test/DatabaseConfig.java +++ b/server/src/com/cloud/test/DatabaseConfig.java @@ -752,7 +752,7 @@ public class DatabaseConfig { String guestIpType = _currentObjectParams.get("guestIpType"); NetworkOffering.GuestIpType type = null; if (guestIpType == null) { - type = NetworkOffering.GuestIpType.Virtualized; + type = NetworkOffering.GuestIpType.Virtual; } else { type = NetworkOffering.GuestIpType.valueOf(guestIpType); } diff --git a/server/src/com/cloud/user/AccountManagerImpl.java b/server/src/com/cloud/user/AccountManagerImpl.java index 290c8280104..1bc40aa3508 100755 --- a/server/src/com/cloud/user/AccountManagerImpl.java +++ b/server/src/com/cloud/user/AccountManagerImpl.java @@ -64,6 +64,7 @@ import com.cloud.exception.PermissionDeniedException; import com.cloud.network.IPAddressVO; import com.cloud.network.NetworkManager; import com.cloud.network.dao.IPAddressDao; +import com.cloud.network.router.DomainRouterManager; import com.cloud.network.security.NetworkGroupManager; import com.cloud.server.Criteria; import com.cloud.storage.StorageManager; @@ -120,6 +121,7 @@ public class AccountManagerImpl implements AccountManager, AccountService { @Inject private StorageManager _storageMgr; @Inject private TemplateManager _tmpltMgr; @Inject private ConfigurationManager _configMgr; + @Inject private DomainRouterManager _routerMgr; private final GlobalLock m_resourceCountLock = GlobalLock.getInternLock("resource.count"); @@ -557,7 +559,9 @@ public class AccountManagerImpl implements AccountManager, AccountService { accountId = userAccount.getId(); } - if (accountId != null) domainId = null; + if (accountId != null) { + domainId = null; + } @@ -701,7 +705,6 @@ public class AccountManagerImpl implements AccountManager, AccountService { } } } - private boolean doSetUserStatus(long userId, String state) { UserVO userForUpdate = _userDao.createForUpdate(); @@ -738,6 +741,7 @@ public class AccountManagerImpl implements AccountManager, AccountService { return success; } + @Override public boolean deleteUserInternal(long userId, long startEventId) { UserAccount userAccount = null; Long accountId = null; @@ -789,8 +793,9 @@ public class AccountManagerImpl implements AccountManager, AccountService { return false; }finally{ long domainId = 0L; - if (userAccount != null) + if (userAccount != null) { domainId = userAccount.getDomainId(); + } String description = "User " + username + " (id: " + userId + ") for accountId = " + accountId + " and domainId = " + domainId; if(result){ EventUtils.saveEvent(UserContext.current().getUserId(), accountId, EventVO.LEVEL_INFO, EventTypes.EVENT_USER_DELETE, "Successfully deleted " +description, startEventId); @@ -800,6 +805,7 @@ public class AccountManagerImpl implements AccountManager, AccountService { } } + @Override public boolean deleteAccount(AccountVO account) { long accountId = account.getId(); long userId = 1L; // only admins can delete users, pass in userId 1 XXX: Shouldn't it be userId 2. @@ -852,7 +858,7 @@ public class AccountManagerImpl implements AccountManager, AccountService { boolean routersCleanedUp = true; for (DomainRouterVO router : routers) { - if (!_networkMgr.destroyRouter(router.getId())) { + if (!_routerMgr.destroyRouter(router.getId())) { s_logger.error("Unable to destroy router: " + router.getId()); routersCleanedUp = false; } @@ -866,7 +872,7 @@ public class AccountManagerImpl implements AccountManager, AccountService { } for (IPAddressVO ip : ips) { - List podVlanMaps = _podVlanMapDao.listPodVlanMapsByVlan(ip.getVlanDbId()); + List podVlanMaps = _podVlanMapDao.listPodVlanMapsByVlan(ip.getVlanId()); if (podVlanMaps != null && podVlanMaps.size() != 0) { Long podId = podVlanMaps.get(0).getPodId(); if (podId != null) { @@ -927,6 +933,7 @@ public class AccountManagerImpl implements AccountManager, AccountService { } } + @Override public boolean disableAccount(long accountId) { boolean success = false; if (accountId <= 2) { @@ -963,7 +970,7 @@ public class AccountManagerImpl implements AccountManager, AccountService { List routers = _routerDao.listBy(accountId); for (DomainRouterVO router : routers) { - success = (success && _networkMgr.stopRouter(router.getId(), 0)); + success = (success && _routerMgr.stopRouter(router.getId(), 0)); } return success; @@ -1168,8 +1175,9 @@ public class AccountManagerImpl implements AccountManager, AccountService { //Check if user exists in the system User user = _userDao.findById(userId); - if ((user == null) || (user.getRemoved() != null)) + if ((user == null) || (user.getRemoved() != null)) { throw new InvalidParameterValueException("Unable to find active user by id " + userId); + } // If the user is a System user, return an error Account account = _accountDao.findById(user.getAccountId()); @@ -1191,10 +1199,11 @@ public class AccountManagerImpl implements AccountManager, AccountService { } // there are no enabled users attached to this user's account, disable the account - if (disableAccount(user.getAccountId())) + if (disableAccount(user.getAccountId())) { return _userAccountDao.findById(userId); - else + } else { throw new CloudRuntimeException("Unable to disable corresponding account for the user " + userId); + } } else { throw new CloudRuntimeException("Unable to disable user " + userId); @@ -1209,8 +1218,9 @@ public class AccountManagerImpl implements AccountManager, AccountService { //Check if user exists in the system User user = _userDao.findById(userId); - if ((user == null) || (user.getRemoved() != null)) + if ((user == null) || (user.getRemoved() != null)) { throw new InvalidParameterValueException("Unable to find active user by id " + userId); + } // If the user is a System user, return an error Account account = _accountDao.findById(user.getAccountId()); @@ -1227,9 +1237,11 @@ public class AccountManagerImpl implements AccountManager, AccountService { // make sure the account is enabled too success = (success && enableAccount(user.getAccountId())); - if (success) + if (success) { return _userAccountDao.findById(userId); - else throw new CloudRuntimeException("Unable to enable user " + userId); + } else { + throw new CloudRuntimeException("Unable to enable user " + userId); + } } @Override @@ -1283,10 +1295,11 @@ public class AccountManagerImpl implements AccountManager, AccountService { } } - if (success) + if (success) { return _userAccountDao.findById(id); - else + } else { throw new CloudRuntimeException("Unable to lock user " + id); + } } @Override @@ -1335,10 +1348,11 @@ public class AccountManagerImpl implements AccountManager, AccountService { } success = enableAccount(account.getId()); - if (success) + if (success) { return _accountDao.findById(account.getId()); - else + } else { throw new CloudRuntimeException("Unable to enable account " + accountName + " in domain " + domainId); + } } @Override @@ -1361,10 +1375,11 @@ public class AccountManagerImpl implements AccountManager, AccountService { throw new InvalidParameterValueException("can not lock system account"); } - if (lockAccountInternal(account.getId())) + if (lockAccountInternal(account.getId())) { return _accountDao.findById(account.getId()); - else + } else { throw new CloudRuntimeException("Unable to lock account " + accountName + " in domain " + domainId); + } } @Override @@ -1381,10 +1396,11 @@ public class AccountManagerImpl implements AccountManager, AccountService { if (account == null) { throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain " + domainId); } - if (disableAccount(account.getId())) + if (disableAccount(account.getId())) { return _accountDao.findById(account.getId()); - else + } else { throw new CloudRuntimeException("Unable to update account " + accountName + " in domain " + domainId); + } } @Override @@ -1426,10 +1442,11 @@ public class AccountManagerImpl implements AccountManager, AccountService { acctForUpdate.setAccountName(newAccountName); success = _accountDao.update(Long.valueOf(account.getId()), acctForUpdate); } - if (success) + if (success) { return _accountDao.findById(account.getId()); - else + } else { throw new CloudRuntimeException("Unable to update account " + accountName + " in domain " + domainId); + } } } diff --git a/server/src/com/cloud/vm/MauriceMoss.java b/server/src/com/cloud/vm/MauriceMoss.java index a435d05e83d..9db342e3471 100644 --- a/server/src/com/cloud/vm/MauriceMoss.java +++ b/server/src/com/cloud/vm/MauriceMoss.java @@ -19,6 +19,7 @@ package com.cloud.vm; import java.util.ArrayList; import java.util.HashMap; +import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.UUID; @@ -31,17 +32,21 @@ import org.apache.log4j.Logger; import com.cloud.agent.AgentManager; import com.cloud.agent.AgentManager.OnError; import com.cloud.agent.api.Answer; +import com.cloud.agent.api.PrepareForMigrationCommand; import com.cloud.agent.api.Start2Command; import com.cloud.agent.api.StopAnswer; import com.cloud.agent.api.StopCommand; import com.cloud.agent.api.to.VirtualMachineTO; import com.cloud.agent.manager.Commands; +import com.cloud.capacity.dao.CapacityDao; import com.cloud.cluster.ClusterManager; import com.cloud.cluster.ClusterManagerListener; import com.cloud.cluster.ManagementServerHostVO; import com.cloud.configuration.Config; import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.dc.DataCenter; +import com.cloud.dc.DataCenterVO; +import com.cloud.dc.HostPodVO; import com.cloud.deploy.DataCenterDeployment; import com.cloud.deploy.DeployDestination; import com.cloud.deploy.DeploymentPlan; @@ -57,6 +62,8 @@ import com.cloud.exception.InsufficientServerCapacityException; import com.cloud.exception.OperationTimedoutException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.exception.StorageUnavailableException; +import com.cloud.host.Host; +import com.cloud.host.HostVO; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.hypervisor.HypervisorGuru; import com.cloud.network.NetworkVO; @@ -66,7 +73,9 @@ import com.cloud.service.dao.ServiceOfferingDao; import com.cloud.storage.DiskOfferingVO; import com.cloud.storage.Storage.ImageFormat; import com.cloud.storage.StorageManager; +import com.cloud.storage.StoragePoolVO; import com.cloud.storage.VMTemplateVO; +import com.cloud.storage.VolumeVO; import com.cloud.storage.Volume.VolumeType; import com.cloud.storage.dao.VMTemplateDao; import com.cloud.user.Account; @@ -82,8 +91,13 @@ import com.cloud.utils.component.Inject; import com.cloud.utils.db.DB; import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; +import com.cloud.utils.fsm.StateMachine2; import com.cloud.vm.ItWorkVO.Type; import com.cloud.vm.VirtualMachine.Event; +import com.cloud.vm.dao.ConsoleProxyDao; +import com.cloud.vm.dao.DomainRouterDao; +import com.cloud.vm.dao.SecondaryStorageVmDao; +import com.cloud.vm.dao.UserVmDao; import com.cloud.vm.dao.VMInstanceDao; @Local(value=VmManager.class) @@ -102,12 +116,19 @@ public class MauriceMoss implements VmManager, ClusterManagerListener { @Inject private DomainDao _domainDao; @Inject private ClusterManager _clusterMgr; @Inject private ItWorkDao _workDao; + @Inject private CapacityDao _capacityDao; + @Inject private UserVmDao _userVmDao; + @Inject private DomainRouterDao _routerDao; + @Inject private ConsoleProxyDao _consoleDao; + @Inject private SecondaryStorageVmDao _secondaryDao; @Inject(adapter=DeploymentPlanner.class) private Adapters _planners; + private boolean _useNewNetworking; Map> _vmGurus = new HashMap>(); Map _hvGurus = new HashMap(); + private StateMachine2 _stateMachine; private int _retry; private long _nodeId; @@ -170,7 +191,7 @@ public class MauriceMoss implements VmManager, ClusterManagerListener { _storageMgr.allocateRawVolume(VolumeType.DATADISK, "DATA-" + vm.getId(), offering.first(), offering.second(), vm, owner); } - _vmDao.updateIf(vm, Event.OperationSucceeded, null); + stateTransitTo(vm, Event.OperationSucceeded, null); txn.commit(); if (s_logger.isDebugEnabled()) { s_logger.debug("Allocation completed for VM: " + vm); @@ -234,7 +255,7 @@ public class MauriceMoss implements VmManager, ClusterManagerListener { if (s_logger.isDebugEnabled()) { s_logger.debug("Destroying vm " + vm); } - if (!_vmDao.updateIf(vm, VirtualMachine.Event.DestroyRequested, vm.getHostId())) { + if (!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()); return false; } @@ -260,7 +281,7 @@ public class MauriceMoss implements VmManager, ClusterManagerListener { ConfigurationDao configDao = locator.getDao(ConfigurationDao.class); Map params = configDao.getConfiguration(xmlParams); - _retry = NumbersUtil.parseInt(params.get(Config.StartRetry.key()), 2); + _retry = NumbersUtil.parseInt(params.get(Config.StartRetry.key()), 10); ReservationContextImpl.setComponents(_userDao, _domainDao, _accountDao); VirtualMachineProfileImpl.setComponents(_offeringDao, _templateDao, _accountDao); @@ -272,6 +293,9 @@ public class MauriceMoss implements VmManager, ClusterManagerListener { _nodeId = _clusterMgr.getId(); _clusterMgr.registerListener(this); + _useNewNetworking = Boolean.parseBoolean(configDao.getValue("use.new.networking")); + + setStateMachine(); return true; } @@ -320,15 +344,21 @@ public class MauriceMoss implements VmManager, ClusterManagerListener { vm.setReservationId(work.getId()); - if (!_vmDao.updateIf(vm, Event.StartRequested, null)) { + if (!stateTransitTo(vm, Event.StartRequested, null)) { throw new ConcurrentOperationException("Unable to start vm " + vm + " due to concurrent operations"); } ExcludeList avoids = new ExcludeList(); int retry = _retry; - while (retry-- != 0) { // It's != so that it can match -1. + DeployDestination dest = null; + while (retry-- != 0) { // It's != so that it can match -1. + /*this will release resource allocated on dest host*/ + if (retry < (_retry -1)) { + stateTransitTo(vm, Event.OperationRetry, dest.getHost().getId()); + } + VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vm, template, offering, null, params); - DeployDestination dest = null; + for (DeploymentPlanner planner : _planners) { dest = planner.plan(vmProfile, plan, avoids); if (dest != null) { @@ -339,19 +369,21 @@ public class MauriceMoss implements VmManager, ClusterManagerListener { } if (dest == null) { + stateTransitTo(vm, Event.OperationFailed, null); throw new InsufficientServerCapacityException("Unable to create a deployment for " + vmProfile, DataCenter.class, plan.getDataCenterId()); } vm.setDataCenterId(dest.getDataCenter().getId()); - vm.setPodId(dest.getPod().getId()); - _vmDao.updateIf(vm, Event.OperationRetry, dest.getHost().getId()); + vm.setPodId(dest.getPod().getId()); try { _storageMgr.prepare(vmProfile, dest); } catch (ConcurrentOperationException e) { + stateTransitTo(vm, Event.OperationFailed, dest.getHost().getId()); throw e; } catch (StorageUnavailableException e) { s_logger.warn("Unable to contact storage.", e); + avoids.addCluster(dest.getCluster().getId()); continue; } _networkMgr.prepare(vmProfile, dest, context); @@ -367,7 +399,7 @@ public class MauriceMoss implements VmManager, ClusterManagerListener { try { Answer[] answers = _agentMgr.send(dest.getHost().getId(), cmds); if (answers[0].getResult() && vmGuru.finalizeStart(cmds, vmProfile, dest, context)) { - if (!_vmDao.updateIf(vm, Event.OperationSucceeded, dest.getHost().getId())) { + if (!stateTransitTo(vm, Event.OperationSucceeded, dest.getHost().getId())) { throw new CloudRuntimeException("Unable to transition to a new state."); } return vm; @@ -382,6 +414,8 @@ public class MauriceMoss implements VmManager, ClusterManagerListener { } } + stateTransitTo(vm, Event.OperationFailed, dest.getHost().getId()); + if (s_logger.isDebugEnabled()) { s_logger.debug("Creation complete for VM " + vm); } @@ -404,7 +438,7 @@ public class MauriceMoss implements VmManager, ClusterManagerListener { return true; } - if (!_vmDao.updateIf(vm, Event.StopRequested, vm.getHostId())) { + if (!stateTransitTo(vm, Event.StopRequested, vm.getHostId())) { throw new ConcurrentOperationException("VM is being operated on by someone else."); } @@ -433,7 +467,7 @@ public class MauriceMoss implements VmManager, ClusterManagerListener { } } finally { if (!stopped) { - _vmDao.updateIf(vm, Event.OperationFailed, vm.getHostId()); + stateTransitTo(vm, Event.OperationFailed, vm.getHostId()); } } @@ -442,7 +476,7 @@ public class MauriceMoss implements VmManager, ClusterManagerListener { } boolean cleanup = false; - + VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm); try { _networkMgr.release(profile); @@ -468,7 +502,8 @@ public class MauriceMoss implements VmManager, ClusterManagerListener { } vm.setReservationId(null); - _vmDao.updateIf(vm, Event.OperationSucceeded, null); + + stateTransitTo(vm, Event.OperationSucceeded, null); if (cleanup) { ItWorkVO work = new ItWorkVO(reservationId, _nodeId, Type.Cleanup); @@ -487,4 +522,72 @@ public class MauriceMoss implements VmManager, ClusterManagerListener { public void onManagementNodeLeft(List nodeList, long selfNodeId) { } + private void setStateMachine() { + _stateMachine = new StateMachine2(); + + _stateMachine.addTransition(null, VirtualMachine.Event.CreateRequested, State.Creating); + _stateMachine.addTransition(State.Creating, VirtualMachine.Event.OperationSucceeded, State.Stopped); + _stateMachine.addTransition(State.Creating, VirtualMachine.Event.OperationFailed, State.Destroyed); + _stateMachine.addTransition(State.Stopped, VirtualMachine.Event.StartRequested, State.Starting); + _stateMachine.addTransition(State.Stopped, VirtualMachine.Event.DestroyRequested, State.Destroyed); + _stateMachine.addTransition(State.Stopped, VirtualMachine.Event.StopRequested, State.Stopped); + _stateMachine.addTransition(State.Stopped, VirtualMachine.Event.AgentReportStopped, State.Stopped); + _stateMachine.addTransition(State.Starting, VirtualMachine.Event.OperationRetry, State.Starting); + _stateMachine.addTransition(State.Starting, VirtualMachine.Event.OperationSucceeded, State.Running); + _stateMachine.addTransition(State.Starting, VirtualMachine.Event.OperationFailed, State.Stopped); + _stateMachine.addTransition(State.Starting, VirtualMachine.Event.AgentReportRunning, State.Running); + _stateMachine.addTransition(State.Starting, VirtualMachine.Event.AgentReportStopped, State.Stopped); + _stateMachine.addTransition(State.Destroyed, VirtualMachine.Event.RecoveryRequested, State.Stopped); + _stateMachine.addTransition(State.Destroyed, VirtualMachine.Event.ExpungeOperation, State.Expunging); + _stateMachine.addTransition(State.Creating, VirtualMachine.Event.MigrationRequested, State.Destroyed); + _stateMachine.addTransition(State.Running, VirtualMachine.Event.MigrationRequested, State.Migrating); + _stateMachine.addTransition(State.Running, VirtualMachine.Event.AgentReportRunning, State.Running); + _stateMachine.addTransition(State.Running, VirtualMachine.Event.AgentReportStopped, State.Stopped); + _stateMachine.addTransition(State.Running, VirtualMachine.Event.StopRequested, State.Stopping); + _stateMachine.addTransition(State.Migrating, VirtualMachine.Event.MigrationRequested, State.Migrating); + _stateMachine.addTransition(State.Migrating, VirtualMachine.Event.OperationSucceeded, State.Running); + _stateMachine.addTransition(State.Migrating, VirtualMachine.Event.OperationFailed, State.Running); + _stateMachine.addTransition(State.Migrating, VirtualMachine.Event.MigrationFailedOnSource, State.Running); + _stateMachine.addTransition(State.Migrating, VirtualMachine.Event.MigrationFailedOnDest, State.Running); + _stateMachine.addTransition(State.Migrating, VirtualMachine.Event.AgentReportRunning, State.Running); + _stateMachine.addTransition(State.Migrating, VirtualMachine.Event.AgentReportStopped, State.Stopped); + _stateMachine.addTransition(State.Stopping, VirtualMachine.Event.OperationSucceeded, State.Stopped); + _stateMachine.addTransition(State.Stopping, VirtualMachine.Event.OperationFailed, State.Running); + _stateMachine.addTransition(State.Stopping, VirtualMachine.Event.AgentReportRunning, State.Running); + _stateMachine.addTransition(State.Stopping, VirtualMachine.Event.AgentReportStopped, State.Stopped); + _stateMachine.addTransition(State.Stopping, VirtualMachine.Event.StopRequested, State.Stopping); + _stateMachine.addTransition(State.Expunging, VirtualMachine.Event.OperationFailed, State.Expunging); + _stateMachine.addTransition(State.Expunging, VirtualMachine.Event.ExpungeOperation, State.Expunging); + + _stateMachine.registerListener(new VMStateListener(_capacityDao, _offeringDao)); + } + + @Override + public boolean stateTransitTo(VMInstanceVO vm, VirtualMachine.Event e, Long id) { + if (_useNewNetworking) { + if (vm instanceof UserVmVO) { + return _stateMachine.transitTO(vm, e, id, _userVmDao); + } else if (vm instanceof ConsoleProxyVO) { + return _stateMachine.transitTO(vm, e, id, _consoleDao); + } else if (vm instanceof SecondaryStorageVmVO) { + return _stateMachine.transitTO(vm, e, id, _secondaryDao); + } else if (vm instanceof DomainRouterVO) { + return _stateMachine.transitTO(vm, e, id, _routerDao); + } else { + return _stateMachine.transitTO(vm, e, id, _vmDao); + } + } else { + if (vm instanceof UserVmVO) { + return _userVmDao.updateIf((UserVmVO)vm, e, id); + } else if (vm instanceof ConsoleProxyVO) { + return _consoleDao.updateIf((ConsoleProxyVO)vm, e, id); + } else if (vm instanceof SecondaryStorageVmVO) { + return _secondaryDao.updateIf((SecondaryStorageVmVO)vm, e, id); + } else if (vm instanceof DomainRouterVO) { + return _routerDao.updateIf((DomainRouterVO)vm, e, id); + } else { + return _vmDao.updateIf(vm, e, id); + } + } + } } diff --git a/server/src/com/cloud/vm/UserVmManagerImpl.java b/server/src/com/cloud/vm/UserVmManagerImpl.java index 4033f5853ee..003ffcdd69f 100755 --- a/server/src/com/cloud/vm/UserVmManagerImpl.java +++ b/server/src/com/cloud/vm/UserVmManagerImpl.java @@ -70,7 +70,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; @@ -128,10 +127,8 @@ import com.cloud.host.HostVO; import com.cloud.host.dao.DetailsDao; import com.cloud.host.dao.HostDao; import com.cloud.hypervisor.Hypervisor.HypervisorType; -import com.cloud.network.FirewallRuleVO; import com.cloud.network.IPAddressVO; import com.cloud.network.IpAddrAllocator; -import com.cloud.network.LoadBalancerVMMapVO; import com.cloud.network.NetworkManager; import com.cloud.network.NetworkVO; import com.cloud.network.Networks.TrafficType; @@ -140,12 +137,12 @@ import com.cloud.network.dao.IPAddressDao; import com.cloud.network.dao.LoadBalancerDao; import com.cloud.network.dao.LoadBalancerVMMapDao; import com.cloud.network.dao.NetworkDao; +import com.cloud.network.router.DomainRouterManager; import com.cloud.network.router.VirtualRouter.Role; import com.cloud.network.security.NetworkGroupManager; import com.cloud.network.security.NetworkGroupVO; import com.cloud.offering.NetworkOffering; import com.cloud.offering.ServiceOffering; -import com.cloud.offerings.NetworkOfferingVO; import com.cloud.offerings.dao.NetworkOfferingDao; import com.cloud.service.ServiceOfferingVO; import com.cloud.service.dao.ServiceOfferingDao; @@ -204,7 +201,6 @@ import com.cloud.vm.dao.DomainRouterDao; import com.cloud.vm.dao.InstanceGroupDao; import com.cloud.vm.dao.InstanceGroupVMMapDao; import com.cloud.vm.dao.UserVmDao; - @Local(value={UserVmManager.class, UserVmService.class}) public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualMachineGuru, Manager, VirtualMachineManager { private static final Logger s_logger = Logger.getLogger(UserVmManagerImpl.class); @@ -256,6 +252,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM @Inject InstanceGroupVMMapDao _groupVMMapDao; @Inject VmManager _itMgr; @Inject NetworkDao _networkDao; + @Inject DomainRouterManager _routerMgr; private IpAddrAllocator _IpAllocator; ScheduledExecutorService _executor = null; @@ -328,10 +325,11 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM VMTemplateVO template = _templateDao.findById(vmInstance.getTemplateId()); if (template.getEnablePassword()) { - if (vmInstance.getDomainRouterId() == null) - /*TODO: add it for external dhcp mode*/ + if (vmInstance.getDomainRouterId() == null) { + /*TODO: add it for external dhcp mode*/ return true; - if (_networkMgr.savePasswordToRouter(vmInstance.getDomainRouterId(), vmInstance.getPrivateIpAddress(), password)) { + } + if (_routerMgr.savePasswordToRouter(vmInstance.getDomainRouterId(), vmInstance.getPrivateIpAddress(), password)) { // Need to reboot the virtual machine so that the password gets redownloaded from the DomR, and reset on the VM if (!rebootVirtualMachine(userId, vmId)) { if (vmInstance.getState() == State.Stopped) { @@ -418,11 +416,13 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM // If the account is not an admin, check that the volume and the virtual machine are owned by the account that was passed in if (account != null) { if (!isAdmin(account.getType())) { - if (account.getId() != volume.getAccountId()) + if (account.getId() != volume.getAccountId()) { throw new PermissionDeniedException("Unable to find volume with ID: " + volumeId + " for account: " + account.getAccountName() + ". Permission denied."); + } - if (account.getId() != vm.getAccountId()) + if (account.getId() != vm.getAccountId()) { throw new PermissionDeniedException("Unable to find VM with ID: " + vmId + " for account: " + account.getAccountName() + ". Permission denied"); + } } else { if (!_domainDao.isChildDomain(account.getDomainId(), volume.getDomainId()) || !_domainDao.isChildDomain(account.getDomainId(), vm.getDomainId())) { @@ -538,8 +538,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM if(asyncExecutor != null) { AsyncJobVO job = asyncExecutor.getJob(); - if(s_logger.isInfoEnabled()) - s_logger.info("Trying to attaching volume " + volumeId +" to vm instance:"+vm.getId()+ ", update async job-" + job.getId() + " progress status"); + if(s_logger.isInfoEnabled()) { + s_logger.info("Trying to attaching volume " + volumeId +" to vm instance:"+vm.getId()+ ", update async job-" + job.getId() + " progress status"); + } _asyncMgr.updateAsyncJobAttachment(job.getId(), "volume", volumeId); _asyncMgr.updateAsyncJobStatus(job.getId(), BaseCmd.PROGRESS_INSTANCE_CREATED, volumeId); @@ -552,13 +553,14 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM if(hostId == null) { hostId = vm.getLastHostId(); HostVO host = _hostDao.findById(hostId); - if(host != null && host.getHypervisorType() == HypervisorType.VmWare) - sendCommand = true; + if(host != null && host.getHypervisorType() == HypervisorType.VmWare) { + sendCommand = true; + } } if (sendCommand) { StoragePoolVO volumePool = _storagePoolDao.findById(volume.getPoolId()); - AttachVolumeCommand cmd = new AttachVolumeCommand(true, vm.getInstanceName(), volume.getPoolType(), volume.getFolder(), volume.getPath(), volume.getName(), deviceId); + AttachVolumeCommand cmd = new AttachVolumeCommand(true, vm.getInstanceName(), volume.getPoolType(), volume.getFolder(), volume.getPath(), volume.getName(), deviceId, volume.getChainInfo()); cmd.setPoolUuid(volumePool.getUuid()); try { @@ -581,18 +583,20 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM } else { _volsDao.attachVolume(volume.getId(), vmId, deviceId); } - if(!vm.getHostName().equals(vm.getDisplayName())) - event.setDescription("Volume: " +volume.getName()+ " successfully attached to VM: "+vm.getHostName()+"("+vm.getDisplayName()+")"); - else - event.setDescription("Volume: " +volume.getName()+ " successfully attached to VM: "+vm.getHostName()); + if(!vm.getHostName().equals(vm.getDisplayName())) { + event.setDescription("Volume: " +volume.getName()+ " successfully attached to VM: "+vm.getHostName()+"("+vm.getDisplayName()+")"); + } else { + event.setDescription("Volume: " +volume.getName()+ " successfully attached to VM: "+vm.getHostName()); + } event.setLevel(EventVO.LEVEL_INFO); _eventDao.persist(event); return _volsDao.findById(volumeId); } else { if (answer != null) { String details = answer.getDetails(); - if (details != null && !details.isEmpty()) - errorMsg += "; " + details; + if (details != null && !details.isEmpty()) { + errorMsg += "; " + details; + } } throw new CloudRuntimeException(errorMsg); } @@ -634,13 +638,15 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM } // Check that the volume ID is valid - if (volume == null) - throw new ServerApiException(BaseCmd.PARAM_ERROR, "Unable to find volume with ID: " + volumeId); + if (volume == null) { + throw new ServerApiException(BaseCmd.PARAM_ERROR, "Unable to find volume with ID: " + volumeId); + } // If the account is not an admin, check that the volume is owned by the account that was passed in if (!isAdmin) { - if (account.getId() != volume.getAccountId()) - throw new ServerApiException(BaseCmd.PARAM_ERROR, "Unable to find volume with ID: " + volumeId + " for account: " + account.getAccountName()); + if (account.getId() != volume.getAccountId()) { + throw new ServerApiException(BaseCmd.PARAM_ERROR, "Unable to find volume with ID: " + volumeId + " for account: " + account.getAccountName()); + } } else if (account != null) { if (!_domainDao.isChildDomain(account.getDomainId(), volume.getDomainId())) { throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, "Unable to detach volume with ID: " + volumeId + ", permission denied."); @@ -674,8 +680,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM if(asyncExecutor != null) { AsyncJobVO job = asyncExecutor.getJob(); - if(s_logger.isInfoEnabled()) - s_logger.info("Trying to attaching volume " + volumeId +"to vm instance:"+vm.getId()+ ", update async job-" + job.getId() + " progress status"); + if(s_logger.isInfoEnabled()) { + s_logger.info("Trying to attaching volume " + volumeId +"to vm instance:"+vm.getId()+ ", update async job-" + job.getId() + " progress status"); + } _asyncMgr.updateAsyncJobAttachment(job.getId(), "volume", volumeId); _asyncMgr.updateAsyncJobStatus(job.getId(), BaseCmd.PROGRESS_INSTANCE_CREATED, volumeId); @@ -686,7 +693,8 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM Answer answer = null; if (sendCommand) { - AttachVolumeCommand cmd = new AttachVolumeCommand(false, vm.getInstanceName(), volume.getPoolType(), volume.getFolder(), volume.getPath(), volume.getName(), cmmd.getDeviceId() != null ? cmmd.getDeviceId() : volume.getDeviceId()); + AttachVolumeCommand cmd = new AttachVolumeCommand(false, vm.getInstanceName(), volume.getPoolType(), volume.getFolder(), volume.getPath(), volume.getName(), + cmmd.getDeviceId() != null ? cmmd.getDeviceId() : volume.getDeviceId(), volume.getChainInfo()); StoragePoolVO volumePool = _storagePoolDao.findById(volume.getPoolId()); cmd.setPoolUuid(volumePool.getUuid()); @@ -707,10 +715,16 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM if (!sendCommand || (answer != null && answer.getResult())) { // Mark the volume as detached _volsDao.detachVolume(volume.getId()); - if(!vm.getHostName().equals(vm.getDisplayName())) - event.setDescription("Volume: " +volume.getName()+ " successfully detached from VM: "+vm.getHostName()+"("+vm.getDisplayName()+")"); - else - event.setDescription("Volume: " +volume.getName()+ " successfully detached from VM: "+vm.getHostName()); + if(answer != null && answer instanceof AttachVolumeAnswer) { + volume.setChainInfo(((AttachVolumeAnswer)answer).getChainInfo()); + _volsDao.update(volume.getId(), volume); + } + + if(!vm.getHostName().equals(vm.getDisplayName())) { + event.setDescription("Volume: " +volume.getName()+ " successfully detached from VM: "+vm.getHostName()+"("+vm.getDisplayName()+")"); + } else { + event.setDescription("Volume: " +volume.getName()+ " successfully detached from VM: "+vm.getHostName()); + } event.setLevel(EventVO.LEVEL_INFO); _eventDao.persist(event); @@ -719,8 +733,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM if (answer != null) { String details = answer.getDetails(); - if (details != null && !details.isEmpty()) - errorMsg += "; " + details; + if (details != null && !details.isEmpty()) { + errorMsg += "; " + details; + } } throw new CloudRuntimeException(errorMsg); @@ -781,13 +796,14 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM // TODO following implementation only do asynchronized operation at API level try { UserVmVO vm = start(param.getUserId(), param.getVmId(), null, param.getIsoPath(), param.getEventId()); - if(vm != null) - executor.getAsyncJobMgr().completeAsyncJob(executor.getJob().getId(), + if(vm != null) { + executor.getAsyncJobMgr().completeAsyncJob(executor.getJob().getId(), AsyncJobResult.STATUS_SUCCEEDED, 0, VMExecutorHelper.composeResultObject( executor.getAsyncJobMgr().getExecutorContext().getManagementServer(), vm, null)); - else - executor.getAsyncJobMgr().completeAsyncJob(executor.getJob().getId(), + } else { + executor.getAsyncJobMgr().completeAsyncJob(executor.getJob().getId(), AsyncJobResult.STATUS_FAILED, BaseCmd.INTERNAL_ERROR, "Unable to start vm"); + } } catch (StorageUnavailableException e) { s_logger.debug("Unable to start vm because storage is unavailable: " + e.getMessage()); @@ -881,7 +897,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM StoragePoolVO sp = _storageMgr.getStoragePoolForVm(vm.getId()); VMTemplateVO template = _templateDao.findById(vm.getTemplateId()); - ServiceOffering offering = _offeringDao.findById(vm.getServiceOfferingId()); + ServiceOfferingVO offering = _offeringDao.findById(vm.getServiceOfferingId()); // If an ISO path is passed in, boot from that ISO // Else, check if the VM already has an ISO attached to it. If so, start the VM with that ISO inserted, but don't boot from it. @@ -912,12 +928,14 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM HostVO host = null; if(vm.getLastHostId() != null) { host = _hostDao.findById(vm.getLastHostId()); - if(host == null || host.getStatus() != com.cloud.host.Status.Up || host.getHypervisorType() != HypervisorType.VmWare) - host = null; + if(host == null || host.getStatus() != com.cloud.host.Status.Up || host.getHypervisorType() != HypervisorType.VmWare) { + host = null; + } } - if(host == null) - host = (HostVO) _agentMgr.findHost(Host.Type.Routing, dc, pod, sp, offering, template, vm, null, avoid); + if(host == null) { + host = (HostVO) _agentMgr.findHost(Host.Type.Routing, dc, pod, sp, offering, template, vm, null, avoid); + } if (host == null) { String description = "Unable to find any host for " + vm.toString(); @@ -928,7 +946,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM return null; } - if (!_vmDao.updateIf(vm, VirtualMachine.Event.StartRequested, host.getId())) { + if (!_itMgr.stateTransitTo(vm, VirtualMachine.Event.StartRequested, host.getId())) { String description = "Unable to start VM " + vm.toString() + " because the state is not correct."; s_logger.error(description); event.setDescription(description); @@ -945,14 +963,15 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM String vnet = null; DomainRouterVO router = null; if (vm.getDomainRouterId() != null) { - router = _networkMgr.addVirtualMachineToGuestNetwork(vm, password, startEventId); + router = _routerMgr.addVirtualMachineToGuestNetwork(vm, password, startEventId); if (router == null) { s_logger.error("Unable to add vm " + vm.getId() + " - " + vm.getHostName()); - _vmDao.updateIf(vm, VirtualMachine.Event.OperationFailed, null); - if(!vm.getHostName().equals(vm.getDisplayName())) - event.setDescription("Unable to start VM: " + vm.getHostName()+"("+vm.getDisplayName()+")" + "; Unable to add VM to guest network"); - else - event.setDescription("Unable to start VM: " + vm.getHostName() + "; Unable to add VM to guest network"); + _itMgr.stateTransitTo(vm, VirtualMachine.Event.OperationFailed, null); + if(!vm.getHostName().equals(vm.getDisplayName())) { + event.setDescription("Unable to start VM: " + vm.getHostName()+"("+vm.getDisplayName()+")" + "; Unable to add VM to guest network"); + } else { + event.setDescription("Unable to start VM: " + vm.getHostName() + "; Unable to add VM to guest network"); + } event.setLevel(EventVO.LEVEL_ERROR); _eventDao.persist(event); @@ -967,7 +986,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM //VM is in a different Pod if(router.getZoneVlan() == null){ //Create Zone Vlan if not created already - vnet = _networkMgr.createZoneVlan(router); + vnet = _routerMgr.createZoneVlan(router); if (vnet == null) { s_logger.error("Vlan creation failed. Unable to add vm " + vm.getId() + " - " + vm.getHostName()); return null; @@ -1015,7 +1034,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM if( retry < _retry ) { - if (!_vmDao.updateIf(vm, VirtualMachine.Event.OperationRetry, host.getId())) { + if (!_itMgr.stateTransitTo(vm, VirtualMachine.Event.OperationRetry, host.getId())) { String description = "Unable to start VM " + vm.toString() + " because the state is not correct."; s_logger.debug(description); event.setDescription(description); @@ -1096,21 +1115,23 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM } while (--retry > 0 && (host = (HostVO)_agentMgr.findHost(Host.Type.Routing, dc, pod, sp, offering, template, vm, null, avoid)) != null); if (host == null || retry <= 0) { - if(!vm.getHostName().equals(vm.getDisplayName())) + if(!vm.getHostName().equals(vm.getDisplayName())) { event.setDescription("Unable to start VM: " + vm.getHostName()+"("+vm.getDisplayName()+")"+ " Reason: "+answer.getDetails()); - else + } else { event.setDescription("Unable to start VM: " + vm.getHostName()+ " Reason: "+answer.getDetails()); + } event.setLevel(EventVO.LEVEL_ERROR); _eventDao.persist(event); throw new ExecutionException("Unable to start VM: " + vm.getHostName()+ " Reason: "+answer.getDetails()); } - if (!_vmDao.updateIf(vm, VirtualMachine.Event.OperationSucceeded, host.getId())) { - if(!vm.getHostName().equals(vm.getDisplayName())) - event.setDescription("unable to start VM: " + vm.getHostName()+"("+vm.getDisplayName()+")"); - else - event.setDescription("unable to start VM: " + vm.getHostName()); + if (!_itMgr.stateTransitTo(vm, VirtualMachine.Event.OperationSucceeded, host.getId())) { + if(!vm.getHostName().equals(vm.getDisplayName())) { + event.setDescription("unable to start VM: " + vm.getHostName()+"("+vm.getDisplayName()+")"); + } else { + event.setDescription("unable to start VM: " + vm.getHostName()); + } event.setLevel(EventVO.LEVEL_ERROR); _eventDao.persist(event); throw new ConcurrentOperationException("Starting vm " + vm.getHostName() + " didn't work."); @@ -1120,10 +1141,11 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM s_logger.debug("Started vm " + vm.getHostName()); } - if(!vm.getHostName().equals(vm.getDisplayName())) - event.setDescription("successfully started VM: " + vm.getHostName()+"("+vm.getDisplayName()+")"); - else - event.setDescription("successfully started VM: " + vm.getHostName()); + if(!vm.getHostName().equals(vm.getDisplayName())) { + event.setDescription("successfully started VM: " + vm.getHostName()+"("+vm.getDisplayName()+")"); + } else { + event.setDescription("successfully started VM: " + vm.getHostName()); + } _eventDao.persist(event); _networkGroupMgr.handleVmStateTransition(vm, State.Running); @@ -1137,7 +1159,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM vm.setVnet(null); txn.start(); - if (_vmDao.updateIf(vm, VirtualMachine.Event.OperationFailed, null)) { + if (_itMgr.stateTransitTo(vm, VirtualMachine.Event.OperationFailed, null)) { txn.commit(); } } @@ -1220,8 +1242,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM resultDescription = "VM is either removed or deleted"; executor.getAsyncJobMgr().completeAsyncJob(executor.getJob().getId(), AsyncJobResult.STATUS_SUCCEEDED, 0, resultDescription); - if(s_logger.isDebugEnabled()) - s_logger.debug("Execute asynchronize stop VM command: " +resultDescription); + if(s_logger.isDebugEnabled()) { + s_logger.debug("Execute asynchronize stop VM command: " +resultDescription); + } response = new OperationResponse(OperationResponse.STATUS_SUCCEEDED, resultDescription); return response; } @@ -1232,8 +1255,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM executor.getAsyncJobMgr().completeAsyncJob(executor.getJob().getId(), AsyncJobResult.STATUS_SUCCEEDED, 0, resultDescription); - if(s_logger.isDebugEnabled()) - s_logger.debug("Execute asynchronize stop VM command: " +resultDescription); + if(s_logger.isDebugEnabled()) { + s_logger.debug("Execute asynchronize stop VM command: " +resultDescription); + } response = new OperationResponse(OperationResponse.STATUS_SUCCEEDED, resultDescription); return response; } @@ -1243,19 +1267,21 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM executor.getAsyncJobMgr().completeAsyncJob(executor.getJob().getId(), AsyncJobResult.STATUS_SUCCEEDED, 0, resultDescription); - if(s_logger.isDebugEnabled()) - s_logger.debug("Execute asynchronize stop VM command: " +resultDescription); + if(s_logger.isDebugEnabled()) { + s_logger.debug("Execute asynchronize stop VM command: " +resultDescription); + } response = new OperationResponse(OperationResponse.STATUS_SUCCEEDED, resultDescription); return response; } - if (!_vmDao.updateIf(vm, VirtualMachine.Event.StopRequested, vm.getHostId())) { + if (!_itMgr.stateTransitTo(vm, VirtualMachine.Event.StopRequested, vm.getHostId())) { resultDescription = "VM is not in a state to stop"; executor.getAsyncJobMgr().completeAsyncJob(executor.getJob().getId(), AsyncJobResult.STATUS_FAILED, 0, resultDescription); - if(s_logger.isDebugEnabled()) - s_logger.debug("Execute asynchronize stop VM command: " +resultDescription); + if(s_logger.isDebugEnabled()) { + s_logger.debug("Execute asynchronize stop VM command: " +resultDescription); + } response = new OperationResponse(OperationResponse.STATUS_FAILED, resultDescription); return response; } @@ -1265,8 +1291,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM executor.getAsyncJobMgr().completeAsyncJob(executor.getJob().getId(), AsyncJobResult.STATUS_FAILED, 0, resultDescription); - if(s_logger.isDebugEnabled()) - s_logger.debug("Execute asynchronize stop VM command: " +resultDescription); + if(s_logger.isDebugEnabled()) { + s_logger.debug("Execute asynchronize stop VM command: " +resultDescription); + } response = new OperationResponse(OperationResponse.STATUS_FAILED, resultDescription); return response; } @@ -1281,15 +1308,16 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM try { long seq = _agentMgr.send(vm.getHostId(), new Commands(cmd), new VMOperationListener(executor, param, vm, 0)); resultDescription = "Execute asynchronize stop VM command: sending command to agent, seq - " + seq; - if(s_logger.isDebugEnabled()) - s_logger.debug(resultDescription); + if(s_logger.isDebugEnabled()) { + s_logger.debug(resultDescription); + } response = new OperationResponse(OperationResponse.STATUS_IN_PROGRESS, resultDescription); return response; } catch (AgentUnavailableException e) { resultDescription = "Agent is not available"; executor.getAsyncJobMgr().completeAsyncJob(executor.getJob().getId(), AsyncJobResult.STATUS_FAILED, 0, resultDescription); - _vmDao.updateIf(vm, VirtualMachine.Event.OperationFailed, vm.getHostId()); + _itMgr.stateTransitTo(vm, VirtualMachine.Event.OperationFailed, vm.getHostId()); response = new OperationResponse(OperationResponse.STATUS_FAILED, resultDescription); return response; @@ -1314,17 +1342,19 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM RebootAnswer answer = (RebootAnswer)_agentMgr.easySend(vm.getHostId(), cmd); if (answer != null) { - if(!vm.getHostName().equals(vm.getDisplayName())) - event.setDescription("Successfully rebooted VM instance : " + vm.getHostName()+"("+vm.getDisplayName()+")"); - else - event.setDescription("Successfully rebooted VM instance : " + vm.getHostName()); + if(!vm.getHostName().equals(vm.getDisplayName())) { + event.setDescription("Successfully rebooted VM instance : " + vm.getHostName()+"("+vm.getDisplayName()+")"); + } else { + event.setDescription("Successfully rebooted VM instance : " + vm.getHostName()); + } _eventDao.persist(event); return true; } else { - if(!vm.getHostName().equals(vm.getDisplayName())) - event.setDescription("failed to reboot VM instance : " + vm.getHostName()+"("+vm.getDisplayName()+")"); - else - event.setDescription("failed to reboot VM instance : " + vm.getHostName()); + if(!vm.getHostName().equals(vm.getDisplayName())) { + event.setDescription("failed to reboot VM instance : " + vm.getHostName()+"("+vm.getDisplayName()+")"); + } else { + event.setDescription("failed to reboot VM instance : " + vm.getHostName()); + } event.setLevel(EventVO.LEVEL_ERROR); _eventDao.persist(event); return false; @@ -1520,9 +1550,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM public void releaseGuestIpAddress(UserVmVO userVm) { ServiceOffering offering = _offeringDao.findById(userVm.getServiceOfferingId()); - if (offering.getGuestIpType() != NetworkOffering.GuestIpType.Virtualized) { + if (offering.getGuestIpType() != NetworkOffering.GuestIpType.Virtual) { IPAddressVO guestIP = (userVm.getGuestIpAddress() == null) ? null : _ipAddressDao.findById(userVm.getGuestIpAddress()); - if (guestIP != null && guestIP.getAllocated() != null) { + if (guestIP != null && guestIP.getAllocatedTime() != null) { _ipAddressDao.unassignIpAddress(userVm.getGuestIpAddress()); s_logger.debug("Released guest IP address=" + userVm.getGuestIpAddress() + " vmName=" + userVm.getHostName() + " dcId=" + userVm.getDataCenterId()); @@ -1634,7 +1664,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM vm = _vmDao.persist(vm); } else { vm.setPodId(pod.first().getId()); - _vmDao.updateIf(vm, VirtualMachine.Event.OperationRetry, null); + _itMgr.stateTransitTo(vm, VirtualMachine.Event.OperationRetry, null); } String ipAddressStr = acquireGuestIpAddress(dataCenterId, accountId, vm); @@ -1673,10 +1703,11 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM txn.start(); if(vm != null && vm.getHostName() != null && vm.getDisplayName() != null) { - if(!vm.getHostName().equals(vm.getDisplayName())) - event.setDescription("successfully created VM instance : " + vm.getHostName()+"("+vm.getDisplayName()+")"); - else - event.setDescription("successfully created VM instance : " + vm.getHostName()); + if(!vm.getHostName().equals(vm.getDisplayName())) { + event.setDescription("successfully created VM instance : " + vm.getHostName()+"("+vm.getDisplayName()+")"); + } else { + event.setDescription("successfully created VM instance : " + vm.getHostName()); + } } else { @@ -1685,7 +1716,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM _eventDao.persist(event); - _vmDao.updateIf(vm, VirtualMachine.Event.OperationSucceeded, null); + _itMgr.stateTransitTo(vm, VirtualMachine.Event.OperationSucceeded, null); if (s_logger.isDebugEnabled()) { s_logger.debug("vm created " + vmId); } @@ -1744,10 +1775,11 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM event.setAccountId(vm.getAccountId()); event.setType(EventTypes.EVENT_VM_DESTROY); event.setParameters("id="+vm.getId() + "\nvmName=" + vm.getHostName() + "\nsoId=" + vm.getServiceOfferingId() + "\ntId=" + vm.getTemplateId() + "\ndcId=" + vm.getDataCenterId()); - if(!vm.getHostName().equals(vm.getDisplayName())) - event.setDescription("Successfully destroyed VM instance : " + vm.getHostName()+"("+vm.getDisplayName()+")"); - else - event.setDescription("Successfully destroyed VM instance : " + vm.getHostName()); + if(!vm.getHostName().equals(vm.getDisplayName())) { + event.setDescription("Successfully destroyed VM instance : " + vm.getHostName()+"("+vm.getDisplayName()+")"); + } else { + event.setDescription("Successfully destroyed VM instance : " + vm.getHostName()); + } _eventDao.persist(event); _accountMgr.decrementResourceCount(vm.getAccountId(), ResourceType.user_vm); @@ -1775,8 +1807,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM Account accountHandle = UserContext.current().getAccount(); //if account is removed, return error - if(accountHandle!=null && accountHandle.getRemoved() != null) - throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, "The account " + accountHandle.getId()+" is removed"); + if(accountHandle!=null && accountHandle.getRemoved() != null) { + throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, "The account " + accountHandle.getId()+" is removed"); + } // Verify input parameters UserVmVO vm = _vmDao.findById(vmId.longValue()); @@ -1821,18 +1854,20 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM account = _accountDao.lockRow(vm.getAccountId(), true); //if the account is deleted, throw error - if(account.getRemoved()!=null) - throw new CloudRuntimeException("Unable to recover VM as the account is deleted"); + if(account.getRemoved()!=null) { + throw new CloudRuntimeException("Unable to recover VM as the account is deleted"); + } // First check that the maximum number of UserVMs for the given accountId will not be exceeded if (_accountMgr.resourceLimitExceeded(account, ResourceType.user_vm)) { ResourceAllocationException rae = new ResourceAllocationException("Maximum number of virtual machines for account: " + account.getAccountName() + " has been exceeded."); rae.setResourceType("vm"); event.setLevel(EventVO.LEVEL_ERROR); - if(!vm.getHostName().equals(vm.getDisplayName())) - event.setDescription("Failed to recover VM instance : " + vm.getHostName()+"("+vm.getDisplayName()+")" + "; the resource limit for account: " + account.getAccountName() + " has been exceeded."); - else - event.setDescription("Failed to recover VM instance : " + vm.getHostName() + "; the resource limit for account: " + account.getAccountName() + " has been exceeded."); + if(!vm.getHostName().equals(vm.getDisplayName())) { + event.setDescription("Failed to recover VM instance : " + vm.getHostName()+"("+vm.getDisplayName()+")" + "; the resource limit for account: " + account.getAccountName() + " has been exceeded."); + } else { + event.setDescription("Failed to recover VM instance : " + vm.getHostName() + "; the resource limit for account: " + account.getAccountName() + " has been exceeded."); + } _eventDao.persist(event); txn.commit(); throw rae; @@ -1842,7 +1877,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM _accountMgr.incrementResourceCount(account.getId(), ResourceType.user_vm); - if (!_vmDao.updateIf(vm, VirtualMachine.Event.RecoveryRequested, null)) { + if (!_itMgr.stateTransitTo(vm, VirtualMachine.Event.RecoveryRequested, null)) { s_logger.debug("Unable to recover the vm because it is not in the correct state: " + vmId); throw new InvalidParameterValueException("Unable to recover the vm because it is not in the correct state: " + vmId); } @@ -1873,10 +1908,11 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM _accountMgr.incrementResourceCount(account.getId(), ResourceType.volume, new Long(volumes.size())); event.setLevel(EventVO.LEVEL_INFO); - if(!vm.getHostName().equals(vm.getDisplayName())) - event.setDescription("successfully recovered VM instance : " + vm.getHostName()+"("+vm.getDisplayName()+")"); - else + if(!vm.getHostName().equals(vm.getDisplayName())) { + event.setDescription("successfully recovered VM instance : " + vm.getHostName()+"("+vm.getDisplayName()+")"); + } else { event.setDescription("successfully recovered VM instance : " + vm.getHostName()); + } _eventDao.persist(event); txn.commit(); @@ -1975,7 +2011,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM @Override public void completeStartCommand(UserVmVO vm) { - _vmDao.updateIf(vm, VirtualMachine.Event.AgentReportRunning, vm.getHostId()); + _itMgr.stateTransitTo(vm, VirtualMachine.Event.AgentReportRunning, vm.getHostId()); _networkGroupMgr.handleVmStateTransition(vm, State.Running); } @@ -1997,7 +2033,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM txn.start(); - if (!_vmDao.updateIf(vm, e, null)) { + if (!_itMgr.stateTransitTo(vm, e, null)) { s_logger.debug("Unable to update "); return; } @@ -2023,10 +2059,11 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM event.setState(Event.State.Completed); event.setStartId(startEventId); event.setParameters("id="+vm.getId() + "\n" + "vmName=" + vm.getHostName() + "\nsoId=" + vm.getServiceOfferingId() + "\ntId=" + vm.getTemplateId() + "\ndcId=" + vm.getDataCenterId()); - if(!vm.getHostName().equals(vm.getDisplayName())) - event.setDescription("Successfully stopped VM instance : " + vm.getHostName()+"("+vm.getDisplayName()+")"); - else - event.setDescription("Successfully stopped VM instance : " + vm.getHostName()); + if(!vm.getHostName().equals(vm.getDisplayName())) { + event.setDescription("Successfully stopped VM instance : " + vm.getHostName()+"("+vm.getDisplayName()+")"); + } else { + event.setDescription("Successfully stopped VM instance : " + vm.getHostName()); + } _eventDao.persist(event); if (_storageMgr.unshare(vm, null) == null) { @@ -2075,7 +2112,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM return true; } - if (!_vmDao.updateIf(vm, VirtualMachine.Event.StopRequested, vm.getHostId())) { + if (!_itMgr.stateTransitTo(vm, VirtualMachine.Event.StopRequested, vm.getHostId())) { s_logger.debug("VM is not in a state to stop: " + vm.getState().toString()); return false; } @@ -2112,13 +2149,14 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM completeStopCommand(userId, vm, VirtualMachine.Event.OperationSucceeded, 0); } else { - if(!vm.getHostName().equals(vm.getDisplayName())) - event.setDescription("failed to stop VM instance : " + vm.getHostName()+"("+vm.getDisplayName()+")"); - else - event.setDescription("failed to stop VM instance : " + vm.getHostName()); + if(!vm.getHostName().equals(vm.getDisplayName())) { + event.setDescription("failed to stop VM instance : " + vm.getHostName()+"("+vm.getDisplayName()+")"); + } else { + event.setDescription("failed to stop VM instance : " + vm.getHostName()); + } event.setLevel(EventVO.LEVEL_ERROR); _eventDao.persist(event); - _vmDao.updateIf(vm, VirtualMachine.Event.OperationFailed, vm.getHostId()); + _itMgr.stateTransitTo(vm, VirtualMachine.Event.OperationFailed, vm.getHostId()); s_logger.error("Unable to stop vm " + vm.getHostName()); } @@ -2130,7 +2168,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM if (s_logger.isDebugEnabled()) { s_logger.debug("Destroying vm " + vm.toString()); } - if (!_vmDao.updateIf(vm, VirtualMachine.Event.DestroyRequested, vm.getHostId())) { + if (!_itMgr.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()); return false; } @@ -2197,7 +2235,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM public boolean migrate(UserVmVO vm, HostVO host) throws AgentUnavailableException, OperationTimedoutException { HostVO fromHost = _hostDao.findById(vm.getHostId()); - if (!_vmDao.updateIf(vm, VirtualMachine.Event.MigrationRequested, vm.getHostId())) { + if (!_itMgr.stateTransitTo(vm, VirtualMachine.Event.MigrationRequested, vm.getHostId())) { s_logger.debug("State for " + vm.toString() + " has changed so migration can not take place."); return false; } @@ -2229,7 +2267,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM releaseGuestIpAddress(vm); vm.setGuestNetmask(null); vm.setGuestMacAddress(null); - if (!_vmDao.updateIf(vm, VirtualMachine.Event.ExpungeOperation, null)) { + if (!_itMgr.stateTransitTo(vm, VirtualMachine.Event.ExpungeOperation, null)) { s_logger.info("vm " + vmId + " is skipped because it is no longer in Destroyed state"); continue; } @@ -2238,53 +2276,53 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM deleteRules = false; } - if(deleteRules) - { - List forwardingRules = null; - forwardingRules = _rulesDao.listByPrivateIp(privateIpAddress); - - for(FirewallRuleVO rule: forwardingRules) - { - try - { - IPAddressVO publicIp = _ipAddressDao.findById(rule.getPublicIpAddress()); - - if(publicIp != null) - { - if((publicIp.getAccountId().longValue() == vm.getAccountId())) - { - if(publicIp.isOneToOneNat()){ - _networkMgr.deleteIpForwardingRule(rule.getId()); - if(s_logger.isDebugEnabled()) - s_logger.debug("Rule "+rule.getId()+" for vm:"+vm.getHostName()+" is deleted successfully during expunge operation"); - }else{ - _networkMgr.deletePortForwardingRule(rule.getId(),true);//delete the rule with the sys user's credentials - if(s_logger.isDebugEnabled()) - s_logger.debug("Rule "+rule.getId()+" for vm:"+vm.getHostName()+" is deleted successfully during expunge operation"); - } - } - } - } - catch(Exception e) - { - s_logger.warn("Failed to delete rule:"+rule.getId()+" for vm:"+vm.getHostName()); - } - } - } - - List vols = null; - try { - vols = _volsDao.findByInstanceIdDestroyed(vmId); - _storageMgr.destroy(vm, vols); - - _vmDao.remove(vm.getId()); - _networkGroupMgr.removeInstanceFromGroups(vm.getId()); - removeInstanceFromGroup(vm.getId()); - - s_logger.debug("vm is destroyed"); - } catch (Exception e) { - s_logger.info("VM " + vmId +" expunge failed due to " + e.getMessage()); - } +//FIXME if(deleteRules) +// { +// List forwardingRules = null; +// forwardingRules = _rulesDao.listByPrivateIp(privateIpAddress); +// +// for(PortForwardingRuleVO rule: forwardingRules) +// { +// try +// { +// IPAddressVO publicIp = _ipAddressDao.findById(rule.getSourceIpAddress()); +// +// if(publicIp != null) +// { +// if((publicIp.getAccountId().longValue() == vm.getAccountId())) +// { +// if(publicIp.isOneToOneNat()){ +// _networkMgr.deleteIpForwardingRule(rule.getId()); +// if(s_logger.isDebugEnabled()) +// s_logger.debug("Rule "+rule.getId()+" for vm:"+vm.getHostName()+" is deleted successfully during expunge operation"); +// }else{ +// _networkMgr.deletePortForwardingRule(rule.getId(),true);//delete the rule with the sys user's credentials +// if(s_logger.isDebugEnabled()) +// s_logger.debug("Rule "+rule.getId()+" for vm:"+vm.getHostName()+" is deleted successfully during expunge operation"); +// } +// } +// } +// } +// catch(Exception e) +// { +// s_logger.warn("Failed to delete rule:"+rule.getId()+" for vm:"+vm.getHostName()); +// } +// } +// } +// +// List vols = null; +// try { +// vols = _volsDao.findByInstanceIdDestroyed(vmId); +// _storageMgr.destroy(vm, vols); +// +// _vmDao.remove(vm.getId()); +// _networkGroupMgr.removeInstanceFromGroups(vm.getId()); +// removeInstanceFromGroup(vm.getId()); +// +// s_logger.debug("vm is destroyed"); +// } catch (Exception e) { +// s_logger.info("VM " + vmId +" expunge failed due to " + e.getMessage()); +// } } List destroyedVolumes = _volsDao.findByDetachedDestroyed(); @@ -2298,14 +2336,14 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM CheckVirtualMachineAnswer answer = (CheckVirtualMachineAnswer)_agentMgr.send(host.getId(), cvm); if (!answer.getResult()) { s_logger.debug("Unable to complete migration for " + vm.toString()); - _vmDao.updateIf(vm, VirtualMachine.Event.AgentReportStopped, null); + _itMgr.stateTransitTo(vm, 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.toString()); - _vmDao.updateIf(vm, VirtualMachine.Event.AgentReportStopped, null); + _itMgr.stateTransitTo(vm, VirtualMachine.Event.AgentReportStopped, null); return false; } @@ -2316,7 +2354,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM Transaction txn = Transaction.currentTxn(); try { txn.start(); - _vmDao.updateIf(vm, VirtualMachine.Event.OperationSucceeded, host.getId()); + _itMgr.stateTransitTo(vm, VirtualMachine.Event.OperationSucceeded, host.getId()); txn.commit(); _networkGroupMgr.handleVmStateTransition(vm, State.Running); return true; @@ -2328,42 +2366,42 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM @Override public void cleanNetworkRules(long userId, long instanceId) { - UserVmVO vm = _vmDao.findById(instanceId); - String guestIpAddr = vm.getGuestIpAddress(); - long accountId = vm.getAccountId(); - - List loadBalancerMappings = _loadBalancerVMMapDao.listByInstanceId(vm.getId()); - for (LoadBalancerVMMapVO loadBalancerMapping : loadBalancerMappings) { - List lbRules = _rulesDao.listByLoadBalancerId(loadBalancerMapping.getLoadBalancerId()); - FirewallRuleVO targetLbRule = null; - for (FirewallRuleVO lbRule : lbRules) { - if (lbRule.getPrivateIpAddress().equals(guestIpAddr)) { - targetLbRule = lbRule; - targetLbRule.setEnabled(false); - break; - } - } - - if (targetLbRule != null) { - String ipAddress = targetLbRule.getPublicIpAddress(); - DomainRouterVO router = _routerDao.findById(vm.getDomainRouterId()); - _networkMgr.updateFirewallRules(ipAddress, lbRules, router); - - // now that the rule has been disabled, delete it, also remove the mapping from the load balancer mapping table - _rulesDao.remove(targetLbRule.getId()); - _loadBalancerVMMapDao.remove(loadBalancerMapping.getId()); - - // save off the event for deleting the LB rule - EventVO lbRuleEvent = new EventVO(); - lbRuleEvent.setUserId(userId); - lbRuleEvent.setAccountId(accountId); - lbRuleEvent.setType(EventTypes.EVENT_NET_RULE_DELETE); - lbRuleEvent.setDescription("deleted load balancer rule [" + targetLbRule.getPublicIpAddress() + ":" + targetLbRule.getPublicPort() + - "]->[" + targetLbRule.getPrivateIpAddress() + ":" + targetLbRule.getPrivatePort() + "]" + " " + targetLbRule.getAlgorithm()); - lbRuleEvent.setLevel(EventVO.LEVEL_INFO); - _eventDao.persist(lbRuleEvent); - } - } +//FIXME UserVmVO vm = _vmDao.findById(instanceId); +// String guestIpAddr = vm.getGuestIpAddress(); +// long accountId = vm.getAccountId(); +// +// List loadBalancerMappings = _loadBalancerVMMapDao.listByInstanceId(vm.getId()); +// for (LoadBalancerVMMapVO loadBalancerMapping : loadBalancerMappings) { +// List lbRules = _rulesDao.listByLoadBalancerId(loadBalancerMapping.getLoadBalancerId()); +// PortForwardingRuleVO targetLbRule = null; +// for (PortForwardingRuleVO lbRule : lbRules) { +// if (lbRule.getDestinationIpAddress().equals(guestIpAddr)) { +// targetLbRule = lbRule; +// targetLbRule.setEnabled(false); +// break; +// } +// } +// +// if (targetLbRule != null) { +// String ipAddress = targetLbRule.getSourceIpAddress(); +// DomainRouterVO router = _routerDao.findById(vm.getDomainRouterId()); +// _networkMgr.updateFirewallRules(ipAddress, lbRules, router); +// +// // now that the rule has been disabled, delete it, also remove the mapping from the load balancer mapping table +// _rulesDao.remove(targetLbRule.getId()); +// _loadBalancerVMMapDao.remove(loadBalancerMapping.getId()); +// +// // save off the event for deleting the LB rule +// EventVO lbRuleEvent = new EventVO(); +// lbRuleEvent.setUserId(userId); +// lbRuleEvent.setAccountId(accountId); +// lbRuleEvent.setType(EventTypes.EVENT_NET_RULE_DELETE); +// lbRuleEvent.setDescription("deleted load balancer rule [" + targetLbRule.getSourceIpAddress() + ":" + targetLbRule.getSourcePort() + +// "]->[" + targetLbRule.getDestinationIpAddress() + ":" + targetLbRule.getDestinationPort() + "]" + " " + targetLbRule.getAlgorithm()); +// lbRuleEvent.setLevel(EventVO.LEVEL_INFO); +// _eventDao.persist(lbRuleEvent); +// } +// } } @Override @@ -2534,13 +2572,13 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM if (s_logger.isInfoEnabled()) { s_logger.info(msg); } - _templateDao.remove(command.getId()); // Mark it removed so that templates with the same name can be created subsequently. Bug 7366 + _templateDao.remove(command.getEntityId()); // Mark it removed so that templates with the same name can be created subsequently. Bug 7366 throw new CloudRuntimeException(msg); } SnapshotCommand cmd = null; VMTemplateVO privateTemplate = null; - long templateId = command.getId(); + long templateId = command.getEntityId(); long zoneId = volume.getDataCenterId(); String uniqueName = getRandomPrivateTemplateName(); @@ -2664,8 +2702,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM long dataCenterId = dc.getId(); long serviceOfferingId = offering.getId(); long templateId = -1; - if (template != null) - templateId = template.getId(); + if (template != null) { + templateId = template.getId(); + } if (s_logger.isDebugEnabled()) { s_logger.debug("Creating directly attached vm for account id=" + account.getId() + @@ -2761,7 +2800,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM router = rtrs.get(0); routerId = router.getId(); } else if (rtrs.size() == 0) { - router = _networkMgr.createDhcpServerForDirectlyAttachedGuests(userId, accountId, dc, pod.first(), pod.second(), guestVlan); + router = _routerMgr.createDhcpServerForDirectlyAttachedGuests(userId, accountId, dc, pod.first(), pod.second(), guestVlan); if (router == null) { avoids.add(pod.first().getId()); if (s_logger.isDebugEnabled()) { @@ -2777,9 +2816,10 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM { for(VlanVO vlanForAcc : vlansForAccount) { - guestIp = _ipAddressDao.assignIpAddress(accountId, account.getDomainId(), vlanForAcc.getId(), false); - if(guestIp!=null) - break; //got an ip + guestIp = _ipAddressDao.assignIpAddress(accountId, account.getDomainId(), vlanForAcc.getId(), false).getAddress(); + if(guestIp!=null) { + break; //got an ip + } } } else if(!forAccount && !forZone) @@ -2787,9 +2827,10 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM //i.e. for pod for(VlanVO vlanForPod : vlansForPod) { - guestIp = _ipAddressDao.assignIpAddress(accountId, account.getDomainId(), vlanForPod.getId(), false); - if(guestIp!=null) - break;//got an ip + guestIp = _ipAddressDao.assignIpAddress(accountId, account.getDomainId(), vlanForPod.getId(), false).getAddress(); + if(guestIp!=null) { + break;//got an ip + } } } else @@ -2797,9 +2838,10 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM //for zone for(VlanVO vlanForZone : zoneWideVlans) { - guestIp = _ipAddressDao.assignIpAddress(accountId, account.getDomainId(), vlanForZone.getId(), false); - if(guestIp!=null) - break;//found an ip + guestIp = _ipAddressDao.assignIpAddress(accountId, account.getDomainId(), vlanForZone.getId(), false).getAddress(); + if(guestIp!=null) { + break;//found an ip + } } } @@ -2861,10 +2903,11 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM if (poolId == 0) { if(vm != null && vm.getHostName()!=null && vm.getDisplayName() != null) { - if(!vm.getHostName().equals(vm.getDisplayName())) - s_logger.debug("failed to create VM instance : " + name+"("+vm.getInstanceName()+")"); - else - s_logger.debug("failed to create VM instance : " + name); + if(!vm.getHostName().equals(vm.getDisplayName())) { + s_logger.debug("failed to create VM instance : " + name+"("+vm.getInstanceName()+")"); + } else { + s_logger.debug("failed to create VM instance : " + name); + } } else { @@ -2887,13 +2930,14 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM String diskOfferingIdentifier = (diskOffering != null) ? String.valueOf(diskOffering.getId()) : "-1"; String eventParams = "id=" + vm.getId() + "\nvmName=" + vm.getHostName() + "\nsoId=" + vm.getServiceOfferingId() + "\ndoId=" + diskOfferingIdentifier + "\ntId=" + vm.getTemplateId() + "\ndcId=" + vm.getDataCenterId(); event.setParameters(eventParams); - if(!vm.getHostName().equals(vm.getDisplayName())) - event.setDescription("successfully created VM instance : " + vm.getHostName()+"("+vm.getInstanceName()+")"); - else - event.setDescription("successfully created VM instance : " + vm.getHostName()); + if(!vm.getHostName().equals(vm.getDisplayName())) { + event.setDescription("successfully created VM instance : " + vm.getHostName()+"("+vm.getInstanceName()+")"); + } else { + event.setDescription("successfully created VM instance : " + vm.getHostName()); + } _eventDao.persist(event); - _vmDao.updateIf(vm, VirtualMachine.Event.OperationSucceeded, null); + _itMgr.stateTransitTo(vm, VirtualMachine.Event.OperationSucceeded, null); if (s_logger.isDebugEnabled()) { s_logger.debug("vm created " + vmId); } @@ -2916,8 +2960,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM long dataCenterId = dc.getId(); long serviceOfferingId = offering.getId(); long templateId = -1; - if (template != null) - templateId = template.getId(); + if (template != null) { + templateId = template.getId(); + } if (s_logger.isDebugEnabled()) { s_logger.debug("Creating directly attached vm for account id=" + account.getId() + @@ -3015,10 +3060,11 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM if (poolId == 0) { if(vm != null && vm.getHostName()!=null && vm.getDisplayName() != null) { - if(!vm.getHostName().equals(vm.getDisplayName())) - s_logger.debug("failed to create VM instance : " + name+"("+vm.getDisplayName()+")"); - else - s_logger.debug("failed to create VM instance : " + name); + if(!vm.getHostName().equals(vm.getDisplayName())) { + s_logger.debug("failed to create VM instance : " + name+"("+vm.getDisplayName()+")"); + } else { + s_logger.debug("failed to create VM instance : " + name); + } } else { @@ -3041,13 +3087,14 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM String diskOfferingIdentifier = (diskOffering != null) ? String.valueOf(diskOffering.getId()) : "-1"; String eventParams = "id=" + vm.getId() + "\nvmName=" + vm.getHostName() + "\nsoId=" + vm.getServiceOfferingId() + "\ndoId=" + diskOfferingIdentifier + "\ntId=" + vm.getTemplateId() + "\ndcId=" + vm.getDataCenterId(); event.setParameters(eventParams); - if(!vm.getHostName().equals(vm.getDisplayName())) - event.setDescription("successfully created VM instance : " + vm.getHostName()+"("+vm.getDisplayName()+")"); - else - event.setDescription("successfully created VM instance : " + vm.getHostName()); + if(!vm.getHostName().equals(vm.getDisplayName())) { + event.setDescription("successfully created VM instance : " + vm.getHostName()+"("+vm.getDisplayName()+")"); + } else { + event.setDescription("successfully created VM instance : " + vm.getHostName()); + } _eventDao.persist(event); - _vmDao.updateIf(vm, VirtualMachine.Event.OperationSucceeded, null); + _itMgr.stateTransitTo(vm, VirtualMachine.Event.OperationSucceeded, null); if (s_logger.isDebugEnabled()) { s_logger.debug("vm created " + vmId); } @@ -3185,8 +3232,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM Long id = cmd.getId(); //if account is removed, return error - if(account!=null && account.getRemoved() != null) - throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, "The account " + account.getId()+" is removed"); + if(account!=null && account.getRemoved() != null) { + throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, "The account " + account.getId()+" is removed"); + } UserVmVO vmInstance = _vmDao.findById(id); if (vmInstance == null) { @@ -3215,8 +3263,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM Long id = cmd.getId(); //if account is removed, return error - if(account!=null && account.getRemoved() != null) - throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, "The account " + account.getId()+" is removed"); + if(account!=null && account.getRemoved() != null) { + throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, "The account " + account.getId()+" is removed"); + } UserVmVO vmInstance = _vmDao.findById(id.longValue()); if (vmInstance == null) { @@ -3535,9 +3584,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM throw new InvalidParameterValueException("No valid account specified for deploying a virtual machine."); } - AccountVO owner = _accountDao.findById(cmd.getAccountId()); + AccountVO owner = _accountDao.findById(cmd.getEntityOwnerId()); if (owner == null || owner.getRemoved() != null) { - throw new InvalidParameterValueException("Unable to find account: " + cmd.getAccountId()); + throw new InvalidParameterValueException("Unable to find account: " + cmd.getEntityOwnerId()); } Domain domain = _domainDao.findById(owner.getDomainId()); @@ -3652,8 +3701,12 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM if (network == null) { throw new InvalidParameterValueException("Unable to find network by id " + networkId); } else { - if (network.getAccountId() != Account.ACCOUNT_ID_SYSTEM && network.getAccountId() != accountId) { - throw new PermissionDeniedException("Unable to create a vm using network with id " + networkId + ", permission denied"); + if (!network.isShared()) { + //Iterate through account/network map + List networkMap = _networkDao.listBy(accountId, networkId); + if (networkMap == null || networkMap.isEmpty()) { + throw new PermissionDeniedException("Unable to create a vm using network with id " + networkId + ", permission denied"); + } } else if (network.getTrafficType() != TrafficType.Guest) { throw new InvalidParameterValueException("Unable to create a vm using network which traffic type is " + network.getTrafficType() + ". " + "Only Guest traffic type is acceptes"); @@ -3677,8 +3730,8 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM } @Override - public UserVm startVirtualMachine(DeployVm2Cmd cmd) throws ResourceUnavailableException, InsufficientCapacityException, ConcurrentOperationException { - long vmId = cmd.getId(); + public UserVm startVirtualMachine(DeployVMCmd cmd) throws ResourceUnavailableException, InsufficientCapacityException, ConcurrentOperationException { + long vmId = cmd.getEntityId(); UserVmVO vm = _vmDao.findById(vmId); // Check that the password was passed in and is valid @@ -3745,8 +3798,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM Long userId = UserContext.current().getUserId(); //if account is removed, return error - if (caller != null && caller.getRemoved() != null) + if (caller != null && caller.getRemoved() != null) { throw new PermissionDeniedException("The account " + caller.getId()+" is removed"); + } UserVmVO vm = _vmDao.findById(vmId); if (vm == null) { @@ -3784,8 +3838,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM Long userId = UserContext.current().getUserId(); //if account is removed, return error - if(account!=null && account.getRemoved() != null) + if(account!=null && account.getRemoved() != null) { throw new PermissionDeniedException("The account " + account.getId()+" is removed"); + } UserVmVO vm = _vmDao.findById(vmId); if (vm == null) { diff --git a/server/src/com/cloud/vm/VMStateListener.java b/server/src/com/cloud/vm/VMStateListener.java new file mode 100644 index 00000000000..b828234d3ec --- /dev/null +++ b/server/src/com/cloud/vm/VMStateListener.java @@ -0,0 +1,193 @@ +package com.cloud.vm; + +import org.apache.log4j.Logger; + +import com.cloud.capacity.CapacityVO; +import com.cloud.capacity.dao.CapacityDao; +import com.cloud.service.ServiceOfferingVO; +import com.cloud.service.dao.ServiceOfferingDao; +import com.cloud.utils.db.Transaction; +import com.cloud.utils.fsm.StateDao; +import com.cloud.utils.fsm.StateListener; +import com.cloud.vm.VirtualMachine.Event; +import com.cloud.vm.dao.VMInstanceDao; + +public class VMStateListener implements StateListener{ + private static final Logger s_logger = Logger.getLogger(VMStateListener.class); + CapacityDao _capacityDao; + ServiceOfferingDao _offeringDao; + + + public VMStateListener(CapacityDao capacityDao, ServiceOfferingDao offering) { + _capacityDao = capacityDao; + _offeringDao = offering; + } + + @Override + public boolean processStateTransitionEvent(State oldState, + Event event, State newState, VMInstanceVO vm, boolean transitionStatus, Long id, StateDao vmDao) { + s_logger.debug("VM state transitted from :" + oldState + " to " + newState + " with event: " + event + + "vm's original host id: " + vm.getHostId() + " new host id: " + id); + if (!transitionStatus) { + return false; + } + + Transaction txn = Transaction.open(Transaction.CLOUD_DB); + try { + txn.start(); + + if (oldState == State.Starting) { + if (event == Event.OperationSucceeded) { + if (vm.getLastHostId() != null && vm.getLastHostId() != id) { + /*need to release the reserved capacity on lasthost*/ + releaseResource(vm, true, false, vm.getLastHostId()); + } + vm.setLastHostId(id); + + } else if (event == Event.OperationRetry || event == Event.OperationFailed) { + /*need to release resource from host, passed in from id, cause vm.gethostid is null*/ + releaseResource(vm, false, false, id); + id = null; + } + } else if (oldState == State.Running) { + if (event == Event.AgentReportStopped) { + releaseResource(vm, false, true, vm.getHostId()); + } + } else if (oldState == State.Migrating) { + if (event == Event.AgentReportStopped) { + /*Release capacity from original host*/ + releaseResource(vm, false, true, vm.getHostId()); + } else if (event == Event.MigrationFailedOnSource) { + /*release capacity from dest host*/ + releaseResource(vm, false, false, id); + id = vm.getHostId(); + } else if (event == Event.MigrationFailedOnDest) { + /*release capacify from original host*/ + releaseResource(vm, false, false, vm.getHostId()); + } else if (event == Event.OperationSucceeded) { + releaseResource(vm, false, false, vm.getHostId()); + } + } else if (oldState == State.Stopping) { + if (event == Event.AgentReportStopped || event == Event.OperationSucceeded) { + releaseResource(vm, false, true, vm.getHostId()); + } + } else if (oldState == State.Stopped) { + if (event == Event.DestroyRequested) { + releaseResource(vm, true, false, vm.getHostId()); + + vm.setLastHostId(null); + + } + } + + transitionStatus = vmDao.updateState(oldState, event, newState, vm, id); + if (transitionStatus) { + txn.commit(); + } else { + s_logger.debug("Failed to transit vm's state"); + txn.rollback(); + } + } catch (Exception e) { + s_logger.debug("Failed to transit vm's state, due to " + e.getMessage()); + txn.rollback(); + } finally { + txn.close(); + } + + return transitionStatus; + } + + private void releaseResource(VMInstanceVO vm, boolean moveFromReserved, boolean moveToReservered, Long hostId) { + ServiceOfferingVO svo = _offeringDao.findById(vm.getServiceOfferingId()); + CapacityVO capacityCpu = _capacityDao.findByHostIdType(hostId, CapacityVO.CAPACITY_TYPE_CPU); + CapacityVO capacityMemory = _capacityDao.findByHostIdType(hostId, CapacityVO.CAPACITY_TYPE_MEMORY); + + if (capacityCpu == null || capacityMemory == null || svo == null) { + return; + } + + int vmCPU = svo.getCpu() * svo.getSpeed(); + long vmMem = svo.getRamSize() * 1024L * 1024L; + + capacityCpu = _capacityDao.lockRow(capacityCpu.getId(), true); + capacityMemory = _capacityDao.lockRow(capacityMemory.getId(), true); + + long usedCpu = capacityCpu.getUsedCapacity(); + long usedMem = capacityMemory.getUsedCapacity(); + long reservedCpu = capacityCpu.getReservedCapacity(); + long reservedMem = capacityMemory.getReservedCapacity(); + long totalCpu = capacityCpu.getTotalCapacity(); + long totalMem = capacityMemory.getTotalCapacity(); + + if (!moveFromReserved) { + /*move resource from used*/ + if (usedCpu >= vmCPU) + capacityCpu.setUsedCapacity(usedCpu - vmCPU); + if (usedMem >= vmMem) + capacityMemory.setUsedCapacity(usedMem - vmMem); + + if (moveToReservered) { + if (reservedCpu + vmCPU <= totalCpu) { + capacityCpu.setReservedCapacity(reservedCpu + vmCPU); + } + if (reservedMem + vmMem <= totalMem) { + capacityMemory.setReservedCapacity(reservedMem + vmMem); + } + } + } else { + if (reservedCpu >= vmCPU) { + capacityCpu.setReservedCapacity(reservedCpu - vmCPU); + } + if (reservedMem >= vmMem) { + capacityMemory.setReservedCapacity(reservedMem - vmMem); + } + } + + s_logger.debug("release cpu from host: " + hostId + ", old used: " + usedCpu + ",reserved: " + reservedCpu + ", total: " + totalCpu + + "; new used: " + capacityCpu.getUsedCapacity() + ",reserved:" + capacityCpu.getReservedCapacity() + ",total: " + capacityCpu.getTotalCapacity() + + "; movedfromreserved: " + moveFromReserved + ",moveToReservered" + moveToReservered); + + s_logger.debug("release mem from host: " + hostId + ", old used: " + usedMem + ",reserved: " + reservedMem + ", total: " + totalMem + + "; new used: " + capacityMemory.getUsedCapacity() + ",reserved:" + capacityMemory.getReservedCapacity() + ",total: " + capacityMemory.getTotalCapacity() + + "; movedfromreserved: " + moveFromReserved + ",moveToReservered" + moveToReservered); + + _capacityDao.update(capacityCpu.getId(), capacityCpu); + _capacityDao.update(capacityMemory.getId(), capacityMemory); + + } + + /*Add capacity to destination host, for migration*/ + private void addResource(VMInstanceVO vm, Long destHostId) { + ServiceOfferingVO svo = _offeringDao.findById(vm.getServiceOfferingId()); + CapacityVO capacityCpu = _capacityDao.findByHostIdType(destHostId, CapacityVO.CAPACITY_TYPE_CPU); + CapacityVO capacityMemory = _capacityDao.findByHostIdType(destHostId, CapacityVO.CAPACITY_TYPE_MEMORY); + int vmCPU = svo.getCpu() * svo.getSpeed(); + long vmMem = svo.getRamSize() * 1024L * 1024L; + + capacityCpu = _capacityDao.lockRow(capacityCpu.getId(), true); + capacityMemory = _capacityDao.lockRow(capacityMemory.getId(), true); + + long usedCpu = capacityCpu.getUsedCapacity(); + long usedMem = capacityMemory.getUsedCapacity(); + long reservedCpu = capacityCpu.getReservedCapacity(); + long reservedMem = capacityMemory.getReservedCapacity(); + long totalCpu = capacityCpu.getTotalCapacity(); + long totalMem = capacityMemory.getTotalCapacity(); + + if (usedCpu + reservedCpu + vmCPU <= totalCpu) { + capacityCpu.setUsedCapacity(usedCpu + vmCPU); + } else { + s_logger.debug("What's the heck? :u:" + usedCpu + ",r:" + reservedCpu + ",vm:" + vmCPU + " > " + totalCpu); + } + + if (usedMem + reservedMem + vmMem <= totalMem) { + capacityMemory.setUsedCapacity(usedMem + vmMem); + } else { + s_logger.debug("What's the heck? :u:" + usedMem + ",r:" + reservedMem + ",vm:" + vmMem + " > " + totalMem); + } + + _capacityDao.update(capacityCpu.getId(), capacityCpu); + _capacityDao.update(capacityMemory.getId(), capacityMemory); + + } +} diff --git a/server/src/com/cloud/vm/VmManager.java b/server/src/com/cloud/vm/VmManager.java index 63ea51d7474..8d3581bfb7e 100644 --- a/server/src/com/cloud/vm/VmManager.java +++ b/server/src/com/cloud/vm/VmManager.java @@ -27,6 +27,7 @@ import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.OperationTimedoutException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.exception.StorageUnavailableException; +import com.cloud.host.HostVO; import com.cloud.network.NetworkVO; import com.cloud.service.ServiceOfferingVO; import com.cloud.storage.DiskOfferingVO; @@ -35,6 +36,7 @@ import com.cloud.user.Account; import com.cloud.user.User; import com.cloud.utils.Pair; import com.cloud.utils.component.Manager; +import com.cloud.vm.VirtualMachine.Event; /** * Manages allocating resources to vms. @@ -75,5 +77,8 @@ public interface VmManager extends Manager { ; void registerGuru(VirtualMachine.Type type, VirtualMachineGuru guru); + + boolean stateTransitTo(VMInstanceVO vm, Event e, Long id); + } diff --git a/server/src/com/cloud/vm/dao/ConsoleProxyDao.java b/server/src/com/cloud/vm/dao/ConsoleProxyDao.java index f6ab6c94cff..d40083fd009 100644 --- a/server/src/com/cloud/vm/dao/ConsoleProxyDao.java +++ b/server/src/com/cloud/vm/dao/ConsoleProxyDao.java @@ -24,11 +24,13 @@ import java.util.List; import com.cloud.info.ConsoleProxyLoadInfo; import com.cloud.utils.Pair; import com.cloud.utils.db.GenericDao; +import com.cloud.utils.fsm.StateDao; import com.cloud.vm.ConsoleProxyVO; import com.cloud.vm.State; +import com.cloud.vm.VMInstanceVO; import com.cloud.vm.VirtualMachine; -public interface ConsoleProxyDao extends GenericDao { +public interface ConsoleProxyDao extends GenericDao, StateDao { public void update(long id, int activeSession, Date updateTime, byte[] sessionDetails); diff --git a/server/src/com/cloud/vm/dao/ConsoleProxyDaoImpl.java b/server/src/com/cloud/vm/dao/ConsoleProxyDaoImpl.java index 7936c22a370..45a6a564c35 100644 --- a/server/src/com/cloud/vm/dao/ConsoleProxyDaoImpl.java +++ b/server/src/com/cloud/vm/dao/ConsoleProxyDaoImpl.java @@ -39,7 +39,9 @@ import com.cloud.utils.db.Transaction; import com.cloud.utils.db.UpdateBuilder; import com.cloud.vm.ConsoleProxyVO; import com.cloud.vm.State; +import com.cloud.vm.VMInstanceVO; import com.cloud.vm.VirtualMachine; +import com.cloud.vm.VirtualMachine.Event; @Local(value={ConsoleProxyDao.class}) public class ConsoleProxyDaoImpl extends GenericDaoBase implements ConsoleProxyDao { @@ -386,5 +388,40 @@ public class ConsoleProxyDaoImpl extends GenericDaoBase im } catch (Throwable e) { } return l; - } + } + + @Override + public boolean updateState(State oldState, Event event, + State newState, VMInstanceVO vm, Long hostId) { + if (newState == null) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("There's no way to transition from old state: " + oldState.toString() + " event: " + event.toString()); + } + return false; + } + + ConsoleProxyVO consoleVM = (ConsoleProxyVO)vm; + + SearchCriteria sc = StateChangeSearch.create(); + sc.setParameters("id", consoleVM.getId()); + sc.setParameters("states", oldState); + sc.setParameters("host", consoleVM.getHostId()); + sc.setParameters("update", consoleVM.getUpdated()); + + vm.incrUpdated(); + UpdateBuilder ub = getUpdateBuilder(consoleVM); + ub.set(consoleVM, "state", newState); + ub.set(consoleVM, "hostId", hostId); + ub.set(consoleVM, _updateTimeAttr, new Date()); + + int result = update(consoleVM, sc); + if (result == 0 && s_logger.isDebugEnabled()) { + ConsoleProxyVO vo = findById(consoleVM.getId()); + StringBuilder str = new StringBuilder("Unable to update ").append(vo.toString()); + str.append(": DB Data={Host=").append(vo.getHostId()).append("; State=").append(vo.getState().toString()).append("; updated=").append(vo.getUpdated()); + str.append("} Stale Data: {Host=").append(consoleVM.getHostId()).append("; State=").append(consoleVM.getState().toString()).append("; updated=").append(consoleVM.getUpdated()).append("}"); + s_logger.debug(str.toString()); + } + return result > 0; + } } diff --git a/server/src/com/cloud/vm/dao/DomainRouterDao.java b/server/src/com/cloud/vm/dao/DomainRouterDao.java index f5cc5901752..0d31cf935a4 100755 --- a/server/src/com/cloud/vm/dao/DomainRouterDao.java +++ b/server/src/com/cloud/vm/dao/DomainRouterDao.java @@ -21,14 +21,17 @@ import java.util.List; import com.cloud.network.router.VirtualRouter.Role; import com.cloud.utils.db.GenericDao; +import com.cloud.utils.fsm.StateDao; import com.cloud.vm.DomainRouterVO; +import com.cloud.vm.State; +import com.cloud.vm.VMInstanceVO; import com.cloud.vm.VirtualMachine; /** * * DomainRouterDao implements */ -public interface DomainRouterDao extends GenericDao { +public interface DomainRouterDao extends GenericDao, StateDao { //@Deprecated //public boolean updateIf(DomainRouterVO router, State state, State... ifStates); @@ -63,7 +66,7 @@ public interface DomainRouterDao extends GenericDao { * @param hostId host id to set to. * @return true if update worked; false if not. */ - public boolean updateIf(DomainRouterVO router, VirtualMachine.Event event, Long hostId); + public boolean updateIf(DomainRouterVO router, VirtualMachine.Event event, Long hostId); /** * list virtual machine routers by host id. pass in null to get all diff --git a/server/src/com/cloud/vm/dao/DomainRouterDaoImpl.java b/server/src/com/cloud/vm/dao/DomainRouterDaoImpl.java index 50a43e5ae07..1157f159194 100755 --- a/server/src/com/cloud/vm/dao/DomainRouterDaoImpl.java +++ b/server/src/com/cloud/vm/dao/DomainRouterDaoImpl.java @@ -36,9 +36,12 @@ import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.Transaction; import com.cloud.utils.db.UpdateBuilder; import com.cloud.utils.exception.CloudRuntimeException; +import com.cloud.vm.ConsoleProxyVO; import com.cloud.vm.DomainRouterVO; import com.cloud.vm.State; +import com.cloud.vm.VMInstanceVO; import com.cloud.vm.VirtualMachine; +import com.cloud.vm.VirtualMachine.Event; @Local(value = { DomainRouterDao.class }) public class DomainRouterDaoImpl extends GenericDaoBase implements DomainRouterDao { @@ -307,4 +310,39 @@ public class DomainRouterDaoImpl extends GenericDaoBase im sc.setParameters("network", networkConfigurationId); return findOneBy(sc); } + + @Override + public boolean updateState(State oldState, Event event, + State newState, VMInstanceVO vm, Long hostId) { + if (newState == null) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("There's no way to transition from old state: " + oldState.toString() + " event: " + event.toString()); + } + return false; + } + + DomainRouterVO routerVM = (DomainRouterVO)vm; + + SearchCriteria sc = StateChangeSearch.create(); + sc.setParameters("id", routerVM.getId()); + sc.setParameters("states", oldState); + sc.setParameters("host", routerVM.getHostId()); + sc.setParameters("update", routerVM.getUpdated()); + + vm.incrUpdated(); + UpdateBuilder ub = getUpdateBuilder(routerVM); + ub.set(routerVM, "state", newState); + ub.set(routerVM, "hostId", hostId); + ub.set(routerVM, _updateTimeAttr, new Date()); + + int result = update(routerVM, sc); + if (result == 0 && s_logger.isDebugEnabled()) { + DomainRouterVO vo = findById(routerVM.getId()); + StringBuilder str = new StringBuilder("Unable to update ").append(vo.toString()); + str.append(": DB Data={Host=").append(vo.getHostId()).append("; State=").append(vo.getState().toString()).append("; updated=").append(vo.getUpdated()); + str.append("} Stale Data: {Host=").append(routerVM.getHostId()).append("; State=").append(routerVM.getState().toString()).append("; updated=").append(routerVM.getUpdated()).append("}"); + s_logger.debug(str.toString()); + } + return result > 0; + } } diff --git a/server/src/com/cloud/vm/dao/SecondaryStorageVmDao.java b/server/src/com/cloud/vm/dao/SecondaryStorageVmDao.java index 5c6cb8e3399..cd67c6ce389 100644 --- a/server/src/com/cloud/vm/dao/SecondaryStorageVmDao.java +++ b/server/src/com/cloud/vm/dao/SecondaryStorageVmDao.java @@ -21,11 +21,13 @@ import java.util.List; import com.cloud.utils.db.GenericDao; +import com.cloud.utils.fsm.StateDao; import com.cloud.vm.SecondaryStorageVmVO; import com.cloud.vm.State; +import com.cloud.vm.VMInstanceVO; import com.cloud.vm.VirtualMachine; -public interface SecondaryStorageVmDao extends GenericDao { +public interface SecondaryStorageVmDao extends GenericDao, StateDao { public List getSecStorageVmListInStates(long dataCenterId, State... states); public List getSecStorageVmListInStates(State... states); diff --git a/server/src/com/cloud/vm/dao/SecondaryStorageVmDaoImpl.java b/server/src/com/cloud/vm/dao/SecondaryStorageVmDaoImpl.java index d5ff13312b8..f35c5ca5d5e 100644 --- a/server/src/com/cloud/vm/dao/SecondaryStorageVmDaoImpl.java +++ b/server/src/com/cloud/vm/dao/SecondaryStorageVmDaoImpl.java @@ -34,9 +34,12 @@ import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.Transaction; import com.cloud.utils.db.UpdateBuilder; +import com.cloud.vm.ConsoleProxyVO; import com.cloud.vm.SecondaryStorageVmVO; import com.cloud.vm.State; +import com.cloud.vm.VMInstanceVO; import com.cloud.vm.VirtualMachine; +import com.cloud.vm.VirtualMachine.Event; @Local(value={SecondaryStorageVmDao.class}) public class SecondaryStorageVmDaoImpl extends GenericDaoBase implements SecondaryStorageVmDao { @@ -209,5 +212,40 @@ public class SecondaryStorageVmDaoImpl extends GenericDaoBase sc = ZoneSearch.create(); sc.setParameters("zone", zoneId); return listBy(sc); + } + + @Override + public boolean updateState(State oldState, Event event, + State newState, VMInstanceVO vm, Long hostId) { + if (newState == null) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("There's no way to transition from old state: " + oldState.toString() + " event: " + event.toString()); + } + return false; + } + + SecondaryStorageVmVO secondaryVM = (SecondaryStorageVmVO)vm; + + SearchCriteria sc = StateChangeSearch.create(); + sc.setParameters("id", secondaryVM.getId()); + sc.setParameters("states", oldState); + sc.setParameters("host", secondaryVM.getHostId()); + sc.setParameters("update", secondaryVM.getUpdated()); + + vm.incrUpdated(); + UpdateBuilder ub = getUpdateBuilder(secondaryVM); + ub.set(secondaryVM, "state", newState); + ub.set(secondaryVM, "hostId", hostId); + ub.set(secondaryVM, _updateTimeAttr, new Date()); + + int result = update(secondaryVM, sc); + if (result == 0 && s_logger.isDebugEnabled()) { + SecondaryStorageVmVO vo = findById(secondaryVM.getId()); + StringBuilder str = new StringBuilder("Unable to update ").append(vo.toString()); + str.append(": DB Data={Host=").append(vo.getHostId()).append("; State=").append(vo.getState().toString()).append("; updated=").append(vo.getUpdated()); + str.append("} Stale Data: {Host=").append(secondaryVM.getHostId()).append("; State=").append(secondaryVM.getState().toString()).append("; updated=").append(secondaryVM.getUpdated()).append("}"); + s_logger.debug(str.toString()); + } + return result > 0; } } diff --git a/server/src/com/cloud/vm/dao/UserVmDao.java b/server/src/com/cloud/vm/dao/UserVmDao.java index 1ca3aa874f9..935645c548c 100755 --- a/server/src/com/cloud/vm/dao/UserVmDao.java +++ b/server/src/com/cloud/vm/dao/UserVmDao.java @@ -22,11 +22,13 @@ import java.util.List; import com.cloud.uservm.UserVm; import com.cloud.utils.db.GenericDao; +import com.cloud.utils.fsm.StateDao; import com.cloud.vm.State; import com.cloud.vm.UserVmVO; +import com.cloud.vm.VMInstanceVO; import com.cloud.vm.VirtualMachine; -public interface UserVmDao extends GenericDao { +public interface UserVmDao extends GenericDao, StateDao { List listByAccountId(long id); List listByAccountAndPod(long accountId, long podId); diff --git a/server/src/com/cloud/vm/dao/UserVmDaoImpl.java b/server/src/com/cloud/vm/dao/UserVmDaoImpl.java index 75650783317..7ff84b617b6 100755 --- a/server/src/com/cloud/vm/dao/UserVmDaoImpl.java +++ b/server/src/com/cloud/vm/dao/UserVmDaoImpl.java @@ -37,7 +37,9 @@ import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.UpdateBuilder; import com.cloud.vm.State; import com.cloud.vm.UserVmVO; +import com.cloud.vm.VMInstanceVO; import com.cloud.vm.VirtualMachine; +import com.cloud.vm.VirtualMachine.Event; @Local(value={UserVmDao.class}) public class UserVmDaoImpl extends GenericDaoBase implements UserVmDao { @@ -175,7 +177,7 @@ public class UserVmDaoImpl extends GenericDaoBase implements Use return listIncludingRemovedBy(sc); } - @Override + @Override public boolean updateIf(UserVmVO vm, VirtualMachine.Event event, Long hostId) { if (s_logger.isDebugEnabled()) { s_logger.debug("UpdateIf called " + vm.toString() + " event " + event.toString() + " host " + hostId); @@ -287,7 +289,7 @@ public class UserVmDaoImpl extends GenericDaoBase implements Use SearchCriteria sc = AccountDataCenterVirtualSearch.create(); sc.setParameters("account", accountId); sc.setParameters("dc", dcId); - sc.setJoinParameters("offeringSearch", "guestIpType", NetworkOffering.GuestIpType.Virtualized); + sc.setJoinParameters("offeringSearch", "guestIpType", NetworkOffering.GuestIpType.Virtual); return listBy(sc); } @@ -311,4 +313,39 @@ public class UserVmDaoImpl extends GenericDaoBase implements Use return findOneBy(sc); } + + @Override + public boolean updateState(State oldState, Event event, + State newState, VMInstanceVO vm, Long hostId) { + if (newState == null) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("There's no way to transition from old state: " + oldState.toString() + " event: " + event.toString()); + } + return false; + } + + UserVmVO userVM = (UserVmVO)vm; + + SearchCriteria sc = StateChangeSearch.create(); + sc.setParameters("id", userVM.getId()); + sc.setParameters("states", oldState); + sc.setParameters("host", userVM.getHostId()); + sc.setParameters("update", userVM.getUpdated()); + + vm.incrUpdated(); + UpdateBuilder ub = getUpdateBuilder(userVM); + ub.set(userVM, "state", newState); + ub.set(userVM, "hostId", hostId); + ub.set(userVM, _updateTimeAttr, new Date()); + + int result = update(userVM, sc); + if (result == 0 && s_logger.isDebugEnabled()) { + UserVmVO vo = findById(userVM.getId()); + StringBuilder str = new StringBuilder("Unable to update ").append(vo.toString()); + str.append(": DB Data={Host=").append(vo.getHostId()).append("; State=").append(vo.getState().toString()).append("; updated=").append(vo.getUpdated()); + str.append("} Stale Data: {Host=").append(userVM.getHostId()).append("; State=").append(userVM.getState().toString()).append("; updated=").append(userVM.getUpdated()).append("}"); + s_logger.debug(str.toString()); + } + return result > 0; + } } diff --git a/server/src/com/cloud/vm/dao/VMInstanceDao.java b/server/src/com/cloud/vm/dao/VMInstanceDao.java index d496a80f4f3..8403cf6d3b8 100644 --- a/server/src/com/cloud/vm/dao/VMInstanceDao.java +++ b/server/src/com/cloud/vm/dao/VMInstanceDao.java @@ -22,6 +22,7 @@ import java.util.Date; import java.util.List; import com.cloud.utils.db.GenericDao; +import com.cloud.utils.fsm.StateDao; import com.cloud.vm.State; import com.cloud.vm.VMInstanceVO; import com.cloud.vm.VirtualMachine; @@ -29,7 +30,7 @@ import com.cloud.vm.VirtualMachine; /* * Data Access Object for vm_instance table */ -public interface VMInstanceDao extends GenericDao { +public interface VMInstanceDao extends GenericDao, StateDao { /** * What are the vms running on this host? * @param hostId host. diff --git a/server/src/com/cloud/vm/dao/VMInstanceDaoImpl.java b/server/src/com/cloud/vm/dao/VMInstanceDaoImpl.java index d5b1ab90023..e927a8dea49 100644 --- a/server/src/com/cloud/vm/dao/VMInstanceDaoImpl.java +++ b/server/src/com/cloud/vm/dao/VMInstanceDaoImpl.java @@ -37,6 +37,7 @@ import com.cloud.utils.db.UpdateBuilder; import com.cloud.vm.State; import com.cloud.vm.VMInstanceVO; import com.cloud.vm.VirtualMachine; +import com.cloud.vm.VirtualMachine.Event; import com.cloud.vm.VirtualMachine.Type; @Local(value = { VMInstanceDao.class }) @@ -291,4 +292,37 @@ public class VMInstanceDaoImpl extends GenericDaoBase implem vo.setProxyAssignTime(time); update(id, vo); } + + @Override + public boolean updateState(State oldState, Event event, + State newState, VMInstanceVO vm, Long hostId) { + if (newState == null) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("There's no way to transition from old state: " + oldState.toString() + " event: " + event.toString()); + } + return false; + } + + SearchCriteria sc = StateChangeSearch.create(); + sc.setParameters("id", vm.getId()); + sc.setParameters("states", oldState); + sc.setParameters("host", vm.getHostId()); + sc.setParameters("update", vm.getUpdated()); + + vm.incrUpdated(); + UpdateBuilder ub = getUpdateBuilder(vm); + ub.set(vm, "state", newState); + ub.set(vm, "hostId", hostId); + ub.set(vm, _updateTimeAttr, new Date()); + + int result = update(vm, sc); + if (result == 0 && s_logger.isDebugEnabled()) { + VMInstanceVO vo = findById(vm.getId()); + StringBuilder str = new StringBuilder("Unable to update ").append(vo.toString()); + str.append(": DB Data={Host=").append(vo.getHostId()).append("; State=").append(vo.getState().toString()).append("; updated=").append(vo.getUpdated()); + str.append("} Stale Data: {Host=").append(vm.getHostId()).append("; State=").append(vm.getState().toString()).append("; updated=").append(vm.getUpdated()).append("}"); + s_logger.debug(str.toString()); + } + return result > 0; + } } diff --git a/server/wscript_build b/server/wscript_build deleted file mode 100644 index f6660680f77..00000000000 --- a/server/wscript_build +++ /dev/null @@ -1,4 +0,0 @@ -import Options - -if not Options.options.PRESERVECONFIG: - bld.install_files_filtered("${SERVERSYSCONFDIR}","conf/*") diff --git a/setup/db/create-index-fk.sql b/setup/db/create-index-fk.sql index 65fe768283f..259b2956a4c 100755 --- a/setup/db/create-index-fk.sql +++ b/setup/db/create-index-fk.sql @@ -58,8 +58,6 @@ ALTER TABLE `cloud`.`storage_pool` ADD CONSTRAINT `fk_storage_pool__cluster_id` ALTER TABLE `cloud`.`storage_pool_details` ADD CONSTRAINT `fk_storage_pool_details__pool_id` FOREIGN KEY `fk_storage_pool__pool_id`(`pool_id`) REFERENCES `storage_pool`(`id`) ON DELETE CASCADE; ALTER TABLE `cloud`.`storage_pool_details` ADD INDEX `i_storage_pool_details__name__value`(`name`(128), `value`(128)); -ALTER TABLE `cloud`.`op_networks` ADD CONSTRAINT `fk_op_networks__id` FOREIGN KEY `fk_op_networks__id`(`id`) REFERENCES `networks`(`id`) ON DELETE CASCADE; - ALTER TABLE `cloud`.`user` ADD INDEX `i_user__secret_key_removed`(`secret_key`, `removed`); ALTER TABLE `cloud`.`user` ADD INDEX `i_user__removed`(`removed`); ALTER TABLE `cloud`.`user` ADD UNIQUE `i_user__api_key`(`api_key`); diff --git a/setup/db/create-schema.sql b/setup/db/create-schema.sql index 89a2e66ba22..5e6cb7b0c3f 100755 --- a/setup/db/create-schema.sql +++ b/setup/db/create-schema.sql @@ -1,4 +1,7 @@ SET foreign_key_checks = 0; +use cloud; + +DROP VIEW IF EXISTS `cloud`.`port_forwarding_rules_view`; DROP TABLE IF EXISTS `cloud`.`configuration`; DROP TABLE IF EXISTS `cloud`.`ip_forwarding`; DROP TABLE IF EXISTS `cloud`.`management_agent`; @@ -84,6 +87,10 @@ DROP TABLE IF EXISTS `cloud`.`instance_group`; DROP TABLE IF EXISTS `cloud`.`instance_group_vm_map`; DROP TABLE IF EXISTS `cloud`.`certificate`; DROP TABLE IF EXISTS `cloud`.`op_it_work`; +DROP TABLE IF EXISTS `cloud`.`load_balancing_ip_map`; +DROP TABLE IF EXISTS `cloud`.`load_balancing_rules`; +DROP TABLE IF EXISTS `cloud`.`port_forwarding_rules`; +DROP TABLE IF EXISTS `cloud`.`firewall_rules`; CREATE TABLE `cloud`.`op_it_work` ( `id` char(40) COMMENT 'id', @@ -106,7 +113,8 @@ CREATE TABLE `cloud`.`hypervsior_properties` ( CREATE TABLE `cloud`.`op_networks`( `id` bigint unsigned NOT NULL UNIQUE KEY, `mac_address_seq` bigint unsigned NOT NULL DEFAULT 1 COMMENT 'mac address', - PRIMARY KEY(`id`) + PRIMARY KEY(`id`), + CONSTRAINT `fk_op_networks__id` FOREIGN KEY (`id`) REFERENCES `networks`(`id`) ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `cloud`.`networks` ( @@ -131,6 +139,7 @@ CREATE TABLE `cloud`.`networks` ( `guru_data` varchar(1024) COMMENT 'data stored by the network guru that setup this network', `set_fields` bigint unsigned NOT NULL DEFAULT 0 COMMENT 'which fields are set already', `guest_type` char(32) COMMENT 'type of guest network', + `shared` int(1) unsigned NOT NULL DEFAULT 0 COMMENT '0 if network is shared, 1 if network dedicated', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; @@ -191,7 +200,6 @@ CREATE TABLE `cloud`.`network_offerings` ( `service_offering_id` bigint unsigned UNIQUE COMMENT 'service offering id that this network offering is tied to', `created` datetime NOT NULL COMMENT 'time the entry was created', `removed` datetime DEFAULT NULL COMMENT 'time the entry was removed', - `shared` int(1) unsigned NOT NULL DEFAULT 0 COMMENT '0 if network is shared, 1 if network dedicated', `default` int(1) unsigned NOT NULL DEFAULT 0 COMMENT '1 if network is default', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; @@ -316,11 +324,12 @@ CREATE TABLE `cloud`.`volumes` ( `state` varchar(32) COMMENT 'State machine', `source_id` bigint unsigned COMMENT 'id for the source', `source_type` varchar(32) COMMENT 'source from which the volume is created -- snapshot, diskoffering, template, blank', + `chain_info` text COMMENT 'save possible disk chain info in primary storage', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `cloud`.`snapshots` ( - `id` bigint unsigned NOT NULL COMMENT 'Primary Key', + `id` bigint unsigned UNIQUE NOT NULL COMMENT 'Primary Key', `account_id` bigint unsigned NOT NULL COMMENT 'owner. foreign key to account table', `volume_id` bigint unsigned NOT NULL COMMENT 'volume it belongs to. foreign key to volume table', `status` varchar(32) COMMENT 'snapshot creation status', @@ -425,6 +434,58 @@ CREATE TABLE `cloud`.`op_dc_vnet_alloc` ( PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; +CREATE TABLE `cloud`.`firewall_rules` ( + `id` bigint unsigned NOT NULL auto_increment COMMENT 'id', + `ip_address` bigint unsigned NOT NULL COMMENT 'ip_address', + `start_port` int(10) NOT NULL default -1 COMMENT 'starting port of a port range', + `end_port` int(10) NOT NULL default -1 COMMENT 'end port of a port range', + `state` char(32) NOT NULL COMMENT 'current state of this rule', + `protocol` char(16) NOT NULL default 'TCP' COMMENT 'protocol to open these ports for', + `purpose` char(32) NOT NULL COMMENT 'why are these ports opened?', + `account_id` bigint unsigned NOT NULL COMMENT 'owner id', + `domain_id` bigint unsigned NOT NULL COMMENT 'domain id', + `network_id` bigint unsigned NOT NULL COMMENT 'network id', + `xid` char(40) NOT NULL COMMENT 'external id', + `created` datetime COMMENT 'Date created', + PRIMARY KEY (`id`), + CONSTRAINT `fk_firewall_rules__network_id` FOREIGN KEY(`network_id`) REFERENCES `networks`(`id`) ON DELETE CASCADE, + CONSTRAINT `fk_firewall_rules__account_id` FOREIGN KEY(`account_id`) REFERENCES `account`(`id`) ON DELETE CASCADE, + CONSTRAINT `fk_firewall_rules__domain_id` FOREIGN KEY(`domain_id`) REFERENCES `domain`(`id`) ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +CREATE TABLE `cloud`.`load_balancing_rules` ( + `id` bigint unsigned NOT NULL, + `name` varchar(255) NOT NULL, + `description` varchar(4096) NULL COMMENT 'description', + `default_port_start` int(10) NOT NULL COMMENT 'default private port range start', + `default_port_end` int(10) NOT NULL COMMENT 'default destination port range end', + `algorithm` varchar(255) NOT NULL, + PRIMARY KEY (`id`), + CONSTRAINT `fk_load_balancing_rules__id` FOREIGN KEY(`id`) REFERENCES `firewall_rules`(`id`) ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +CREATE TABLE `cloud`.`load_balancer_vm_map` ( + `id` bigint unsigned NOT NULL auto_increment, + `load_balancer_id` bigint unsigned NOT NULL, + `instance_id` bigint unsigned NOT NULL, + `pending` tinyint(1) unsigned NOT NULL DEFAULT 0 COMMENT 'whether the vm is being applied to the load balancer (pending=1) or has already been applied (pending=0)', + PRIMARY KEY (`id`), + UNIQUE KEY (`load_balancer_id`, `instance_id`), + CONSTRAINT `fk_load_balancer_vm_map__load_balancer_id` FOREIGN KEY(`load_balancer_id`) REFERENCES `load_balancing_rules`(`id`) ON DELETE CASCADE, + CONSTRAINT `fk_load_balancer_vm_map__instance_id` FOREIGN KEY(`instance_id`) REFERENCES `vm_instance`(`id`) ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +CREATE TABLE `cloud`.`port_forwarding_rules` ( + `id` bigint unsigned NOT NULL COMMENT 'id', + `dest_ip_address` bigint unsigned NOT NULL COMMENT 'id_address', + `dest_port_start` int(10) NOT NULL COMMENT 'starting port of the port range to map to', + `dest_port_end` int(10) NOT NULL COMMENT 'end port of the the port range to map to', + PRIMARY KEY (`id`), + CONSTRAINT `fk_port_forwarding_rules__id` FOREIGN KEY(`id`) REFERENCES `firewall_rules`(`id`) ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +CREATE VIEW `cloud`.`port_forwarding_rules_view` AS SELECT fw.id, INET_NTOA(fw.ip_address) as src_ip_address, INET_NTOA(pf.dest_ip_address), fw.start_port as src_port_start, pf.dest_port_start, fw.end_port as src_end_port, pf.dest_port_end as dest_end_port, fw.state, fw.protocol, fw.purpose, fw.account_id from cloud.firewall_rules as fw inner join cloud.port_forwarding_rules as pf on fw.id=pf.id; + CREATE TABLE `cloud`.`ip_forwarding` ( `id` bigint unsigned NOT NULL auto_increment, `group_id` bigint unsigned default NULL, @@ -439,6 +500,7 @@ CREATE TABLE `cloud`.`ip_forwarding` ( PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; + CREATE TABLE `cloud`.`host` ( `id` bigint unsigned NOT NULL auto_increment, `name` varchar(255) NOT NULL, @@ -550,6 +612,7 @@ CREATE TABLE `cloud`.`user_ip_address` ( `allocated` datetime NULL COMMENT 'Date this ip was allocated to someone', `vlan_db_id` bigint unsigned NOT NULL, `one_to_one_nat` int(1) unsigned NOT NULL default '0', + `state` char(32) NOT NULL default 'Free' COMMENT 'state of the ip address', PRIMARY KEY (`public_ip_address`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; @@ -802,6 +865,7 @@ CREATE TABLE `cloud`.`op_host_capacity` ( `data_center_id` bigint unsigned NOT NULL, `pod_id` bigint unsigned, `used_capacity` bigint unsigned NOT NULL, + `reserved_capacity` bigint unsigned NOT NULL, `total_capacity` bigint unsigned NOT NULL, `capacity_type` int(1) unsigned NOT NULL, PRIMARY KEY (`id`) @@ -946,14 +1010,6 @@ CREATE TABLE `cloud`.`security_group_vm_map` ( PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -CREATE TABLE `cloud`.`load_balancer_vm_map` ( - `id` bigint unsigned NOT NULL auto_increment, - `load_balancer_id` bigint unsigned NOT NULL, - `instance_id` bigint unsigned NOT NULL, - `pending` tinyint(1) unsigned NOT NULL DEFAULT 0 COMMENT 'whether the vm is being applied to the load balancer (pending=1) or has already been applied (pending=0)', - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - CREATE TABLE `cloud`.`load_balancer` ( `id` bigint unsigned NOT NULL auto_increment, `name` varchar(255) NOT NULL, diff --git a/setup/db/data-21to22.sql b/setup/db/data-21to22.sql index 7fcc35e36a8..5a7f82136be 100644 --- a/setup/db/data-21to22.sql +++ b/setup/db/data-21to22.sql @@ -17,5 +17,6 @@ INSERT INTO vm_template (id, unique_name, name, public, created, type, hvm, bits Update configuration set name='storage.max.volume.size' where name='max.volume.size.mb'; INSERT INTO sequence (name, value) VALUES ('snapshots_seq', '1') +UPDATE cloud.sequence SET value=IF((SELECT COUNT(*) FROM cloud.snapshots) > 0, (SELECT max(id) FROM cloud.snapshots) + 1, 1) WHERE name='snapshots_seq' COMMIT; diff --git a/setup/db/data-22beta1to22beta2.sql b/setup/db/data-22beta1to22beta2.sql index f52a94b3651..1d082a6fd8d 100644 --- a/setup/db/data-22beta1to22beta2.sql +++ b/setup/db/data-22beta1to22beta2.sql @@ -1,2 +1,3 @@ INSERT INTO sequence (name, value) VALUES ('snapshots_seq', '1') +UPDATE cloud.sequence SET value=IF((SELECT COUNT(*) FROM cloud.snapshots) > 0, (SELECT max(id) FROM cloud.snapshots) + 1, 1) WHERE name='snapshots_seq' diff --git a/ui/index.jsp b/ui/index.jsp index 81f7e91999b..4a0eb646d17 100644 --- a/ui/index.jsp +++ b/ui/index.jsp @@ -701,7 +701,7 @@
-