Build fixes after first pass at merge

This commit is contained in:
Chiradeep Vittal 2011-05-02 18:57:42 -07:00
parent 303e2a7481
commit b42ebf4872
12 changed files with 667 additions and 593 deletions

View File

@ -556,7 +556,6 @@ public class FakeComputingResource extends ServerResourceBase implements ServerR
VolumeTO vol = new VolumeTO(cmd.getVolumeId(), VolumeTO vol = new VolumeTO(cmd.getVolumeId(),
Volume.Type.ROOT, Volume.Type.ROOT,
Storage.StorageResourceType.STORAGE_POOL,
com.cloud.storage.Storage.StoragePoolType.LVM, cmd com.cloud.storage.Storage.StoragePoolType.LVM, cmd
.getPool().getUuid(), "dummy", "/mountpoint", .getPool().getUuid(), "dummy", "/mountpoint",
"dummyPath", 1000L, null); "dummyPath", 1000L, null);

View File

@ -78,6 +78,7 @@ import com.cloud.agent.api.CleanupNetworkRulesCmd;
import com.cloud.agent.api.Command; import com.cloud.agent.api.Command;
import com.cloud.agent.api.CreatePrivateTemplateFromSnapshotCommand; import com.cloud.agent.api.CreatePrivateTemplateFromSnapshotCommand;
import com.cloud.agent.api.CreatePrivateTemplateFromVolumeCommand; import com.cloud.agent.api.CreatePrivateTemplateFromVolumeCommand;
import com.cloud.agent.api.CreateStoragePoolCommand;
import com.cloud.agent.api.CreateVolumeFromSnapshotAnswer; import com.cloud.agent.api.CreateVolumeFromSnapshotAnswer;
import com.cloud.agent.api.CreateVolumeFromSnapshotCommand; import com.cloud.agent.api.CreateVolumeFromSnapshotCommand;
import com.cloud.agent.api.DeleteSnapshotBackupAnswer; import com.cloud.agent.api.DeleteSnapshotBackupAnswer;

View File

@ -221,7 +221,7 @@ public class ApiConstants {
public static final String PING_STORAGE_SERVER_IP = "pingstorageserverip"; public static final String PING_STORAGE_SERVER_IP = "pingstorageserverip";
public static final String PING_DIR = "pingdir"; public static final String PING_DIR = "pingdir";
public static final String TFTP_DIR = "tftpdir"; public static final String TFTP_DIR = "tftpdir";
public static final String PZING_CIFS_USERNAME = "pingcifsusername"; public static final String PING_CIFS_USERNAME = "pingcifsusername";
public static final String PING_CIFS_PASSWORD = "pingcifspassword"; public static final String PING_CIFS_PASSWORD = "pingcifspassword";
public static final String CHECKSUM="checksum"; public static final String CHECKSUM="checksum";
public static final String NETWORK_DEVICE_TYPE = "networkdevicetype"; public static final String NETWORK_DEVICE_TYPE = "networkdevicetype";

View File

@ -520,35 +520,6 @@ public class VirtualRoutingResource implements Manager {
} }
} }
private void deletExitingLinkLocalRoutTable(String linkLocalBr) {
Script command = new Script("/bin/bash", _timeout);
command.add("-c");
command.add("ip route | grep " + NetUtils.getLinkLocalCIDR());
OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser();
String result = command.execute(parser);
boolean foundLinkLocalBr = false;
if (result == null && parser.getLines() != null) {
String[] lines = parser.getLines().split("\\n");
for (String line : lines) {
String[] tokens = line.split(" ");
if (!tokens[2].equalsIgnoreCase(linkLocalBr)) {
Script.runSimpleBashScript("ip route del " + NetUtils.getLinkLocalCIDR());
} else {
foundLinkLocalBr = true;
}
}
}
if (!foundLinkLocalBr) {
Script.runSimpleBashScript("ip route add " + NetUtils.getLinkLocalCIDR() + " dev " + linkLocalBr + " src " + NetUtils.getLinkLocalGateway());
}
}
public void createControlNetwork(String privBrName) {
deletExitingLinkLocalRoutTable(privBrName);
if (!isBridgeExists(privBrName)) {
Script.runSimpleBashScript("brctl addbr " + privBrName + "; ifconfig " + privBrName + " up;", _timeout);
}
}
// protected Answer execute(final SetFirewallRuleCommand cmd) { // protected Answer execute(final SetFirewallRuleCommand cmd) {
// String args; // String args;

View File

