use of com.cloud.vm.DomainRouterVO in project cloudstack by apache.
the class NetworkHelperImpl method startVirtualRouter.
@Override
public DomainRouterVO startVirtualRouter(final DomainRouterVO router, final User user, final Account caller, final Map<Param, Object> params) throws StorageUnavailableException, InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException {
if (router.getRole() != Role.VIRTUAL_ROUTER || !router.getIsRedundantRouter()) {
return start(router, user, caller, params, null);
}
if (router.getState() == State.Running) {
s_logger.debug("Redundant router " + router.getInstanceName() + " is already running!");
return router;
}
// We will wait until VR is up or fail
if (router.getState() == State.Starting) {
return waitRouter(router);
}
final DataCenterDeployment plan = new DataCenterDeployment(0, null, null, null, null, null);
DomainRouterVO result = null;
assert router.getIsRedundantRouter();
final List<Long> networkIds = _routerDao.getRouterNetworks(router.getId());
DomainRouterVO routerToBeAvoid = null;
if (networkIds.size() != 0) {
final List<DomainRouterVO> routerList = _routerDao.findByNetwork(networkIds.get(0));
for (final DomainRouterVO rrouter : routerList) {
if (rrouter.getHostId() != null && rrouter.getIsRedundantRouter() && rrouter.getState() == State.Running) {
if (routerToBeAvoid != null) {
throw new ResourceUnavailableException("Try to start router " + router.getInstanceName() + "(" + router.getId() + ")" + ", but there are already two redundant routers with IP " + router.getPublicIpAddress() + ", they are " + rrouter.getInstanceName() + "(" + rrouter.getId() + ") and " + routerToBeAvoid.getInstanceName() + "(" + routerToBeAvoid.getId() + ")", DataCenter.class, rrouter.getDataCenterId());
}
routerToBeAvoid = rrouter;
}
}
}
if (routerToBeAvoid == null) {
return start(router, user, caller, params, null);
}
// We would try best to deploy the router to another place
final int retryIndex = 5;
final ExcludeList[] avoids = new ExcludeList[5];
avoids[0] = new ExcludeList();
avoids[0].addPod(routerToBeAvoid.getPodIdToDeployIn());
avoids[1] = new ExcludeList();
avoids[1].addCluster(_hostDao.findById(routerToBeAvoid.getHostId()).getClusterId());
avoids[2] = new ExcludeList();
final List<VolumeVO> volumes = _volumeDao.findByInstanceAndType(routerToBeAvoid.getId(), Volume.Type.ROOT);
if (volumes != null && volumes.size() != 0) {
avoids[2].addPool(volumes.get(0).getPoolId());
}
avoids[2].addHost(routerToBeAvoid.getHostId());
avoids[3] = new ExcludeList();
avoids[3].addHost(routerToBeAvoid.getHostId());
avoids[4] = new ExcludeList();
for (int i = 0; i < retryIndex; i++) {
if (s_logger.isTraceEnabled()) {
s_logger.trace("Try to deploy redundant virtual router:" + router.getHostName() + ", for " + i + " time");
}
plan.setAvoids(avoids[i]);
try {
result = start(router, user, caller, params, plan);
} catch (final InsufficientServerCapacityException ex) {
result = null;
}
if (result != null) {
break;
}
}
return result;
}
use of com.cloud.vm.DomainRouterVO in project cloudstack by apache.
the class QueryManagerImpl method listDataCentersInternal.
private Pair<List<DataCenterJoinVO>, Integer> listDataCentersInternal(ListZonesCmd cmd) {
Account account = CallContext.current().getCallingAccount();
Long domainId = cmd.getDomainId();
Long id = cmd.getId();
String keyword = cmd.getKeyword();
String name = cmd.getName();
String networkType = cmd.getNetworkType();
Map<String, String> resourceTags = cmd.getTags();
SearchBuilder<DataCenterJoinVO> sb = _dcJoinDao.createSearchBuilder();
if (resourceTags != null && !resourceTags.isEmpty()) {
SearchBuilder<ResourceTagVO> tagSearch = _resourceTagDao.createSearchBuilder();
for (int count = 0; count < resourceTags.size(); count++) {
tagSearch.or().op("key" + String.valueOf(count), tagSearch.entity().getKey(), SearchCriteria.Op.EQ);
tagSearch.and("value" + String.valueOf(count), tagSearch.entity().getValue(), SearchCriteria.Op.EQ);
tagSearch.cp();
}
tagSearch.and("resourceType", tagSearch.entity().getResourceType(), SearchCriteria.Op.EQ);
sb.groupBy(sb.entity().getId());
sb.join("tagSearch", tagSearch, sb.entity().getId(), tagSearch.entity().getResourceId(), JoinBuilder.JoinType.INNER);
}
Filter searchFilter = new Filter(DataCenterJoinVO.class, null, false, cmd.getStartIndex(), cmd.getPageSizeVal());
SearchCriteria<DataCenterJoinVO> sc = sb.create();
if (networkType != null) {
sc.addAnd("networkType", SearchCriteria.Op.EQ, networkType);
}
if (id != null) {
sc.addAnd("id", SearchCriteria.Op.EQ, id);
} else if (name != null) {
sc.addAnd("name", SearchCriteria.Op.EQ, name);
} else {
if (keyword != null) {
SearchCriteria<DataCenterJoinVO> ssc = _dcJoinDao.createSearchCriteria();
ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("description", SearchCriteria.Op.LIKE, "%" + keyword + "%");
sc.addAnd("name", SearchCriteria.Op.SC, ssc);
}
/*
* List all resources due to Explicit Dedication except the
* dedicated resources of other account
*/
if (domainId != null) {
//
// for domainId != null // right now, we made the decision to
// only list zones associated // with this domain, private zone
sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId);
if (_accountMgr.isNormalUser(account.getId())) {
// accountId == null (zones dedicated to a domain) or
// accountId = caller
SearchCriteria<DataCenterJoinVO> sdc = _dcJoinDao.createSearchCriteria();
sdc.addOr("accountId", SearchCriteria.Op.EQ, account.getId());
sdc.addOr("accountId", SearchCriteria.Op.NULL);
sc.addAnd("accountId", SearchCriteria.Op.SC, sdc);
}
} else if (_accountMgr.isNormalUser(account.getId())) {
// it was decided to return all zones for the user's domain, and
// everything above till root
// list all zones belonging to this domain, and all of its
// parents
// check the parent, if not null, add zones for that parent to
// list
// find all domain Id up to root domain for this account
List<Long> domainIds = new ArrayList<Long>();
DomainVO domainRecord = _domainDao.findById(account.getDomainId());
if (domainRecord == null) {
s_logger.error("Could not find the domainId for account:" + account.getAccountName());
throw new CloudAuthenticationException("Could not find the domainId for account:" + account.getAccountName());
}
domainIds.add(domainRecord.getId());
while (domainRecord.getParent() != null) {
domainRecord = _domainDao.findById(domainRecord.getParent());
domainIds.add(domainRecord.getId());
}
// domainId == null (public zones) or domainId IN [all domain id
// up to root domain]
SearchCriteria<DataCenterJoinVO> sdc = _dcJoinDao.createSearchCriteria();
sdc.addOr("domainId", SearchCriteria.Op.IN, domainIds.toArray());
sdc.addOr("domainId", SearchCriteria.Op.NULL);
sc.addAnd("domainId", SearchCriteria.Op.SC, sdc);
// remove disabled zones
sc.addAnd("allocationState", SearchCriteria.Op.NEQ, Grouping.AllocationState.Disabled);
// accountId == null (zones dedicated to a domain) or
// accountId = caller
SearchCriteria<DataCenterJoinVO> sdc2 = _dcJoinDao.createSearchCriteria();
sdc2.addOr("accountId", SearchCriteria.Op.EQ, account.getId());
sdc2.addOr("accountId", SearchCriteria.Op.NULL);
sc.addAnd("accountId", SearchCriteria.Op.SC, sdc2);
// remove Dedicated zones not dedicated to this domainId or
// subdomainId
List<Long> dedicatedZoneIds = removeDedicatedZoneNotSuitabe(domainIds);
if (!dedicatedZoneIds.isEmpty()) {
sdc.addAnd("id", SearchCriteria.Op.NIN, dedicatedZoneIds.toArray(new Object[dedicatedZoneIds.size()]));
}
} else if (_accountMgr.isDomainAdmin(account.getId()) || account.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) {
// it was decided to return all zones for the domain admin, and
// everything above till root, as well as zones till the domain
// leaf
List<Long> domainIds = new ArrayList<Long>();
DomainVO domainRecord = _domainDao.findById(account.getDomainId());
if (domainRecord == null) {
s_logger.error("Could not find the domainId for account:" + account.getAccountName());
throw new CloudAuthenticationException("Could not find the domainId for account:" + account.getAccountName());
}
domainIds.add(domainRecord.getId());
// find all domain Ids till leaf
List<DomainVO> allChildDomains = _domainDao.findAllChildren(domainRecord.getPath(), domainRecord.getId());
for (DomainVO domain : allChildDomains) {
domainIds.add(domain.getId());
}
// then find all domain Id up to root domain for this account
while (domainRecord.getParent() != null) {
domainRecord = _domainDao.findById(domainRecord.getParent());
domainIds.add(domainRecord.getId());
}
// domainId == null (public zones) or domainId IN [all domain id
// up to root domain]
SearchCriteria<DataCenterJoinVO> sdc = _dcJoinDao.createSearchCriteria();
sdc.addOr("domainId", SearchCriteria.Op.IN, domainIds.toArray());
sdc.addOr("domainId", SearchCriteria.Op.NULL);
sc.addAnd("domainId", SearchCriteria.Op.SC, sdc);
// remove disabled zones
sc.addAnd("allocationState", SearchCriteria.Op.NEQ, Grouping.AllocationState.Disabled);
// remove Dedicated zones not dedicated to this domainId or
// subdomainId
List<Long> dedicatedZoneIds = removeDedicatedZoneNotSuitabe(domainIds);
if (!dedicatedZoneIds.isEmpty()) {
sdc.addAnd("id", SearchCriteria.Op.NIN, dedicatedZoneIds.toArray(new Object[dedicatedZoneIds.size()]));
}
}
// handle available=FALSE option, only return zones with at least
// one VM running there
Boolean available = cmd.isAvailable();
if (account != null) {
if ((available != null) && Boolean.FALSE.equals(available)) {
// data centers with
Set<Long> dcIds = new HashSet<Long>();
// at least one VM
// running
List<DomainRouterVO> routers = _routerDao.listBy(account.getId());
for (DomainRouterVO router : routers) {
dcIds.add(router.getDataCenterId());
}
if (dcIds.size() == 0) {
return new Pair<List<DataCenterJoinVO>, Integer>(new ArrayList<DataCenterJoinVO>(), 0);
} else {
sc.addAnd("id", SearchCriteria.Op.IN, dcIds.toArray());
}
}
}
}
if (resourceTags != null && !resourceTags.isEmpty()) {
int count = 0;
sc.setJoinParameters("tagSearch", "resourceType", ResourceObjectType.Zone.toString());
for (Map.Entry<String, String> entry : resourceTags.entrySet()) {
sc.setJoinParameters("tagSearch", "key" + String.valueOf(count), entry.getKey());
sc.setJoinParameters("tagSearch", "value" + String.valueOf(count), entry.getValue());
count++;
}
}
return _dcJoinDao.searchAndCount(sc, searchFilter);
}
use of com.cloud.vm.DomainRouterVO in project cloudstack by apache.
the class CommandSetupHelper method createApplyLoadBalancingRulesCommands.
public void createApplyLoadBalancingRulesCommands(final List<LoadBalancingRule> rules, final VirtualRouter router, final Commands cmds, final long guestNetworkId) {
final LoadBalancerTO[] lbs = new LoadBalancerTO[rules.size()];
int i = 0;
// We don't support VR to be inline currently
final boolean inline = false;
for (final LoadBalancingRule rule : rules) {
final boolean revoked = rule.getState().equals(FirewallRule.State.Revoke);
final String protocol = rule.getProtocol();
final String lb_protocol = rule.getLbProtocol();
final String algorithm = rule.getAlgorithm();
final String uuid = rule.getUuid();
final String srcIp = rule.getSourceIp().addr();
final int srcPort = rule.getSourcePortStart();
final List<LbDestination> destinations = rule.getDestinations();
final List<LbStickinessPolicy> stickinessPolicies = rule.getStickinessPolicies();
final LoadBalancerTO lb = new LoadBalancerTO(uuid, srcIp, srcPort, protocol, algorithm, revoked, false, inline, destinations, stickinessPolicies);
lb.setLbProtocol(lb_protocol);
lbs[i++] = lb;
}
String routerPublicIp = null;
if (router instanceof DomainRouterVO) {
final DomainRouterVO domr = _routerDao.findById(router.getId());
routerPublicIp = domr.getPublicIpAddress();
if (routerPublicIp == null) {
routerPublicIp = router.getPublicIpAddress();
}
}
final Network guestNetwork = _networkModel.getNetwork(guestNetworkId);
final Nic nic = _nicDao.findByNtwkIdAndInstanceId(guestNetwork.getId(), router.getId());
final NicProfile nicProfile = new NicProfile(nic, guestNetwork, nic.getBroadcastUri(), nic.getIsolationUri(), _networkModel.getNetworkRate(guestNetwork.getId(), router.getId()), _networkModel.isSecurityGroupSupportedInNetwork(guestNetwork), _networkModel.getNetworkTag(router.getHypervisorType(), guestNetwork));
final NetworkOffering offering = _networkOfferingDao.findById(guestNetwork.getNetworkOfferingId());
String maxconn = null;
if (offering.getConcurrentConnections() == null) {
maxconn = _configDao.getValue(Config.NetworkLBHaproxyMaxConn.key());
} else {
maxconn = offering.getConcurrentConnections().toString();
}
final LoadBalancerConfigCommand cmd = new LoadBalancerConfigCommand(lbs, routerPublicIp, _routerControlHelper.getRouterIpInNetwork(guestNetworkId, router.getId()), router.getPrivateIpAddress(), _itMgr.toNicTO(nicProfile, router.getHypervisorType()), router.getVpcId(), maxconn, offering.isKeepAliveEnabled());
cmd.lbStatsVisibility = _configDao.getValue(Config.NetworkLBHaproxyStatsVisbility.key());
cmd.lbStatsUri = _configDao.getValue(Config.NetworkLBHaproxyStatsUri.key());
cmd.lbStatsAuth = _configDao.getValue(Config.NetworkLBHaproxyStatsAuth.key());
cmd.lbStatsPort = _configDao.getValue(Config.NetworkLBHaproxyStatsPort.key());
cmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, _routerControlHelper.getRouterControlIp(router.getId()));
cmd.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP, _routerControlHelper.getRouterIpInNetwork(guestNetworkId, router.getId()));
cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());
final DataCenterVO dcVo = _dcDao.findById(router.getDataCenterId());
cmd.setAccessDetail(NetworkElementCommand.ZONE_NETWORK_TYPE, dcVo.getNetworkType().toString());
cmds.addCommand(cmd);
}
use of com.cloud.vm.DomainRouterVO in project cloudstack by apache.
the class StoragePoolAutomationImpl method cancelMaintain.
@Override
public boolean cancelMaintain(DataStore store) {
// Change the storage state back to up
Long userId = CallContext.current().getCallingUserId();
User user = _userDao.findById(userId);
Account account = CallContext.current().getCallingAccount();
StoragePoolVO poolVO = primaryDataStoreDao.findById(store.getId());
StoragePool pool = (StoragePool) store;
//Handeling the Zone wide and cluster wide primay storage
List<HostVO> hosts = new ArrayList<HostVO>();
// if the storage scope is ZONE wide, then get all the hosts for which hypervisor ZWSP created to send Modifystoragepoolcommand
if (poolVO.getScope().equals(ScopeType.ZONE)) {
if (HypervisorType.Any.equals(pool.getHypervisor())) {
hosts = _resourceMgr.listAllUpAndEnabledHostsInOneZone(pool.getDataCenterId());
} else {
hosts = _resourceMgr.listAllUpAndEnabledHostsInOneZoneByHypervisor(poolVO.getHypervisor(), pool.getDataCenterId());
}
} else {
hosts = _resourceMgr.listHostsInClusterByStatus(pool.getClusterId(), Status.Up);
}
if (hosts == null || hosts.size() == 0) {
return true;
}
// add heartbeat
for (HostVO host : hosts) {
ModifyStoragePoolCommand msPoolCmd = new ModifyStoragePoolCommand(true, pool);
final Answer answer = agentMgr.easySend(host.getId(), msPoolCmd);
if (answer == null || !answer.getResult()) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("ModifyStoragePool add failed due to " + ((answer == null) ? "answer null" : answer.getDetails()));
}
} else {
if (s_logger.isDebugEnabled()) {
s_logger.debug("ModifyStoragePool add secceeded");
}
}
}
// 2. Get a list of pending work for this queue
List<StoragePoolWorkVO> pendingWork = _storagePoolWorkDao.listPendingWorkForCancelMaintenanceByPoolId(poolVO.getId());
// 3. work through the queue
for (StoragePoolWorkVO work : pendingWork) {
try {
VMInstanceVO vmInstance = vmDao.findById(work.getVmId());
if (vmInstance == null) {
continue;
}
// proxy
if (vmInstance.getType().equals(VirtualMachine.Type.ConsoleProxy)) {
ConsoleProxyVO consoleProxy = _consoleProxyDao.findById(vmInstance.getId());
vmMgr.advanceStart(consoleProxy.getUuid(), null, null);
// update work queue
work.setStartedAfterMaintenance(true);
_storagePoolWorkDao.update(work.getId(), work);
}
// if the instance is of type ssvm, call the ssvm manager
if (vmInstance.getType().equals(VirtualMachine.Type.SecondaryStorageVm)) {
SecondaryStorageVmVO ssVm = _secStrgDao.findById(vmInstance.getId());
vmMgr.advanceStart(ssVm.getUuid(), null, null);
// update work queue
work.setStartedAfterMaintenance(true);
_storagePoolWorkDao.update(work.getId(), work);
}
// manager
if (vmInstance.getType().equals(VirtualMachine.Type.DomainRouter)) {
DomainRouterVO domR = _domrDao.findById(vmInstance.getId());
vmMgr.advanceStart(domR.getUuid(), null, null);
// update work queue
work.setStartedAfterMaintenance(true);
_storagePoolWorkDao.update(work.getId(), work);
}
// if the instance is of type user vm, call the user vm manager
if (vmInstance.getType().equals(VirtualMachine.Type.User)) {
// don't allow to start vm that doesn't have a root volume
if (volumeDao.findByInstanceAndType(vmInstance.getId(), Volume.Type.ROOT).isEmpty()) {
_storagePoolWorkDao.remove(work.getId());
} else {
UserVmVO userVm = userVmDao.findById(vmInstance.getId());
vmMgr.advanceStart(userVm.getUuid(), null, null);
work.setStartedAfterMaintenance(true);
_storagePoolWorkDao.update(work.getId(), work);
}
}
} catch (Exception e) {
s_logger.debug("Failed start vm", e);
throw new CloudRuntimeException(e.toString());
}
}
return false;
}
use of com.cloud.vm.DomainRouterVO in project cloudstack by apache.
the class RouterControlHelperTest method testGetRouterControlIpWithRouterIp.
@Test
public void testGetRouterControlIpWithRouterIp() {
// Prepare
List<NicVO> nics = new ArrayList<>();
NicVO nic1 = mock(NicVO.class);
when(nic1.getNetworkId()).thenReturn(NW_ID_1);
when(nic1.getIPv4Address()).thenReturn(null);
nics.add(nic1);
when(this.nicDao.listByVmId(ROUTER_ID)).thenReturn(nics);
NetworkVO nw1 = mock(NetworkVO.class);
when(nw1.getTrafficType()).thenReturn(TrafficType.Public);
when(this.nwDao.findById(NW_ID_1)).thenReturn(nw1);
DomainRouterVO router = mock(DomainRouterVO.class);
when(this.routerDao.findById(ROUTER_ID)).thenReturn(router);
when(router.getPrivateIpAddress()).thenReturn(IP4_ADDRES1);
// Execute
final String ip4address = this.routerControlHelper.getRouterControlIp(ROUTER_ID);
// Assert
assertEquals(DIDN_T_GET_THE_EXPECTED_IP4_ADDRESS, IP4_ADDRES1, ip4address);
}
Aggregations