@ -142,15 +142,6 @@ public interface AgentManager extends Manager {
int registerForHostEvents(Listener listener, boolean connections, boolean commands, boolean priority); int registerForHostEvents(Listener listener, boolean connections, boolean commands, boolean priority);
/**
* Register to listen for initial agent connections.
* @param creator
* @param priority in listening for events.
* @return id to unregister if needed.
*/
int registerForInitialConnects(StartupCommandProcessor creator, boolean priority);
/** /**
* Register to listen for initial agent connections. * Register to listen for initial agent connections.
* @param creator * @param creator

View File

@ -238,7 +238,6 @@ public enum Config {
DefaultMaxAccountTemplates("Account Defaults", ManagementServer.class, Long.class, "max.account.templates", "20", "The default maximum number of templates that can be deployed for an account", null), DefaultMaxAccountTemplates("Account Defaults", ManagementServer.class, Long.class, "max.account.templates", "20", "The default maximum number of templates that can be deployed for an account", null),
DefaultMaxAccountSnapshots("Account Defaults", ManagementServer.class, Long.class, "max.account.snapshots", "20", "The default maximum number of snapshots that can be created for an account", null), DefaultMaxAccountSnapshots("Account Defaults", ManagementServer.class, Long.class, "max.account.snapshots", "20", "The default maximum number of snapshots that can be created for an account", null),
DefaultMaxAccountVolumes("Account Defaults", ManagementServer.class, Long.class, "max.account.volumes", "20", "The default maximum number of volumes that can be created for an account", null); DefaultMaxAccountVolumes("Account Defaults", ManagementServer.class, Long.class, "max.account.volumes", "20", "The default maximum number of volumes that can be created for an account", null);
EndpointeUrl("Advanced", ManagementServer.class, String.class, "endpointe.url", "http://localhost:8080/client/api", "Endpointe Url", null);
private final String _category; private final String _category;
private final Class<?> _componentClass; private final Class<?> _componentClass;

View File

@ -260,10 +260,6 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
@Override @Override
public ConsoleProxyInfo assignProxy(final long dataCenterId, final long vmId) { public ConsoleProxyInfo assignProxy(final long dataCenterId, final long vmId) {
if (!isConsoleProxyVmRequired(dataCenterId)) {
return null;
}
final Pair<ConsoleProxyManagerImpl, ConsoleProxyVO> result = new Pair<ConsoleProxyManagerImpl, ConsoleProxyVO>(this, null); final Pair<ConsoleProxyManagerImpl, ConsoleProxyVO> result = new Pair<ConsoleProxyManagerImpl, ConsoleProxyVO>(this, null);
_requestHandlerScheduler.execute(new Runnable() { _requestHandlerScheduler.execute(new Runnable() {

View File

@ -19,7 +19,6 @@ package com.cloud.host.dao;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Map;
import com.cloud.host.Host; import com.cloud.host.Host;
import com.cloud.host.Host.Type; import com.cloud.host.Host.Type;
@ -98,6 +97,8 @@ public interface HostDao extends GenericDao<HostVO, Long> {
*/ */
public HostVO findByGuid(String macAddress); public HostVO findByGuid(String macAddress);
public HostVO findByName(String name);
/** /**
* find all hosts of a certain type in a data center * find all hosts of a certain type in a data center
@ -139,6 +140,8 @@ public interface HostDao extends GenericDao<HostVO, Long> {
void loadDetails(HostVO host); void loadDetails(HostVO host);
void saveDetails(HostVO host);
HostVO findConsoleProxyHost(String name, Type type); HostVO findConsoleProxyHost(String name, Type type);
List<HypervisorType> getAvailHypervisorInZone(long hostId, long zoneId); List<HypervisorType> getAvailHypervisorInZone(long hostId, long zoneId);
@ -163,5 +166,4 @@ public interface HostDao extends GenericDao<HostVO, Long> {
long countRoutingHostsByDataCenter(long dcId); long countRoutingHostsByDataCenter(long dcId);
List<HostVO> listSecondaryStorageHosts(long dataCenterId); List<HostVO> listSecondaryStorageHosts(long dataCenterId);
} }

View File

@ -78,6 +78,7 @@ public class HostDaoImpl extends GenericDaoBase<HostVO, Long> implements HostDao
protected final SearchBuilder<HostVO> TypeSearch; protected final SearchBuilder<HostVO> TypeSearch;
protected final SearchBuilder<HostVO> StatusSearch; protected final SearchBuilder<HostVO> StatusSearch;
protected final SearchBuilder<HostVO> NameLikeSearch; protected final SearchBuilder<HostVO> NameLikeSearch;
protected final SearchBuilder<HostVO> NameSearch;
protected final SearchBuilder<HostVO> SequenceSearch; protected final SearchBuilder<HostVO> SequenceSearch;
protected final SearchBuilder<HostVO> DirectlyConnectedSearch; protected final SearchBuilder<HostVO> DirectlyConnectedSearch;
protected final SearchBuilder<HostVO> UnmanagedDirectConnectSearch; protected final SearchBuilder<HostVO> UnmanagedDirectConnectSearch;
@ -183,6 +184,10 @@ public class HostDaoImpl extends GenericDaoBase<HostVO, Long> implements HostDao
StatusSearch.and("status", StatusSearch.entity().getStatus(), SearchCriteria.Op.IN); StatusSearch.and("status", StatusSearch.entity().getStatus(), SearchCriteria.Op.IN);
StatusSearch.done(); StatusSearch.done();
NameSearch = createSearchBuilder();
NameSearch.and("name", NameSearch.entity().getName(), SearchCriteria.Op.EQ);
NameSearch.done();
NameLikeSearch = createSearchBuilder(); NameLikeSearch = createSearchBuilder();
NameLikeSearch.and("name", NameLikeSearch.entity().getName(), SearchCriteria.Op.LIKE); NameLikeSearch.and("name", NameLikeSearch.entity().getName(), SearchCriteria.Op.LIKE);
NameLikeSearch.done(); NameLikeSearch.done();
@ -525,6 +530,12 @@ public class HostDaoImpl extends GenericDaoBase<HostVO, Long> implements HostDao
return findOneBy(sc); return findOneBy(sc);
} }
@Override
public HostVO findByName(String name) {
SearchCriteria<HostVO> sc = NameSearch.create("name", name);
return findOneBy(sc);
}
@Override @Override
public List<HostVO> findLostHosts(long timeout) { public List<HostVO> findLostHosts(long timeout) {
SearchCriteria<HostVO> sc = LastPingedSearch.create(); SearchCriteria<HostVO> sc = LastPingedSearch.create();
@ -598,7 +609,7 @@ public class HostDaoImpl extends GenericDaoBase<HostVO, Long> implements HostDao
return listBy(sc); return listBy(sc);
} }
protected void saveDetails(HostVO host) { public void saveDetails(HostVO host) {
Map<String, String> details = host.getDetails(); Map<String, String> details = host.getDetails();
if (details == null) { if (details == null) {
return; return;

View File

@ -24,8 +24,10 @@ import javax.ejb.Local;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import com.cloud.configuration.ZoneConfig;
import com.cloud.dc.DataCenter; import com.cloud.dc.DataCenter;
import com.cloud.dc.DataCenter.NetworkType; import com.cloud.dc.DataCenter.NetworkType;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.Pod; import com.cloud.dc.Pod;
import com.cloud.dc.Vlan; import com.cloud.dc.Vlan;
import com.cloud.dc.Vlan.VlanType; import com.cloud.dc.Vlan.VlanType;

View File

@ -17,12 +17,18 @@
*/ */
package com.cloud.network.router; package com.cloud.network.router;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.Comparator; import java.util.Comparator;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.StringTokenizer;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@ -173,8 +179,7 @@ import com.cloud.vm.dao.UserVmDao;
import com.cloud.vm.dao.VMInstanceDao; import com.cloud.vm.dao.VMInstanceDao;
/** /**
* VirtualNetworkApplianceManagerImpl manages the different types of * VirtualNetworkApplianceManagerImpl manages the different types of virtual network appliances available in the Cloud Stack.
* virtual network appliances available in the Cloud Stack.
*/ */
@Local(value = { VirtualNetworkApplianceManager.class, VirtualNetworkApplianceService.class }) @Local(value = { VirtualNetworkApplianceManager.class, VirtualNetworkApplianceService.class })
public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplianceManager, VirtualNetworkApplianceService, VirtualMachineGuru<DomainRouterVO> { public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplianceManager, VirtualNetworkApplianceService, VirtualMachineGuru<DomainRouterVO> {
@ -283,6 +288,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
int _routerStatsInterval = 300; int _routerStatsInterval = 300;
private ServiceOfferingVO _offering; private ServiceOfferingVO _offering;
private String trafficSentinelHostname;
ScheduledExecutorService _executor; ScheduledExecutorService _executor;
@ -306,7 +312,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
} }
@Override @Override
public boolean destroyRouter(final long routerId) throws ResourceUnavailableException, ConcurrentOperationException{ public boolean destroyRouter(final long routerId) throws ResourceUnavailableException, ConcurrentOperationException {
UserContext context = UserContext.current(); UserContext context = UserContext.current();
User user = _accountMgr.getActiveUser(context.getCallerUserId()); User user = _accountMgr.getActiveUser(context.getCallerUserId());
@ -325,7 +331,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
@Override @Override
@DB @DB
public VirtualRouter upgradeRouter(UpgradeRouterCmd cmd) throws InvalidParameterValueException, PermissionDeniedException { public VirtualRouter upgradeRouter(UpgradeRouterCmd cmd) {
Long routerId = cmd.getId(); Long routerId = cmd.getId();
Long serviceOfferingId = cmd.getServiceOfferingId(); Long serviceOfferingId = cmd.getServiceOfferingId();
Account account = UserContext.current().getCaller(); Account account = UserContext.current().getCaller();
@ -352,14 +358,15 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
// Check that the router is stopped // Check that the router is stopped
if (!router.getState().equals(State.Stopped)) { if (!router.getState().equals(State.Stopped)) {
s_logger.warn("Unable to upgrade router " + router.toString() + " in state " + router.getState()); s_logger.warn("Unable to upgrade router " + router.toString() + " in state " + router.getState());
throw new InvalidParameterValueException("Unable to upgrade router " + router.toString() + " in state " + router.getState() + "; make sure the router is stopped and not in an error state before upgrading."); throw new InvalidParameterValueException("Unable to upgrade router " + router.toString() + " in state " + router.getState()
+ "; make sure the router is stopped and not in an error state before upgrading.");
} }
ServiceOfferingVO currentServiceOffering = _serviceOfferingDao.findById(router.getServiceOfferingId()); ServiceOfferingVO currentServiceOffering = _serviceOfferingDao.findById(router.getServiceOfferingId());
if (currentServiceOffering.getUseLocalStorage() != newServiceOffering.getUseLocalStorage()) { if (currentServiceOffering.getUseLocalStorage() != newServiceOffering.getUseLocalStorage()) {
throw new InvalidParameterValueException("Can't upgrade, due to new local storage status : " + newServiceOffering.getUseLocalStorage() throw new InvalidParameterValueException("Can't upgrade, due to new local storage status : " + newServiceOffering.getUseLocalStorage() + " is different from "
+ " is different from " + "curruent local storage status: " + currentServiceOffering.getUseLocalStorage()); + "curruent local storage status: " + currentServiceOffering.getUseLocalStorage());
} }
router.setServiceOfferingId(serviceOfferingId); router.setServiceOfferingId(serviceOfferingId);
@ -371,9 +378,8 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
} }
@Override @Override
public boolean savePasswordToRouter(Network network, NicProfile nic, VirtualMachineProfile<UserVm> profile) throws ResourceUnavailableException{ public boolean savePasswordToRouter(Network network, NicProfile nic, VirtualMachineProfile<UserVm> profile) throws ResourceUnavailableException {
DomainRouterVO router = _routerDao.findByNetwork(network.getId()); DomainRouterVO router = _routerDao.findByNetwork(network.getId());
if (router == null) { if (router == null) {
s_logger.warn("Unable save password, router doesn't exist in network " + network.getId()); s_logger.warn("Unable save password, router doesn't exist in network " + network.getId());
@ -381,11 +387,11 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
} }
UserVm userVm = profile.getVirtualMachine(); UserVm userVm = profile.getVirtualMachine();
String password = (String)profile.getParameter(Param.VmPassword); String password = (String) profile.getParameter(Param.VmPassword);
String encodedPassword = PasswordGenerator.rot13(password); String encodedPassword = PasswordGenerator.rot13(password);
Commands cmds = new Commands(OnError.Continue); Commands cmds = new Commands(OnError.Continue);
SavePasswordCommand cmd = new SavePasswordCommand(encodedPassword, nic.getIp4Address(), userVm.getName()); SavePasswordCommand cmd = new SavePasswordCommand(encodedPassword, nic.getIp4Address(), userVm.getHostName());
cmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, router.getPrivateIpAddress()); cmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, router.getPrivateIpAddress());
cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName()); cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());
cmds.addCommand("password", cmd); cmds.addCommand("password", cmd);
@ -393,7 +399,6 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
return sendCommandsToRouter(router, cmds); return sendCommandsToRouter(router, cmds);
} }
@Override @Override
public VirtualRouter stopRouter(long routerId, boolean forced) throws ResourceUnavailableException, ConcurrentOperationException { public VirtualRouter stopRouter(long routerId, boolean forced) throws ResourceUnavailableException, ConcurrentOperationException {
UserContext context = UserContext.current(); UserContext context = UserContext.current();
@ -468,24 +473,19 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
} }
/* /*
* final GetVmStatsCommand cmd = new GetVmStatsCommand(router, * final GetVmStatsCommand cmd = new GetVmStatsCommand(router, router.getInstanceName()); final Answer answer =
* router.getInstanceName()); * _agentMgr.easySend(router.getHostId(), cmd); if (answer == null) { return false; }
* final Answer answer = _agentMgr.easySend(router.getHostId(), cmd);
* if (answer == null) {
* return false;
* }
* *
* final GetVmStatsAnswer stats = (GetVmStatsAnswer)answer; * final GetVmStatsAnswer stats = (GetVmStatsAnswer)answer;
* *
* netStats.putAll(stats.getNetworkStats()); * netStats.putAll(stats.getNetworkStats()); diskStats.putAll(stats.getDiskStats());
* diskStats.putAll(stats.getDiskStats());
*/ */
return true; return true;
} }
@Override @Override
public VirtualRouter rebootRouter(long routerId, boolean restartNetwork) throws InvalidParameterValueException, PermissionDeniedException, ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { public VirtualRouter rebootRouter(long routerId, boolean restartNetwork) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException {
Account caller = UserContext.current().getCaller(); Account caller = UserContext.current().getCaller();
// verify parameters // verify parameters
@ -498,7 +498,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
throw new PermissionDeniedException("Unable to reboot domain router with id " + routerId + ". Permission denied"); throw new PermissionDeniedException("Unable to reboot domain router with id " + routerId + ". Permission denied");
} }
//Can reboot domain router only in Running state // Can reboot domain router only in Running state
if (router == null || router.getState() != State.Running) { if (router == null || router.getState() != State.Running) {
s_logger.warn("Unable to reboot, virtual router is not in the right state " + router.getState()); s_logger.warn("Unable to reboot, virtual router is not in the right state " + router.getState());
throw new ResourceUnavailableException("Unable to reboot domR, it is not in right state " + router.getState(), DataCenter.class, router.getDataCenterId()); throw new ResourceUnavailableException("Unable to reboot domR, it is not in right state " + router.getState(), DataCenter.class, router.getDataCenterId());
@ -549,12 +549,14 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
_itMgr.registerGuru(VirtualMachine.Type.DomainRouter, this); _itMgr.registerGuru(VirtualMachine.Type.DomainRouter, this);
boolean useLocalStorage = Boolean.parseBoolean(configs.get(Config.SystemVMUseLocalStorage.key())); boolean useLocalStorage = Boolean.parseBoolean(configs.get(Config.SystemVMUseLocalStorage.key()));
_offering = new ServiceOfferingVO("System Offering For Software Router", 1, _routerRamSize, _routerCpuMHz, 0, 0, true, null, useLocalStorage, true, null, true); _offering = new ServiceOfferingVO("System Offering For Software Router", 1, _routerRamSize, _routerCpuMHz, null, null, true, null, useLocalStorage, true, null, true);
_offering.setUniqueName("Cloud.Com-SoftwareRouter"); _offering.setUniqueName("Cloud.Com-SoftwareRouter");
_offering = _serviceOfferingDao.persistSystemServiceOffering(_offering); _offering = _serviceOfferingDao.persistSystemServiceOffering(_offering);
_systemAcct = _accountService.getSystemAccount(); _systemAcct = _accountService.getSystemAccount();
trafficSentinelHostname = configs.get("traffic.sentinel.hostname");
s_logger.info("DomainRouterManager is configured."); s_logger.info("DomainRouterManager is configured.");
return true; return true;
@ -588,8 +590,8 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
return VirtualMachineName.getRouterId(vmName); return VirtualMachineName.getRouterId(vmName);
} }
private VmDataCommand generateVmDataCommand(DomainRouterVO router, String vmPrivateIpAddress, private VmDataCommand generateVmDataCommand(DomainRouterVO router, String vmPrivateIpAddress, String userData, String serviceOffering, String zoneName, String guestIpAddress, String vmName,
String userData, String serviceOffering, String zoneName, String guestIpAddress, String vmName, String vmInstanceName, long vmId, String publicKey) { String vmInstanceName, long vmId, String publicKey) {
VmDataCommand cmd = new VmDataCommand(vmPrivateIpAddress, vmName); VmDataCommand cmd = new VmDataCommand(vmPrivateIpAddress, vmName);
cmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, router.getPrivateIpAddress()); cmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, router.getPrivateIpAddress());
@ -606,6 +608,14 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
cmd.addVmData("metadata", "vm-id", String.valueOf(vmId)); cmd.addVmData("metadata", "vm-id", String.valueOf(vmId));
cmd.addVmData("metadata", "public-keys", publicKey); cmd.addVmData("metadata", "public-keys", publicKey);
String cloudIdentifier = _configDao.getValue("cloud.identifier");
if (cloudIdentifier == null) {
cloudIdentifier = "";
} else {
cloudIdentifier = "CloudStack-{" + cloudIdentifier + "}";
}
cmd.addVmData("metadata", "cloud-identifier", cloudIdentifier);
return cmd; return cmd;
} }
@ -616,13 +626,74 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
@Override @Override
public void run() { public void run() {
//Direct Network Usage
URL trafficSentinel;
try {
//Query traffic Sentinel
if(trafficSentinelHostname != null){
trafficSentinel = new URL(trafficSentinelHostname+"/inmsf/Query?script=var+q+%3D+Query.topN(%22historytrmx%22,%0D%0A+++++++++++++++++%22ipsource,bytes%22,%0D%0A+++++++++++++++++%22sourcezone+!%3D+EXTERNAL" +
"+%26+destinationzone+%3D+EXTERNAL%22,%0D%0A+++++++++++++++++%22end+-+5+minutes,+end%22,%0D%0A+++++++++++++++++%22bytes%22,%0D%0A+++++++++++++++++100000);%0D%0A%0D%0Avar+totalsSent+%3D+" +
"{};%0D%0A%0D%0Avar+t+%3D+q.run(%0D%0A++function(row,table)+{%0D%0A++++if(row[0])+{++++%0D%0A++++++totalsSent[row[0]]+%3D+row[1];%0D%0A++++}%0D%0A++});%0D%0A%0D%0Avar+totalsRcvd+%3D+{};" +
"%0D%0A%0D%0Avar+q+%3D+Query.topN(%22historytrmx%22,%0D%0A+++++++++++++++++%22ipdestination,bytes%22,%0D%0A+++++++++++++++++%22destinationzone+!%3D+EXTERNAL+%26+sourcezone+%3D+EXTERNAL%22," +
"%0D%0A+++++++++++++++++%22end+-+5minutes,+end%22,%0D%0A+++++++++++++++++%22bytes%22,%0D%0A+++++++++++++++++100000);%0D%0A%0D%0Avar+t+%3D+q.run(%0D%0A++function(row,table)+{%0D%0A++++" +
"if(row[0])+{%0D%0A++++++totalsRcvd[row[0]]+%3D+row[1];%0D%0A++++}%0D%0A++});%0D%0A%0D%0Afor+(var+addr+in+totalsSent)+{%0D%0A++++var+TS+%3D+0;%0D%0A++++var+TR+%3D+0;%0D%0A++++if(totalsSent[addr])" +
"+TS+%3D+totalsSent[addr];%0D%0A++++if(totalsRcvd[addr])+TR+%3D+totalsRcvd[addr];%0D%0A++++println(addr+%2B+%22,%22+%2B+TS+%2B+%22,%22+%2B+TR);%0D%0A}&authenticate=basic&resultFormat=txt");
BufferedReader in = new BufferedReader(
new InputStreamReader(trafficSentinel.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null){
//Parse the script output
StringTokenizer st = new StringTokenizer(inputLine, ",");
if(st.countTokens() == 3){
String publicIp = st.nextToken();
//Find the account owning the IP
IPAddressVO ipaddress = _ipAddressDao.findByIpAddress(publicIp);
if(ipaddress == null || ipaddress.getAccountId() == Account.ACCOUNT_ID_SYSTEM){
continue;
}
Long bytesSent = new Long(st.nextToken());
Long bytesRcvd = new Long(st.nextToken());
if(bytesSent == null || bytesRcvd == null){
s_logger.debug("Incorrect bytes for IP: "+publicIp);
}
Transaction txn = Transaction.open(Transaction.CLOUD_DB);
txn.start();
//update user_statistics
UserStatisticsVO stats = _statsDao.lock(ipaddress.getAccountId(), ipaddress.getDataCenterId(), null, 0L, "DirectNetwork");
if (stats == null) {
stats = new UserStatisticsVO(ipaddress.getAccountId(), ipaddress.getDataCenterId(), null, 0L, "DirectNetwork", null);
stats.setCurrentBytesSent(bytesSent);
stats.setCurrentBytesReceived(bytesRcvd);
_statsDao.persist(stats);
} else {
stats.setCurrentBytesSent(stats.getCurrentBytesSent() + bytesSent);
stats.setCurrentBytesReceived(stats.getCurrentBytesReceived() + bytesRcvd);
_statsDao.update(stats.getId(), stats);
}
txn.commit();
txn.close();
}
}
in.close();
}
} catch (MalformedURLException e1) {
s_logger.info("Invalid T raffic Sentinel URL",e1);
} catch (IOException e) {
s_logger.debug("Error in direct network usage accounting",e);
}
final List<DomainRouterVO> routers = _routerDao.listUpByHostId(null); final List<DomainRouterVO> routers = _routerDao.listUpByHostId(null);
s_logger.debug("Found " + routers.size() + " running routers. "); s_logger.debug("Found " + routers.size() + " running routers. ");
for (DomainRouterVO router : routers) { for (DomainRouterVO router : routers) {
String privateIP = router.getPrivateIpAddress(); String privateIP = router.getPrivateIpAddress();
if (privateIP != null) { if (privateIP != null) {
final NetworkUsageCommand usageCmd = new NetworkUsageCommand(privateIP, router.getName()); final NetworkUsageCommand usageCmd = new NetworkUsageCommand(privateIP, router.getHostName());
final NetworkUsageAnswer answer = (NetworkUsageAnswer) _agentMgr.easySend(router.getHostId(), usageCmd); final NetworkUsageAnswer answer = (NetworkUsageAnswer) _agentMgr.easySend(router.getHostId(), usageCmd);
if (answer != null) { if (answer != null) {
Transaction txn = Transaction.open(Transaction.CLOUD_DB); Transaction txn = Transaction.open(Transaction.CLOUD_DB);
@ -639,16 +710,16 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
} }
if (stats.getCurrentBytesReceived() > answer.getBytesReceived()) { if (stats.getCurrentBytesReceived() > answer.getBytesReceived()) {
if (s_logger.isDebugEnabled()) { if (s_logger.isDebugEnabled()) {
s_logger.debug("Received # of bytes that's less than the last one. Assuming something went wrong and persisting it. Reported: " s_logger.debug("Received # of bytes that's less than the last one. Assuming something went wrong and persisting it. Reported: " + answer.getBytesReceived()
+ answer.getBytesReceived() + " Stored: " + stats.getCurrentBytesReceived()); + " Stored: " + stats.getCurrentBytesReceived());
} }
stats.setNetBytesReceived(stats.getNetBytesReceived() + stats.getCurrentBytesReceived()); stats.setNetBytesReceived(stats.getNetBytesReceived() + stats.getCurrentBytesReceived());
} }
stats.setCurrentBytesReceived(answer.getBytesReceived()); stats.setCurrentBytesReceived(answer.getBytesReceived());
if (stats.getCurrentBytesSent() > answer.getBytesSent()) { if (stats.getCurrentBytesSent() > answer.getBytesSent()) {
if (s_logger.isDebugEnabled()) { if (s_logger.isDebugEnabled()) {
s_logger.debug("Received # of bytes that's less than the last one. Assuming something went wrong and persisting it. Reported: " s_logger.debug("Received # of bytes that's less than the last one. Assuming something went wrong and persisting it. Reported: " + answer.getBytesSent()
+ answer.getBytesSent() + " Stored: " + stats.getCurrentBytesSent()); + " Stored: " + stats.getCurrentBytesSent());
} }
stats.setNetBytesSent(stats.getNetBytesSent() + stats.getCurrentBytesSent()); stats.setNetBytesSent(stats.getNetBytesSent() + stats.getCurrentBytesSent());
} }
@ -657,8 +728,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
txn.commit(); txn.commit();
} catch (Exception e) { } catch (Exception e) {
txn.rollback(); txn.rollback();
s_logger.warn("Unable to update user statistics for account: " + router.getAccountId() + " Rx: " s_logger.warn("Unable to update user statistics for account: " + router.getAccountId() + " Rx: " + answer.getBytesReceived() + "; Tx: " + answer.getBytesSent());
+ answer.getBytesReceived() + "; Tx: " + answer.getBytesSent());
} finally { } finally {
txn.close(); txn.close();
} }
@ -673,6 +743,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
} }
@Override @Override
@DB
public DomainRouterVO deployVirtualRouter(Network guestNetwork, DeployDestination dest, Account owner, Map<Param, Object> params) throws InsufficientCapacityException, public DomainRouterVO deployVirtualRouter(Network guestNetwork, DeployDestination dest, Account owner, Map<Param, Object> params) throws InsufficientCapacityException,
ConcurrentOperationException, ResourceUnavailableException { ConcurrentOperationException, ResourceUnavailableException {
long dcId = dest.getDataCenter().getId(); long dcId = dest.getDataCenter().getId();
@ -681,7 +752,17 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
s_logger.debug("Starting a router for network configurations: virtual=" + guestNetwork + " in " + dest); s_logger.debug("Starting a router for network configurations: virtual=" + guestNetwork + " in " + dest);
} }
assert guestNetwork.getState() == Network.State.Implemented || guestNetwork.getState() == Network.State.Setup || guestNetwork.getState() == Network.State.Implementing: "Network is not yet fully implemented: " // lock guest network
Long guestNetworkId = guestNetwork.getId();
guestNetwork = _networkDao.acquireInLockTable(guestNetworkId);
if (guestNetwork == null) {
throw new ConcurrentOperationException("Unable to acquire network configuration: " + guestNetworkId);
}
try {
assert guestNetwork.getState() == Network.State.Implemented || guestNetwork.getState() == Network.State.Setup || guestNetwork.getState() == Network.State.Implementing : "Network is not yet fully implemented: "
+ guestNetwork; + guestNetwork;
assert guestNetwork.getTrafficType() == TrafficType.Guest; assert guestNetwork.getTrafficType() == TrafficType.Guest;
@ -726,10 +807,10 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
networks.add(new Pair<NetworkVO, NicProfile>((NetworkVO) guestNetwork, gatewayNic)); networks.add(new Pair<NetworkVO, NicProfile>((NetworkVO) guestNetwork, gatewayNic));
networks.add(new Pair<NetworkVO, NicProfile>(controlConfig, null)); networks.add(new Pair<NetworkVO, NicProfile>(controlConfig, null));
/*Before starting router, already know the hypervisor type*/ /* Before starting router, already know the hypervisor type */
VMTemplateVO template = _templateDao.findRoutingTemplate(dest.getCluster().getHypervisorType()); VMTemplateVO template = _templateDao.findRoutingTemplate(dest.getCluster().getHypervisorType());
router = new DomainRouterVO(id, _offering.getId(), VirtualMachineName.getRouterName(id, _instance), template.getId(), router = new DomainRouterVO(id, _offering.getId(), VirtualMachineName.getRouterName(id, _instance), template.getId(), template.getHypervisorType(), template.getGuestOSId(),
template.getHypervisorType(), template.getGuestOSId(), owner.getDomainId(), owner.getId(), guestNetwork.getId(), _offering.getOfferHA()); owner.getDomainId(), owner.getId(), guestNetwork.getId(), _offering.getOfferHA());
router = _itMgr.allocate(router, template, _offering, networks, plan, null, owner); router = _itMgr.allocate(router, template, _offering, networks, plan, null, owner);
} }
@ -742,19 +823,33 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
UserStatisticsVO stats = _userStatsDao.findBy(owner.getId(), dcId, null, router.getId(), router.getType().toString()); UserStatisticsVO stats = _userStatsDao.findBy(owner.getId(), dcId, null, router.getId(), router.getType().toString());
if (stats == null) { if (stats == null) {
if (s_logger.isDebugEnabled()) { if (s_logger.isDebugEnabled()) {
s_logger.debug("Creating user statistics for the account: " + owner.getId() + " Router Id: "+router.getId()); s_logger.debug("Creating user statistics for the account: " + owner.getId() + " Router Id: " + router.getId());
} }
stats = new UserStatisticsVO(owner.getId(), dcId, null, router.getId(), router.getType().toString(), guestNetwork.getId()); stats = new UserStatisticsVO(owner.getId(), dcId, null, router.getId(), router.getType().toString(), guestNetwork.getId());
_userStatsDao.persist(stats); _userStatsDao.persist(stats);
} }
return router; return router;
} finally {
_networkDao.releaseFromLockTable(guestNetworkId);
}
} }
@Override @Override
public DomainRouterVO deployDhcp(Network guestNetwork, DeployDestination dest, Account owner, Map<Param, Object> params) throws InsufficientCapacityException, @DB
StorageUnavailableException, ConcurrentOperationException, ResourceUnavailableException { public DomainRouterVO deployDhcp(Network guestNetwork, DeployDestination dest, Account owner, Map<Param, Object> params) throws InsufficientCapacityException, StorageUnavailableException,
ConcurrentOperationException, ResourceUnavailableException {
long dcId = dest.getDataCenter().getId(); long dcId = dest.getDataCenter().getId();
// lock guest network
Long guestNetworkId = guestNetwork.getId();
guestNetwork = _networkDao.acquireInLockTable(guestNetworkId);
if (guestNetwork == null) {
throw new ConcurrentOperationException("Unable to acquire network configuration: " + guestNetworkId);
}
try {
NetworkOffering offering = _networkOfferingDao.findByIdIncludingRemoved(guestNetwork.getNetworkOfferingId()); NetworkOffering offering = _networkOfferingDao.findByIdIncludingRemoved(guestNetwork.getNetworkOfferingId());
if (offering.isSystemOnly() || guestNetwork.getIsShared()) { if (offering.isSystemOnly() || guestNetwork.getIsShared()) {
owner = _accountMgr.getAccount(Account.ACCOUNT_ID_SYSTEM); owner = _accountMgr.getAccount(Account.ACCOUNT_ID_SYSTEM);
@ -766,16 +861,18 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
assert guestNetwork.getState() == Network.State.Implemented || guestNetwork.getState() == Network.State.Setup || guestNetwork.getState() == Network.State.Implementing : "Network is not yet fully implemented: " assert guestNetwork.getState() == Network.State.Implemented || guestNetwork.getState() == Network.State.Setup || guestNetwork.getState() == Network.State.Implementing : "Network is not yet fully implemented: "
+ guestNetwork; + guestNetwork;
DataCenterDeployment plan = new DataCenterDeployment(dcId); DataCenterDeployment plan = null;
DataCenter dc = _dcDao.findById(dcId); DataCenter dc = _dcDao.findById(dcId);
DomainRouterVO router = null; DomainRouterVO router = null;
Long podId = dest.getPod().getId(); Long podId = dest.getPod().getId();
//In Basic zone and Guest network we have to start domR per pod, not per network // In Basic zone and Guest network we have to start domR per pod, not per network
if ((dc.getNetworkType() == NetworkType.Basic || guestNetwork.isSecurityGroupEnabled()) && guestNetwork.getTrafficType() == TrafficType.Guest ) { if ((dc.getNetworkType() == NetworkType.Basic || guestNetwork.isSecurityGroupEnabled()) && guestNetwork.getTrafficType() == TrafficType.Guest) {
router = _routerDao.findByNetworkAndPod(guestNetwork.getId(), podId); router = _routerDao.findByNetworkAndPod(guestNetwork.getId(), podId);
plan = new DataCenterDeployment(dcId, podId, null, null, null);
} else { } else {
router = _routerDao.findByNetwork(guestNetwork.getId()); router = _routerDao.findByNetwork(guestNetwork.getId());
plan = new DataCenterDeployment(dcId);
} }
if (router == null) { if (router == null) {
@ -794,14 +891,15 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
networks.add(new Pair<NetworkVO, NicProfile>((NetworkVO) guestNetwork, gatewayNic)); networks.add(new Pair<NetworkVO, NicProfile>((NetworkVO) guestNetwork, gatewayNic));
networks.add(new Pair<NetworkVO, NicProfile>(controlConfig, null)); networks.add(new Pair<NetworkVO, NicProfile>(controlConfig, null));
/*Before starting router, already know the hypervisor type*/ /* Before starting router, already know the hypervisor type */
VMTemplateVO template = _templateDao.findRoutingTemplate(dest.getCluster().getHypervisorType()); VMTemplateVO template = _templateDao.findRoutingTemplate(dest.getCluster().getHypervisorType());
router = new DomainRouterVO(id, _offering.getId(), VirtualMachineName.getRouterName(id, _instance), template.getId(), router = new DomainRouterVO(id, _offering.getId(), VirtualMachineName.getRouterName(id, _instance), template.getId(), template.getHypervisorType(), template.getGuestOSId(),
template.getHypervisorType(), template.getGuestOSId(), owner.getDomainId(), owner.getId(), guestNetwork.getId(), _offering.getOfferHA()); owner.getDomainId(), owner.getId(), guestNetwork.getId(), _offering.getOfferHA());
router.setRole(Role.DHCP_USERDATA); router.setRole(Role.DHCP_USERDATA);
router = _itMgr.allocate(router, template, _offering, networks, plan, null, owner); router = _itMgr.allocate(router, template, _offering, networks, plan, null, owner);
} }
State state = router.getState(); State state = router.getState();
if (state != State.Running) { if (state != State.Running) {
router = this.start(router, _accountService.getSystemUser(), _accountService.getSystemAccount(), params); router = this.start(router, _accountService.getSystemUser(), _accountService.getSystemAccount(), params);
@ -810,13 +908,16 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
UserStatisticsVO stats = _userStatsDao.findBy(owner.getId(), dcId, null, router.getId(), router.getType().toString()); UserStatisticsVO stats = _userStatsDao.findBy(owner.getId(), dcId, null, router.getId(), router.getType().toString());
if (stats == null) { if (stats == null) {
if (s_logger.isDebugEnabled()) { if (s_logger.isDebugEnabled()) {
s_logger.debug("Creating user statistics for the account: " + owner.getId() + " Router Id: "+router.getId()); s_logger.debug("Creating user statistics for the account: " + owner.getId() + " Router Id: " + router.getId());
} }
stats = new UserStatisticsVO(owner.getId(), dcId, null, router.getId(), router.getType().toString(), guestNetwork.getId()); stats = new UserStatisticsVO(owner.getId(), dcId, null, router.getId(), router.getType().toString(), guestNetwork.getId());
_userStatsDao.persist(stats); _userStatsDao.persist(stats);
} }
return router; return router;
} finally {
_networkDao.releaseFromLockTable(guestNetworkId);
}
} }
@Override @Override
@ -873,26 +974,32 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
// DOMR control command is sent over management server in VMware // DOMR control command is sent over management server in VMware
if (dest.getHost().getHypervisorType() == HypervisorType.VMware) { if (dest.getHost().getHypervisorType() == HypervisorType.VMware) {
if(s_logger.isInfoEnabled()) { if (s_logger.isInfoEnabled()) {
s_logger.info("Check if we need to add management server explicit route to DomR. pod cidr: " + dest.getPod().getCidrAddress() + "/" + dest.getPod().getCidrSize() s_logger.info("Check if we need to add management server explicit route to DomR. pod cidr: " + dest.getPod().getCidrAddress() + "/" + dest.getPod().getCidrSize()
+ ", pod gateway: " + dest.getPod().getGateway() + ", management host: " + _mgmt_host); + ", pod gateway: " + dest.getPod().getGateway() + ", management host: " + _mgmt_host);
} }
if(!NetUtils.sameSubnetCIDR(_mgmt_host, dest.getPod().getGateway(), dest.getPod().getCidrSize())) { if (s_logger.isInfoEnabled()) {
if(s_logger.isInfoEnabled()) {
s_logger.info("Add management server explicit route to DomR."); s_logger.info("Add management server explicit route to DomR.");
} }
// always add management explicit route, for basic networking setup, DomR may have two interfaces while both
// are on the same subnet
_mgmt_cidr = _configDao.getValue(Config.ManagementNetwork.key()); _mgmt_cidr = _configDao.getValue(Config.ManagementNetwork.key());
if (NetUtils.isValidCIDR(_mgmt_cidr)) { if (NetUtils.isValidCIDR(_mgmt_cidr)) {
buf.append(" mgmtcidr=").append(_mgmt_cidr); buf.append(" mgmtcidr=").append(_mgmt_cidr);
buf.append(" localgw=").append(dest.getPod().getGateway()); buf.append(" localgw=").append(dest.getPod().getGateway());
} }
} else {
if(s_logger.isInfoEnabled()) { /*
s_logger.info("Management server host is at same subnet at pod private network, don't add explict route to DomR"); * if(!NetUtils.sameSubnetCIDR(_mgmt_host, dest.getPod().getGateway(), dest.getPod().getCidrSize())) {
} * if(s_logger.isInfoEnabled()) { s_logger.info("Add management server explicit route to DomR."); }
} *
* _mgmt_cidr = _configDao.getValue(Config.ManagementNetwork.key()); if (NetUtils.isValidCIDR(_mgmt_cidr)) {
* buf.append(" mgmtcidr=").append(_mgmt_cidr); buf.append(" localgw=").append(dest.getPod().getGateway());
* } } else { if(s_logger.isInfoEnabled()) {
* s_logger.info("Management server host is at same subnet at pod private network"); } }
*/
} }
controlNic = nic; controlNic = nic;
@ -937,7 +1044,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
} }
@Override @Override
public boolean finalizeDeployment(Commands cmds, VirtualMachineProfile<DomainRouterVO> profile, DeployDestination dest, ReservationContext context) throws ResourceUnavailableException{ public boolean finalizeDeployment(Commands cmds, VirtualMachineProfile<DomainRouterVO> profile, DeployDestination dest, ReservationContext context) throws ResourceUnavailableException {
DomainRouterVO router = profile.getVirtualMachine(); DomainRouterVO router = profile.getVirtualMachine();
List<NicProfile> nics = profile.getNics(); List<NicProfile> nics = profile.getNics();
@ -977,24 +1084,23 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
cmds.addCommand("checkSsh", new CheckSshCommand(profile.getInstanceName(), controlNic.getIp4Address(), 3922, 5, 20)); cmds.addCommand("checkSsh", new CheckSshCommand(profile.getInstanceName(), controlNic.getIp4Address(), 3922, 5, 20));
//restart network if restartNetwork = false is not specified in profile parameters // restart network if restartNetwork = false is not specified in profile parameters
boolean restartNetwork = true; boolean restartNetwork = true;
if (profile.getParameter(Param.RestartNetwork) != null && (Boolean)profile.getParameter(Param.RestartNetwork) == false) { if (profile.getParameter(Param.RestartNetwork) != null && (Boolean) profile.getParameter(Param.RestartNetwork) == false) {
restartNetwork = false; restartNetwork = false;
} }
//The commands should be sent for domR only, skip for DHCP // The commands should be sent for domR only, skip for DHCP
if (router.getRole() == VirtualRouter.Role.DHCP_FIREWALL_LB_PASSWD_USERDATA && restartNetwork) { if (router.getRole() == VirtualRouter.Role.DHCP_FIREWALL_LB_PASSWD_USERDATA && restartNetwork) {
s_logger.debug("Resending ipAssoc, port forwarding, load balancing rules as a part of Virtual router start"); s_logger.debug("Resending ipAssoc, port forwarding, load balancing rules as a part of Virtual router start");
long networkId = router.getNetworkId(); long networkId = router.getNetworkId();
long ownerId = router.getAccountId(); long ownerId = router.getAccountId();
long zoneId = router.getDataCenterId(); long zoneId = router.getDataCenterId();
final List<IPAddressVO> userIps = _networkMgr.listPublicIpAddressesInVirtualNetwork(ownerId, zoneId, null, null); final List<IPAddressVO> userIps = _networkMgr.listPublicIpAddressesInVirtualNetwork(ownerId, zoneId, null, null);
List<PublicIpAddress> publicIps = new ArrayList<PublicIpAddress>(); List<PublicIpAddress> publicIps = new ArrayList<PublicIpAddress>();
if (userIps != null && !userIps.isEmpty()) { if (userIps != null && !userIps.isEmpty()) {
for (IPAddressVO userIp : userIps) { for (IPAddressVO userIp : userIps) {
PublicIp publicIp = new PublicIp(userIp, _vlanDao.findById(userIp.getVlanId()), userIp.getMacAddress()); PublicIp publicIp = new PublicIp(userIp, _vlanDao.findById(userIp.getVlanId()), NetUtils.createSequenceBasedMacAddress(userIp.getMacAddress()));
publicIps.add(publicIp); publicIps.add(publicIp);
} }
} }
@ -1003,7 +1109,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
if (!publicIps.isEmpty()) { if (!publicIps.isEmpty()) {
//Re-apply public ip addresses - should come before PF/LB/VPN // Re-apply public ip addresses - should come before PF/LB/VPN
createAssociateIPCommands(router, publicIps, cmds, 0); createAssociateIPCommands(router, publicIps, cmds, 0);
List<RemoteAccessVpn> vpns = new ArrayList<RemoteAccessVpn>(); List<RemoteAccessVpn> vpns = new ArrayList<RemoteAccessVpn>();
@ -1020,13 +1126,13 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
} }
} }
//Re-apply port forwarding rules // Re-apply port forwarding rules
s_logger.debug("Found " + pfRules.size() + " port forwarding rule(s) to apply as a part of domR " + router + " start."); s_logger.debug("Found " + pfRules.size() + " port forwarding rule(s) to apply as a part of domR " + router + " start.");
if (!pfRules.isEmpty()) { if (!pfRules.isEmpty()) {
createApplyPortForwardingRulesCommands(pfRules, router, cmds); createApplyPortForwardingRulesCommands(pfRules, router, cmds);
} }
//Re-apply static nat rules // Re-apply static nat rules
s_logger.debug("Found " + staticNatFirewallRules.size() + " static nat rule(s) to apply as a part of domR " + router + " start."); s_logger.debug("Found " + staticNatFirewallRules.size() + " static nat rule(s) to apply as a part of domR " + router + " start.");
if (!staticNatFirewallRules.isEmpty()) { if (!staticNatFirewallRules.isEmpty()) {
List<StaticNatRule> staticNatRules = new ArrayList<StaticNatRule>(); List<StaticNatRule> staticNatRules = new ArrayList<StaticNatRule>();
@ -1036,7 +1142,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
createApplyStaticNatRulesCommands(staticNatRules, router, cmds); createApplyStaticNatRulesCommands(staticNatRules, router, cmds);
} }
//Re-apply vpn rules // Re-apply vpn rules
s_logger.debug("Found " + vpns.size() + " vpn(s) to apply as a part of domR " + router + " start."); s_logger.debug("Found " + vpns.size() + " vpn(s) to apply as a part of domR " + router + " start.");
if (!vpns.isEmpty()) { if (!vpns.isEmpty()) {
for (RemoteAccessVpn vpn : vpns) { for (RemoteAccessVpn vpn : vpns) {
@ -1044,7 +1150,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
} }
} }
//Re-apply load balancing rules // Re-apply load balancing rules
List<LoadBalancerVO> lbs = _loadBalancerDao.listByNetworkId(networkId); List<LoadBalancerVO> lbs = _loadBalancerDao.listByNetworkId(networkId);
List<LoadBalancingRule> lbRules = new ArrayList<LoadBalancingRule>(); List<LoadBalancingRule> lbRules = new ArrayList<LoadBalancingRule>();
for (LoadBalancerVO lb : lbs) { for (LoadBalancerVO lb : lbs) {
@ -1060,15 +1166,15 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
} }
} }
//Resend dhcp // Resend dhcp
s_logger.debug("Reapplying dhcp entries as a part of domR " + router + " start..."); s_logger.debug("Reapplying dhcp entries as a part of domR " + router + " start...");
createDhcpEntriesCommands(router, cmds); createDhcpEntriesCommands(router, cmds);
//Resend user data // Resend user data
s_logger.debug("Reapplying vm data (userData and metaData) entries as a part of domR " + router + " start..."); s_logger.debug("Reapplying vm data (userData and metaData) entries as a part of domR " + router + " start...");
createVmDataCommands(router, cmds); createVmDataCommands(router, cmds);
// Network usage command to create iptables rules // Network usage command to create iptables rules
cmds.addCommand("networkUsage", new NetworkUsageCommand(controlNic.getIp4Address(), router.getName(), "create")); cmds.addCommand("networkUsage", new NetworkUsageCommand(controlNic.getIp4Address(), router.getHostName(), "create"));
return true; return true;
} }
@ -1103,11 +1209,11 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
DomainRouterVO router = _routerDao.findByNetwork(network.getId()); DomainRouterVO router = _routerDao.findByNetwork(network.getId());
if (router == null) { if (router == null) {
s_logger.warn("Failed to start remote access VPN: no router found for account and zone"); s_logger.warn("Failed to start remote access VPN: no router found for account and zone");
throw new ResourceUnavailableException("Unable to apply lb rules", DataCenter.class, network.getDataCenterId()); throw new ResourceUnavailableException("Failed to start remote access VPN: no router found for account and zone", DataCenter.class, network.getDataCenterId());
} }
if (router.getState() != State.Running) { if (router.getState() != State.Running) {
s_logger.warn("Failed to start remote access VPN: router not in running state"); s_logger.warn("Failed to start remote access VPN: router not in right state " + router.getState());
throw new ResourceUnavailableException("Unable to assign ip addresses, domR is not in right state " + router.getState(), DataCenter.class, network.getDataCenterId()); throw new ResourceUnavailableException("Failed to start remote access VPN: router not in right state " + router.getState(), DataCenter.class, network.getDataCenterId());
} }
Commands cmds = new Commands(OnError.Stop); Commands cmds = new Commands(OnError.Stop);
@ -1122,32 +1228,31 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
} }
Answer answer = cmds.getAnswer("users"); Answer answer = cmds.getAnswer("users");
if (!answer.getResult()) { if (!answer.getResult()) {
s_logger.error("Unable to start vpn: unable add users to vpn in zone " + router.getDataCenterId() + " for account " + vpn.getAccountId() s_logger.error("Unable to start vpn: unable add users to vpn in zone " + router.getDataCenterId() + " for account " + vpn.getAccountId() + " on domR: " + router.getInstanceName()
+ " on domR: " + router.getInstanceName() + " due to " + answer.getDetails()); + " due to " + answer.getDetails());
throw new ResourceUnavailableException("Unable to start vpn: Unable to add users to vpn in zone " + router.getDataCenterId() + " for account " throw new ResourceUnavailableException("Unable to start vpn: Unable to add users to vpn in zone " + router.getDataCenterId() + " for account " + vpn.getAccountId() + " on domR: "
+ vpn.getAccountId() + " on domR: " + router.getInstanceName() + " due to " + answer.getDetails(), DataCenter.class, + router.getInstanceName() + " due to " + answer.getDetails(), DataCenter.class, router.getDataCenterId());
router.getDataCenterId());
} }
answer = cmds.getAnswer("startVpn"); answer = cmds.getAnswer("startVpn");
if (!answer.getResult()) { if (!answer.getResult()) {
s_logger.error("Unable to start vpn in zone " + router.getDataCenterId() + " for account " + vpn.getAccountId() + " on domR: " s_logger.error("Unable to start vpn in zone " + router.getDataCenterId() + " for account " + vpn.getAccountId() + " on domR: " + router.getInstanceName() + " due to "
+ router.getInstanceName() + " due to " + answer.getDetails()); + answer.getDetails());
throw new ResourceUnavailableException("Unable to start vpn in zone " + router.getDataCenterId() + " for account " + vpn.getAccountId() throw new ResourceUnavailableException("Unable to start vpn in zone " + router.getDataCenterId() + " for account " + vpn.getAccountId() + " on domR: " + router.getInstanceName()
+ " on domR: " + router.getInstanceName() + " due to " + answer.getDetails(), DataCenter.class, router.getDataCenterId()); + " due to " + answer.getDetails(), DataCenter.class, router.getDataCenterId());
} }
return true; return true;
} }
@Override @Override
public boolean deleteRemoteAccessVpn(Network network, RemoteAccessVpn vpn) throws ResourceUnavailableException{ public boolean deleteRemoteAccessVpn(Network network, RemoteAccessVpn vpn) throws ResourceUnavailableException {
DomainRouterVO router = getRouter(vpn.getAccountId(), network.getDataCenterId()); DomainRouterVO router = getRouter(vpn.getAccountId(), network.getDataCenterId());
if (router == null) { if (router == null) {
s_logger.warn("Failed to delete remote access VPN: no router found for account and zone"); s_logger.warn("Failed to delete remote access VPN: no router found for account and zone");
throw new ResourceUnavailableException("Unable to apply lb rules", DataCenter.class, network.getDataCenterId()); throw new ResourceUnavailableException("Failed to delete remote access VPN", DataCenter.class, network.getDataCenterId());
} }
if (router.getState() != State.Running) { if (router.getState() != State.Running) {
s_logger.warn("Failed to delete remote access VPN: router not in running state"); s_logger.warn("Failed to delete remote access VPN: domR is not in right state " + router.getState());
throw new ResourceUnavailableException("Failed to delete remote access VPN: domR is not in right state " + router.getState(), DataCenter.class, network.getDataCenterId()); throw new ResourceUnavailableException("Failed to delete remote access VPN: domR is not in right state " + router.getState(), DataCenter.class, network.getDataCenterId());
} }
Commands cmds = new Commands(OnError.Continue); Commands cmds = new Commands(OnError.Continue);
@ -1175,7 +1280,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
public DomainRouterVO stop(VirtualRouter router, boolean forced, User user, Account caller) throws ConcurrentOperationException, ResourceUnavailableException { public DomainRouterVO stop(VirtualRouter router, boolean forced, User user, Account caller) throws ConcurrentOperationException, ResourceUnavailableException {
s_logger.debug("Stopping router " + router); s_logger.debug("Stopping router " + router);
try { try {
if (_itMgr.advanceStop((DomainRouterVO)router, forced, user, caller)) { if (_itMgr.advanceStop((DomainRouterVO) router, forced, user, caller)) {
return _routerDao.findById(router.getId()); return _routerDao.findById(router.getId());
} else { } else {
return null; return null;
@ -1185,16 +1290,15 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
} }
} }
@Override @Override
public VirtualRouter addVirtualMachineIntoNetwork(Network network, NicProfile nic, VirtualMachineProfile<UserVm> profile, DeployDestination dest, public VirtualRouter addVirtualMachineIntoNetwork(Network network, NicProfile nic, VirtualMachineProfile<UserVm> profile, DeployDestination dest, ReservationContext context, Boolean startDhcp)
ReservationContext context, Boolean startDhcp) throws ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException { throws ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException {
DomainRouterVO router = startDhcp ? deployDhcp(network, dest, profile.getOwner(), profile.getParameters()) : deployVirtualRouter(network, dest, profile.getOwner(), profile.getParameters()); DomainRouterVO router = startDhcp ? deployDhcp(network, dest, profile.getOwner(), profile.getParameters()) : deployVirtualRouter(network, dest, profile.getOwner(), profile.getParameters());
_userVmDao.loadDetails((UserVmVO) profile.getVirtualMachine()); _userVmDao.loadDetails((UserVmVO) profile.getVirtualMachine());
String password = (String)profile.getParameter(VirtualMachineProfile.Param.VmPassword); String password = (String) profile.getParameter(VirtualMachineProfile.Param.VmPassword);
String userData = profile.getVirtualMachine().getUserData(); String userData = profile.getVirtualMachine().getUserData();
String sshPublicKey = profile.getVirtualMachine().getDetail("SSH.PublicKey"); String sshPublicKey = profile.getVirtualMachine().getDetail("SSH.PublicKey");
Commands cmds = new Commands(OnError.Stop); Commands cmds = new Commands(OnError.Stop);
@ -1208,16 +1312,15 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
} }
} }
DhcpEntryCommand dhcpCommand = new DhcpEntryCommand(nic.getMacAddress(), nic.getIp4Address(), profile.getVirtualMachine() DhcpEntryCommand dhcpCommand = new DhcpEntryCommand(nic.getMacAddress(), nic.getIp4Address(), profile.getVirtualMachine().getHostName());
.getName());
dhcpCommand.setAccessDetail(NetworkElementCommand.ROUTER_IP, routerControlIpAddress); dhcpCommand.setAccessDetail(NetworkElementCommand.ROUTER_IP, routerControlIpAddress);
dhcpCommand.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName()); dhcpCommand.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());
cmds.addCommand("dhcp", dhcpCommand); cmds.addCommand("dhcp", dhcpCommand);
//password should be set only on default network element // password should be set only on default network element
if (password != null && network.isDefault()) { if (password != null && network.isDefault()) {
final String encodedPassword = PasswordGenerator.rot13(password); final String encodedPassword = PasswordGenerator.rot13(password);
SavePasswordCommand cmd = new SavePasswordCommand(encodedPassword, nic.getIp4Address(), profile.getVirtualMachine().getName()); SavePasswordCommand cmd = new SavePasswordCommand(encodedPassword, nic.getIp4Address(), profile.getVirtualMachine().getHostName());
cmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, router.getPrivateIpAddress()); cmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, router.getPrivateIpAddress());
cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName()); cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());
cmds.addCommand("password", cmd); cmds.addCommand("password", cmd);
@ -1228,8 +1331,8 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
cmds.addCommand( cmds.addCommand(
"vmdata", "vmdata",
generateVmDataCommand(router, nic.getIp4Address(), userData, serviceOffering, zoneName, generateVmDataCommand(router, nic.getIp4Address(), userData, serviceOffering, zoneName, nic.getIp4Address(), profile.getVirtualMachine().getHostName(), profile.getVirtualMachine()
nic.getIp4Address(), profile.getVirtualMachine().getName(), profile.getVirtualMachine().getInstanceName(), profile.getId(), sshPublicKey)); .getInstanceName(), profile.getId(), sshPublicKey));
try { try {
_agentMgr.send(router.getHostId(), cmds); _agentMgr.send(router.getHostId(), cmds);
@ -1239,9 +1342,8 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
Answer answer = cmds.getAnswer("dhcp"); Answer answer = cmds.getAnswer("dhcp");
if (!answer.getResult()) { if (!answer.getResult()) {
s_logger.error("Unable to set dhcp entry for " + profile + " on domR: " + router.getName() + " due to " + answer.getDetails()); s_logger.error("Unable to set dhcp entry for " + profile + " on domR: " + router.getHostName() + " due to " + answer.getDetails());
throw new ResourceUnavailableException("Unable to set dhcp entry for " + profile + " due to " + answer.getDetails(), DataCenter.class, throw new ResourceUnavailableException("Unable to set dhcp entry for " + profile + " due to " + answer.getDetails(), DataCenter.class, router.getDataCenterId());
router.getDataCenterId());
} }
answer = cmds.getAnswer("password"); answer = cmds.getAnswer("password");
@ -1264,7 +1366,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
} }
@Override @Override
public String[] applyVpnUsers(Network network, List<? extends VpnUser> users) throws ResourceUnavailableException{ public String[] applyVpnUsers(Network network, List<? extends VpnUser> users) throws ResourceUnavailableException {
DomainRouterVO router = _routerDao.findByNetwork(network.getId()); DomainRouterVO router = _routerDao.findByNetwork(network.getId());
if (router == null) { if (router == null) {
s_logger.warn("Failed to add/remove VPN users: no router found for account and zone"); s_logger.warn("Failed to add/remove VPN users: no router found for account and zone");
@ -1278,7 +1380,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
Commands cmds = new Commands(OnError.Continue); Commands cmds = new Commands(OnError.Continue);
List<VpnUser> addUsers = new ArrayList<VpnUser>(); List<VpnUser> addUsers = new ArrayList<VpnUser>();
List<VpnUser> removeUsers = new ArrayList<VpnUser>(); List<VpnUser> removeUsers = new ArrayList<VpnUser>();
for (VpnUser user: users) { for (VpnUser user : users) {
if (user.getState() == VpnUser.State.Add || user.getState() == VpnUser.State.Active) { if (user.getState() == VpnUser.State.Add || user.getState() == VpnUser.State.Active) {
addUsers.add(user); addUsers.add(user);
} else if (user.getState() == VpnUser.State.Revoke) { } else if (user.getState() == VpnUser.State.Revoke) {
@ -1291,8 +1393,10 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName()); cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());
cmds.addCommand(cmd); cmds.addCommand(cmd);
//Currently we receive just one answer from the agent. In the future we have to parse individual answers and set results accordingly // Currently we receive just one answer from the agent. In the future we have to parse individual answers and set
boolean agentResult = sendCommandsToRouter(router, cmds);; // results accordingly
boolean agentResult = sendCommandsToRouter(router, cmds);
;
String[] result = new String[users.size()]; String[] result = new String[users.size()];
for (int i = 0; i < result.length; i++) { for (int i = 0; i < result.length; i++) {
if (agentResult) { if (agentResult) {
@ -1333,7 +1437,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
Account owner = _accountMgr.getAccount(router.getAccountId()); Account owner = _accountMgr.getAccount(router.getAccountId());
//Check if all networks are implemented for the domR; if not - implement them // Check if all networks are implemented for the domR; if not - implement them
DataCenter dc = _dcDao.findById(router.getDataCenterId()); DataCenter dc = _dcDao.findById(router.getDataCenterId());
HostPodVO pod = _podDao.findById(router.getPodId()); HostPodVO pod = _podDao.findById(router.getPodId());
DeployDestination dest = new DeployDestination(dc, pod, null, null); DeployDestination dest = new DeployDestination(dc, pod, null, null);
@ -1361,9 +1465,9 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
private void createAssociateIPCommands(final DomainRouterVO router, final List<? extends PublicIpAddress> ips, Commands cmds, long vmId) { private void createAssociateIPCommands(final DomainRouterVO router, final List<? extends PublicIpAddress> ips, Commands cmds, long vmId) {
//Ensure that in multiple vlans case we first send all ip addresses of vlan1, then all ip addresses of vlan2, etc.. // Ensure that in multiple vlans case we first send all ip addresses of vlan1, then all ip addresses of vlan2, etc..
Map<String, ArrayList<PublicIpAddress>> vlanIpMap = new HashMap<String, ArrayList<PublicIpAddress>>(); Map<String, ArrayList<PublicIpAddress>> vlanIpMap = new HashMap<String, ArrayList<PublicIpAddress>>();
for (final PublicIpAddress ipAddress: ips) { for (final PublicIpAddress ipAddress : ips) {
String vlanTag = ipAddress.getVlanTag(); String vlanTag = ipAddress.getVlanTag();
ArrayList<PublicIpAddress> ipList = vlanIpMap.get(vlanTag); ArrayList<PublicIpAddress> ipList = vlanIpMap.get(vlanTag);
if (ipList == null) { if (ipList == null) {
@ -1373,21 +1477,22 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
vlanIpMap.put(vlanTag, ipList); vlanIpMap.put(vlanTag, ipList);
} }
for (Map.Entry<String, ArrayList<PublicIpAddress>> vlanAndIp: vlanIpMap.entrySet()) { for (Map.Entry<String, ArrayList<PublicIpAddress>> vlanAndIp : vlanIpMap.entrySet()) {
List<PublicIpAddress> ipAddrList = vlanAndIp.getValue(); List<PublicIpAddress> ipAddrList = vlanAndIp.getValue();
//Source nat ip address should always be sent first // Source nat ip address should always be sent first
Collections.sort(ipAddrList, new Comparator<PublicIpAddress>() { Collections.sort(ipAddrList, new Comparator<PublicIpAddress>() {
@Override @Override
public int compare(PublicIpAddress o1, PublicIpAddress o2) { public int compare(PublicIpAddress o1, PublicIpAddress o2) {
boolean s1 = o1.isSourceNat(); boolean s1 = o1.isSourceNat();
boolean s2 = o2.isSourceNat(); boolean s2 = o2.isSourceNat();
return (s1 ^ s2) ? ((s1 ^ true) ? 1 : -1) : 0; return (s1 ^ s2) ? ((s1 ^ true) ? 1 : -1) : 0;
} }); }
});
IpAddressTO[] ipsToSend = new IpAddressTO[ipAddrList.size()]; IpAddressTO[] ipsToSend = new IpAddressTO[ipAddrList.size()];
int i = 0; int i = 0;
boolean firstIP = true; boolean firstIP = true;
for (final PublicIpAddress ipAddr: ipAddrList) { for (final PublicIpAddress ipAddr : ipAddrList) {
boolean add = (ipAddr.getState() == IpAddress.State.Releasing ? false : true); boolean add = (ipAddr.getState() == IpAddress.State.Releasing ? false : true);
boolean sourceNat = ipAddr.isSourceNat(); boolean sourceNat = ipAddr.isSourceNat();
@ -1398,10 +1503,8 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
String vmGuestAddress = null; String vmGuestAddress = null;
//Get network rate - required for IpAssoc // Get network rate - required for IpAssoc
Network network = _networkMgr.getNetwork(ipAddr.getNetworkId()); Integer networkRate = _networkMgr.getNetworkRate(ipAddr.getNetworkId(), null);
NetworkOffering no = _configMgr.getNetworkOffering(network.getNetworkOfferingId());
Integer networkRate = _configMgr.getNetworkRate(no.getId());
IpAddressTO ip = new IpAddressTO(ipAddr.getAddress().addr(), add, firstIP, sourceNat, vlanId, vlanGateway, vlanNetmask, vifMacAddress, vmGuestAddress, networkRate); IpAddressTO ip = new IpAddressTO(ipAddr.getAddress().addr(), add, firstIP, sourceNat, vlanId, vlanGateway, vlanNetmask, vifMacAddress, vmGuestAddress, networkRate);
ipsToSend[i++] = ip; ipsToSend[i++] = ip;
@ -1475,7 +1578,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
List<VpnUserVO> vpnUsers = _vpnUsersDao.listByAccount(vpn.getAccountId()); List<VpnUserVO> vpnUsers = _vpnUsersDao.listByAccount(vpn.getAccountId());
List<VpnUser> addUsers = new ArrayList<VpnUser>(); List<VpnUser> addUsers = new ArrayList<VpnUser>();
List<VpnUser> removeUsers = new ArrayList<VpnUser>(); List<VpnUser> removeUsers = new ArrayList<VpnUser>();
for (VpnUser user: vpnUsers) { for (VpnUser user : vpnUsers) {
if (user.getState() == VpnUser.State.Add) { if (user.getState() == VpnUser.State.Add) {
addUsers.add(user); addUsers.add(user);
} else if (user.getState() == VpnUser.State.Revoke) { } else if (user.getState() == VpnUser.State.Revoke) {
@ -1489,8 +1592,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
IpAddress ip = _networkMgr.getIp(vpn.getServerAddressId()); IpAddress ip = _networkMgr.getIp(vpn.getServerAddressId());
RemoteAccessVpnCfgCommand startVpnCmd = new RemoteAccessVpnCfgCommand(true, ip.getAddress().addr(), RemoteAccessVpnCfgCommand startVpnCmd = new RemoteAccessVpnCfgCommand(true, ip.getAddress().addr(), vpn.getLocalIp(), vpn.getIpRange(), vpn.getIpsecPresharedKey());
vpn.getLocalIp(), vpn.getIpRange(), vpn.getIpsecPresharedKey());
startVpnCmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, router.getPrivateIpAddress()); startVpnCmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, router.getPrivateIpAddress());
startVpnCmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName()); startVpnCmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());
@ -1498,7 +1600,6 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
cmds.addCommand("startVpn", startVpnCmd); cmds.addCommand("startVpn", startVpnCmd);
} }
private void createVmDataCommands(DomainRouterVO router, Commands cmds) { private void createVmDataCommands(DomainRouterVO router, Commands cmds) {
long networkId = router.getNetworkId(); long networkId = router.getNetworkId();
List<UserVmVO> vms = _userVmDao.listByNetworkId(networkId); List<UserVmVO> vms = _userVmDao.listByNetworkId(networkId);
@ -1509,10 +1610,8 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
s_logger.debug("Creating user data entry for vm " + vm + " on domR " + router); s_logger.debug("Creating user data entry for vm " + vm + " on domR " + router);
String serviceOffering = _serviceOfferingDao.findByIdIncludingRemoved(vm.getServiceOfferingId()).getDisplayText(); String serviceOffering = _serviceOfferingDao.findByIdIncludingRemoved(vm.getServiceOfferingId()).getDisplayText();
String zoneName = _dcDao.findById(router.getDataCenterId()).getName(); String zoneName = _dcDao.findById(router.getDataCenterId()).getName();
cmds.addCommand( cmds.addCommand("vmdata",
"vmdata", generateVmDataCommand(router, nic.getIp4Address(), vm.getUserData(), serviceOffering, zoneName, nic.getIp4Address(), vm.getHostName(), vm.getInstanceName(), vm.getId(), null));
generateVmDataCommand(router, nic.getIp4Address(), vm.getUserData(), serviceOffering, zoneName,
nic.getIp4Address(), vm.getName(), vm.getInstanceName(), vm.getId(), null));
} }
} }
} }
@ -1521,13 +1620,14 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
private void createDhcpEntriesCommands(DomainRouterVO router, Commands cmds) { private void createDhcpEntriesCommands(DomainRouterVO router, Commands cmds) {
long networkId = router.getNetworkId(); long networkId = router.getNetworkId();
List<UserVmVO> vms = _userVmDao.listByNetworkId(networkId); List<UserVmVO> vms = _userVmDao.listByNetworkId(networkId);
if (vms != null && !vms.isEmpty()) { if (!vms.isEmpty()) {
for (UserVmVO vm : vms) { for (UserVmVO vm : vms) {
if (vm.getState() != State.Destroyed && vm.getState() != State.Expunging) {
NicVO nic = _nicDao.findByInstanceIdAndNetworkId(networkId, vm.getId()); NicVO nic = _nicDao.findByInstanceIdAndNetworkId(networkId, vm.getId());
if (nic != null) { if (nic != null) {
s_logger.debug("Creating dhcp entry for vm " + vm + " on domR " + router + "."); s_logger.debug("Creating dhcp entry for vm " + vm + " on domR " + router + ".");
DhcpEntryCommand dhcpCommand = new DhcpEntryCommand(nic.getMacAddress(), nic.getIp4Address(), vm.getName()); DhcpEntryCommand dhcpCommand = new DhcpEntryCommand(nic.getMacAddress(), nic.getIp4Address(), vm.getHostName());
dhcpCommand.setAccessDetail(NetworkElementCommand.ROUTER_IP, router.getPrivateIpAddress()); dhcpCommand.setAccessDetail(NetworkElementCommand.ROUTER_IP, router.getPrivateIpAddress());
dhcpCommand.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName()); dhcpCommand.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());
cmds.addCommand("dhcp", dhcpCommand); cmds.addCommand("dhcp", dhcpCommand);
@ -1535,7 +1635,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
} }
} }
} }
}
private boolean sendCommandsToRouter(final DomainRouterVO router, Commands cmds) throws AgentUnavailableException { private boolean sendCommandsToRouter(final DomainRouterVO router, Commands cmds) throws AgentUnavailableException {
Answer[] answers = null; Answer[] answers = null;
@ -1572,7 +1672,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
if (router.getState() == State.Running) { if (router.getState() == State.Running) {
Commands cmds = new Commands(OnError.Continue); Commands cmds = new Commands(OnError.Continue);
//Have to resend all already associated ip addresses // Have to resend all already associated ip addresses
createAssociateIPCommands(router, ipAddress, cmds, 0); createAssociateIPCommands(router, ipAddress, cmds, 0);
return sendCommandsToRouter(router, cmds); return sendCommandsToRouter(router, cmds);
@ -1595,7 +1695,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
if (router.getState() == State.Running) { if (router.getState() == State.Running) {
if (rules != null && !rules.isEmpty()) { if (rules != null && !rules.isEmpty()) {
if (rules.get(0).getPurpose() == Purpose.LoadBalancing) { if (rules.get(0).getPurpose() == Purpose.LoadBalancing) {
//for load balancer we have to resend all lb rules for the network // for load balancer we have to resend all lb rules for the network
List<LoadBalancerVO> lbs = _loadBalancerDao.listByNetworkId(network.getId()); List<LoadBalancerVO> lbs = _loadBalancerDao.listByNetworkId(network.getId());
List<LoadBalancingRule> lbRules = new ArrayList<LoadBalancingRule>(); List<LoadBalancingRule> lbRules = new ArrayList<LoadBalancingRule>();
for (LoadBalancerVO lb : lbs) { for (LoadBalancerVO lb : lbs) {
@ -1606,18 +1706,18 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
return applyLBRules(router, lbRules); return applyLBRules(router, lbRules);
} else if (rules.get(0).getPurpose() == Purpose.PortForwarding) { } else if (rules.get(0).getPurpose() == Purpose.PortForwarding) {
return applyPortForwardingRules(router, (List<PortForwardingRule>)rules); return applyPortForwardingRules(router, (List<PortForwardingRule>) rules);
} else if (rules.get(0).getPurpose() == Purpose.StaticNat) { } else if (rules.get(0).getPurpose() == Purpose.StaticNat) {
return applyStaticNatRules(router, (List<StaticNatRule>)rules); return applyStaticNatRules(router, (List<StaticNatRule>) rules);
}else { } else {
s_logger.warn("Unable to apply rules of purpose: " + rules.get(0).getPurpose()); s_logger.warn("Unable to apply rules of purpose: " + rules.get(0).getPurpose());
return false; return false;
} }
} else { } else {
return true; return true;
} }
} else if (router.getState() == State.Stopped || router.getState() == State.Stopping){ } else if (router.getState() == State.Stopped || router.getState() == State.Stopping) {
s_logger.debug("Router is in " + router.getState() + ", so not sending apply firewall rules commands to the backend"); s_logger.debug("Router is in " + router.getState() + ", so not sending apply firewall rules commands to the backend");
return true; return true;
} else { } else {
@ -1626,26 +1726,24 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
} }
} }
protected boolean applyLBRules(DomainRouterVO router, List<LoadBalancingRule> rules) throws ResourceUnavailableException { protected boolean applyLBRules(DomainRouterVO router, List<LoadBalancingRule> rules) throws ResourceUnavailableException {
Commands cmds = new Commands(OnError.Continue); Commands cmds = new Commands(OnError.Continue);
createApplyLoadBalancingRulesCommands(rules, router, cmds); createApplyLoadBalancingRulesCommands(rules, router, cmds);
//Send commands to router // Send commands to router
return sendCommandsToRouter(router, cmds); return sendCommandsToRouter(router, cmds);
} }
protected boolean applyPortForwardingRules(DomainRouterVO router, List<PortForwardingRule> rules) throws ResourceUnavailableException { protected boolean applyPortForwardingRules(DomainRouterVO router, List<PortForwardingRule> rules) throws ResourceUnavailableException {
Commands cmds = new Commands(OnError.Continue); Commands cmds = new Commands(OnError.Continue);
createApplyPortForwardingRulesCommands(rules, router, cmds); createApplyPortForwardingRulesCommands(rules, router, cmds);
//Send commands to router // Send commands to router
return sendCommandsToRouter(router, cmds); return sendCommandsToRouter(router, cmds);
} }
protected boolean applyStaticNatRules(DomainRouterVO router, List<StaticNatRule> rules) throws ResourceUnavailableException { protected boolean applyStaticNatRules(DomainRouterVO router, List<StaticNatRule> rules) throws ResourceUnavailableException {
Commands cmds = new Commands(OnError.Continue); Commands cmds = new Commands(OnError.Continue);
createApplyStaticNatRulesCommands(rules, router, cmds); createApplyStaticNatRulesCommands(rules, router, cmds);
//Send commands to router // Send commands to router
return sendCommandsToRouter(router, cmds); return sendCommandsToRouter(router, cmds);
} }

View File

@ -42,10 +42,13 @@ import com.cloud.agent.api.CreatePrivateTemplateFromVolumeCommand;
import com.cloud.agent.api.GetVmStatsAnswer; import com.cloud.agent.api.GetVmStatsAnswer;
import com.cloud.agent.api.GetVmStatsCommand; import com.cloud.agent.api.GetVmStatsCommand;
import com.cloud.agent.api.SnapshotCommand; import com.cloud.agent.api.SnapshotCommand;
import com.cloud.agent.api.StartAnswer;
import com.cloud.agent.api.StopAnswer; import com.cloud.agent.api.StopAnswer;
import com.cloud.agent.api.UpgradeSnapshotCommand; import com.cloud.agent.api.UpgradeSnapshotCommand;
import com.cloud.agent.api.VmStatsEntry; import com.cloud.agent.api.VmStatsEntry;
import com.cloud.agent.api.storage.CreatePrivateTemplateAnswer; import com.cloud.agent.api.storage.CreatePrivateTemplateAnswer;
import com.cloud.agent.api.to.NicTO;
import com.cloud.agent.api.to.VirtualMachineTO;
import com.cloud.agent.api.to.VolumeTO; import com.cloud.agent.api.to.VolumeTO;
import com.cloud.agent.manager.Commands; import com.cloud.agent.manager.Commands;
import com.cloud.alert.AlertManager; import com.cloud.alert.AlertManager;
@ -110,6 +113,7 @@ import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.network.IPAddressVO; import com.cloud.network.IPAddressVO;
import com.cloud.network.Network; import com.cloud.network.Network;
import com.cloud.network.Network.GuestIpType; import com.cloud.network.Network.GuestIpType;
import com.cloud.network.Network.Provider;
import com.cloud.network.NetworkManager; import com.cloud.network.NetworkManager;
import com.cloud.network.NetworkVO; import com.cloud.network.NetworkVO;
import com.cloud.network.Networks.TrafficType; import com.cloud.network.Networks.TrafficType;