use of com.cloud.network.dao.NetworkAccountVO in project cosmic by MissionCriticalCloud.
the class NetworkOrchestrator method destroyNetwork.
@Override
@DB
public boolean destroyNetwork(final long networkId, final ReservationContext context, final boolean forced) {
final Account callerAccount = context.getAccount();
NetworkVO network = _networksDao.findById(networkId);
if (network == null) {
s_logger.debug("Unable to find network with id: " + networkId);
return false;
}
// Make sure that there are no user vms in the network that are not Expunged/Error
final List<UserVmVO> userVms = _userVmDao.listByNetworkIdAndStates(networkId);
for (final UserVmVO vm : userVms) {
if (!(vm.getState() == VirtualMachine.State.Expunging && vm.getRemoved() != null)) {
s_logger.warn("Can't delete the network, not all user vms are expunged. Vm " + vm + " is in " + vm.getState() + " state");
return false;
}
}
// Don't allow to delete network via api call when it has vms assigned to it
final int nicCount = getActiveNicsInNetwork(networkId);
if (nicCount > 0) {
s_logger.debug("The network id=" + networkId + " has active Nics, but shouldn't.");
// at this point we have already determined that there are no active user vms in network
// if the op_networks table shows active nics, it's a bug in releasing nics updating op_networks
_networksDao.changeActiveNicsBy(networkId, -1 * nicCount);
}
// In Basic zone, make sure that there are no non-removed console proxies and SSVMs using the network
final Zone zone = _zoneRepository.findOne(network.getDataCenterId());
if (zone.getNetworkType() == com.cloud.model.enumeration.NetworkType.Basic) {
final List<VMInstanceVO> systemVms = _vmDao.listNonRemovedVmsByTypeAndNetwork(network.getId(), Type.ConsoleProxy, Type.SecondaryStorageVm);
if (systemVms != null && !systemVms.isEmpty()) {
s_logger.warn("Can't delete the network, not all consoleProxy/secondaryStorage vms are expunged");
return false;
}
}
// Shutdown network first
shutdownNetwork(networkId, context, false);
// get updated state for the network
network = _networksDao.findById(networkId);
if (network.getState() != Network.State.Allocated && network.getState() != Network.State.Setup && !forced) {
s_logger.debug("Network is not not in the correct state to be destroyed: " + network.getState());
return false;
}
boolean success = true;
if (!cleanupNetworkResources(networkId, callerAccount, context.getCaller().getId())) {
s_logger.warn("Unable to delete network id=" + networkId + ": failed to cleanup network resources");
return false;
}
// get providers to destroy
final List<Provider> providersToDestroy = getNetworkProviders(network.getId());
for (final NetworkElement element : networkElements) {
if (providersToDestroy.contains(element.getProvider())) {
try {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Sending destroy to " + element);
}
if (!element.destroy(network, context)) {
success = false;
s_logger.warn("Unable to complete destroy of the network: failed to destroy network element " + element.getName());
}
} catch (final ResourceUnavailableException e) {
s_logger.warn("Unable to complete destroy of the network due to element: " + element.getName(), e);
success = false;
} catch (final ConcurrentOperationException e) {
s_logger.warn("Unable to complete destroy of the network due to element: " + element.getName(), e);
success = false;
} catch (final Exception e) {
s_logger.warn("Unable to complete destroy of the network due to element: " + element.getName(), e);
success = false;
}
}
}
if (success) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Network id=" + networkId + " is destroyed successfully, cleaning up corresponding resources now.");
}
final NetworkVO networkFinal = network;
try {
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(final TransactionStatus status) {
final NetworkGuru guru = AdapterBase.getAdapterByName(networkGurus, networkFinal.getGuruName());
// Deleting sync networks
final List<NetworkVO> syncNetworks = _networksDao.listSyncNetworksByRelatedNetwork(networkId);
syncNetworks.forEach(syncNetwork -> removeAndShutdownSyncNetwork(syncNetwork.getId()));
guru.trash(networkFinal, _networkOfferingDao.findById(networkFinal.getNetworkOfferingId()));
if (!deleteVlansInNetwork(networkFinal.getId(), context.getCaller().getId(), callerAccount)) {
s_logger.warn("Failed to delete network " + networkFinal + "; was unable to cleanup corresponding ip ranges");
throw new CloudRuntimeException("Failed to delete network " + networkFinal + "; was unable to cleanup corresponding ip ranges");
} else {
// commit transaction only when ips and vlans for the network are released successfully
try {
stateTransitTo(networkFinal, Event.DestroyNetwork);
} catch (final NoTransitionException e) {
s_logger.debug(e.getMessage());
}
if (_networksDao.remove(networkFinal.getId())) {
final NetworkDomainVO networkDomain = _networkDomainDao.getDomainNetworkMapByNetworkId(networkFinal.getId());
if (networkDomain != null) {
_networkDomainDao.remove(networkDomain.getId());
}
final NetworkAccountVO networkAccount = _networkAccountDao.getAccountNetworkMapByNetworkId(networkFinal.getId());
if (networkAccount != null) {
_networkAccountDao.remove(networkAccount.getId());
}
}
final NetworkOffering ntwkOff = _entityMgr.findById(NetworkOffering.class, networkFinal.getNetworkOfferingId());
final boolean updateResourceCount = resourceCountNeedsUpdate(ntwkOff, networkFinal.getAclType());
if (updateResourceCount) {
_resourceLimitMgr.decrementResourceCount(networkFinal.getAccountId(), ResourceType.network, networkFinal.getDisplayNetwork());
}
}
}
});
if (_networksDao.findById(network.getId()) == null) {
// remove its related ACL permission
final Pair<Class<?>, Long> networkMsg = new Pair<>(Network.class, networkFinal.getId());
_messageBus.publish(_name, EntityManager.MESSAGE_REMOVE_ENTITY_EVENT, PublishScope.LOCAL, networkMsg);
}
return true;
} catch (final CloudRuntimeException e) {
s_logger.error("Failed to delete network", e);
return false;
}
}
return success;
}
use of com.cloud.network.dao.NetworkAccountVO in project cloudstack by apache.
the class NetworkOrchestrator method destroyNetwork.
@Override
@DB
public boolean destroyNetwork(final long networkId, final ReservationContext context, final boolean forced) {
final Account callerAccount = context.getAccount();
NetworkVO network = _networksDao.findById(networkId);
if (network == null) {
s_logger.debug("Unable to find network with id: " + networkId);
return false;
}
// Make sure that there are no user vms in the network that are not Expunged/Error
final List<UserVmVO> userVms = _userVmDao.listByNetworkIdAndStates(networkId);
for (final UserVmVO vm : userVms) {
if (!(vm.getState() == VirtualMachine.State.Expunging && vm.getRemoved() != null)) {
s_logger.warn("Can't delete the network, not all user vms are expunged. Vm " + vm + " is in " + vm.getState() + " state");
return false;
}
}
// Don't allow to delete network via api call when it has vms assigned to it
final int nicCount = getActiveNicsInNetwork(networkId);
if (nicCount > 0) {
s_logger.debug("The network id=" + networkId + " has active Nics, but shouldn't.");
// at this point we have already determined that there are no active user vms in network
// if the op_networks table shows active nics, it's a bug in releasing nics updating op_networks
_networksDao.changeActiveNicsBy(networkId, -1 * nicCount);
}
// In Basic zone, make sure that there are no non-removed console proxies and SSVMs using the network
final DataCenter zone = _entityMgr.findById(DataCenter.class, network.getDataCenterId());
if (zone.getNetworkType() == NetworkType.Basic) {
final List<VMInstanceVO> systemVms = _vmDao.listNonRemovedVmsByTypeAndNetwork(network.getId(), Type.ConsoleProxy, Type.SecondaryStorageVm);
if (systemVms != null && !systemVms.isEmpty()) {
s_logger.warn("Can't delete the network, not all consoleProxy/secondaryStorage vms are expunged");
return false;
}
}
cleanupPersistentnNetworkResources(network);
// Shutdown network first
shutdownNetwork(networkId, context, false);
// get updated state for the network
network = _networksDao.findById(networkId);
if (network.getState() != Network.State.Allocated && network.getState() != Network.State.Setup && !forced) {
s_logger.debug("Network is not not in the correct state to be destroyed: " + network.getState());
return false;
}
boolean success = true;
if (!cleanupNetworkResources(networkId, callerAccount, context.getCaller().getId())) {
s_logger.warn("Unable to delete network id=" + networkId + ": failed to cleanup network resources");
return false;
}
// get providers to destroy
final List<Provider> providersToDestroy = getNetworkProviders(network.getId());
for (final NetworkElement element : networkElements) {
if (providersToDestroy.contains(element.getProvider())) {
try {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Sending destroy to " + element);
}
if (!element.destroy(network, context)) {
success = false;
s_logger.warn("Unable to complete destroy of the network: failed to destroy network element " + element.getName());
}
} catch (final ResourceUnavailableException e) {
s_logger.warn("Unable to complete destroy of the network due to element: " + element.getName(), e);
success = false;
} catch (final ConcurrentOperationException e) {
s_logger.warn("Unable to complete destroy of the network due to element: " + element.getName(), e);
success = false;
} catch (final Exception e) {
s_logger.warn("Unable to complete destroy of the network due to element: " + element.getName(), e);
success = false;
}
}
}
if (success) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Network id=" + networkId + " is destroyed successfully, cleaning up corresponding resources now.");
}
final NetworkVO networkFinal = network;
try {
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(final TransactionStatus status) {
final NetworkGuru guru = AdapterBase.getAdapterByName(networkGurus, networkFinal.getGuruName());
if (!guru.trash(networkFinal, _networkOfferingDao.findById(networkFinal.getNetworkOfferingId()))) {
throw new CloudRuntimeException("Failed to trash network.");
}
if (!deleteVlansInNetwork(networkFinal.getId(), context.getCaller().getId(), callerAccount)) {
s_logger.warn("Failed to delete network " + networkFinal + "; was unable to cleanup corresponding ip ranges");
throw new CloudRuntimeException("Failed to delete network " + networkFinal + "; was unable to cleanup corresponding ip ranges");
} else {
// commit transaction only when ips and vlans for the network are released successfully
try {
stateTransitTo(networkFinal, Event.DestroyNetwork);
} catch (final NoTransitionException e) {
s_logger.debug(e.getMessage());
}
if (_networksDao.remove(networkFinal.getId())) {
final NetworkDomainVO networkDomain = _networkDomainDao.getDomainNetworkMapByNetworkId(networkFinal.getId());
if (networkDomain != null) {
_networkDomainDao.remove(networkDomain.getId());
}
final NetworkAccountVO networkAccount = _networkAccountDao.getAccountNetworkMapByNetworkId(networkFinal.getId());
if (networkAccount != null) {
_networkAccountDao.remove(networkAccount.getId());
}
networkDetailsDao.removeDetails(networkFinal.getId());
}
final NetworkOffering ntwkOff = _entityMgr.findById(NetworkOffering.class, networkFinal.getNetworkOfferingId());
final boolean updateResourceCount = resourceCountNeedsUpdate(ntwkOff, networkFinal.getAclType());
if (updateResourceCount) {
_resourceLimitMgr.decrementResourceCount(networkFinal.getAccountId(), ResourceType.network, networkFinal.getDisplayNetwork());
}
}
}
});
if (_networksDao.findById(network.getId()) == null) {
// remove its related ACL permission
final Pair<Class<?>, Long> networkMsg = new Pair<Class<?>, Long>(Network.class, networkFinal.getId());
_messageBus.publish(_name, EntityManager.MESSAGE_REMOVE_ENTITY_EVENT, PublishScope.LOCAL, networkMsg);
}
return true;
} catch (final CloudRuntimeException e) {
s_logger.error("Failed to delete network", e);
return false;
}
}
return success;
}
use of com.cloud.network.dao.NetworkAccountVO in project cloudstack by apache.
the class ManagementServerImpl method searchForIPAddresses.
@Override
public Pair<List<? extends IpAddress>, Integer> searchForIPAddresses(final ListPublicIpAddressesCmd cmd) {
final Long associatedNetworkId = cmd.getAssociatedNetworkId();
final Long zone = cmd.getZoneId();
final Long vlan = cmd.getVlanId();
final Boolean forVirtualNetwork = cmd.isForVirtualNetwork();
final Long ipId = cmd.getId();
final Long networkId = cmd.getNetworkId();
final Long vpcId = cmd.getVpcId();
final String state = cmd.getState();
Boolean isAllocated = cmd.isAllocatedOnly();
if (isAllocated == null) {
if (state != null && state.equalsIgnoreCase(IpAddress.State.Free.name())) {
isAllocated = Boolean.FALSE;
} else {
// default
isAllocated = Boolean.TRUE;
}
} else {
if (state != null && state.equalsIgnoreCase(IpAddress.State.Free.name())) {
if (isAllocated) {
throw new InvalidParameterValueException("Conflict: allocatedonly is true but state is Free");
}
} else if (state != null && state.equalsIgnoreCase(IpAddress.State.Allocated.name())) {
isAllocated = Boolean.TRUE;
}
}
VlanType vlanType = null;
if (forVirtualNetwork != null) {
vlanType = forVirtualNetwork ? VlanType.VirtualNetwork : VlanType.DirectAttached;
} else {
vlanType = VlanType.VirtualNetwork;
}
final Account caller = getCaller();
List<IPAddressVO> addrs = new ArrayList<>();
if (vlanType == VlanType.DirectAttached && networkId == null && ipId == null) {
// only root admin can list public ips in all shared networks
if (caller.getType() != Account.ACCOUNT_TYPE_ADMIN) {
isAllocated = true;
}
} else if (vlanType == VlanType.DirectAttached) {
// list public ip address on shared network
// access control. admin: all Ips, domain admin/user: all Ips in shared network in the domain/sub-domain/user
NetworkVO network = null;
if (networkId == null) {
IPAddressVO ip = _publicIpAddressDao.findById(ipId);
if (ip == null) {
throw new InvalidParameterValueException("Please specify a valid ipaddress id");
}
network = _networkDao.findById(ip.getSourceNetworkId());
} else {
network = _networkDao.findById(networkId);
}
if (network == null || network.getGuestType() != Network.GuestType.Shared) {
throw new InvalidParameterValueException("Please specify a valid network id");
}
if (network.getAclType() == ControlledEntity.ACLType.Account) {
NetworkAccountVO networkMap = _networkAccountDao.getAccountNetworkMapByNetworkId(network.getId());
if (networkMap == null) {
return new Pair<>(addrs, 0);
}
_accountMgr.checkAccess(caller, null, false, _accountDao.findById(networkMap.getAccountId()));
} else {
// Domain level
NetworkDomainVO networkMap = _networkDomainDao.getDomainNetworkMapByNetworkId(network.getId());
if (networkMap == null) {
return new Pair<>(addrs, 0);
}
if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL || caller.getType() == Account.ACCOUNT_TYPE_PROJECT) {
if (_networkMgr.isNetworkAvailableInDomain(network.getId(), caller.getDomainId())) {
isAllocated = Boolean.TRUE;
} else {
return new Pair<>(addrs, 0);
}
} else if (caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) {
if (caller.getDomainId() == networkMap.getDomainId() || _domainDao.isChildDomain(caller.getDomainId(), networkMap.getDomainId())) {
s_logger.debug("Caller " + caller.getUuid() + " has permission to access the network : " + network.getUuid());
} else {
if (_networkMgr.isNetworkAvailableInDomain(network.getId(), caller.getDomainId())) {
isAllocated = Boolean.TRUE;
} else {
return new Pair<>(addrs, 0);
}
}
}
}
}
final Filter searchFilter = new Filter(IPAddressVO.class, "address", false, null, null);
final SearchBuilder<IPAddressVO> sb = _publicIpAddressDao.createSearchBuilder();
Long domainId = null;
Boolean isRecursive = null;
final List<Long> permittedAccounts = new ArrayList<>();
ListProjectResourcesCriteria listProjectResourcesCriteria = null;
if (isAllocated || (vlanType == VlanType.VirtualNetwork && (caller.getType() != Account.ACCOUNT_TYPE_ADMIN || cmd.getDomainId() != null))) {
final Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<>(cmd.getDomainId(), cmd.isRecursive(), null);
_accountMgr.buildACLSearchParameters(caller, cmd.getId(), cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), false);
domainId = domainIdRecursiveListProject.first();
isRecursive = domainIdRecursiveListProject.second();
listProjectResourcesCriteria = domainIdRecursiveListProject.third();
_accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
}
buildParameters(sb, cmd, vlanType == VlanType.VirtualNetwork ? true : isAllocated);
SearchCriteria<IPAddressVO> sc = sb.create();
setParameters(sc, cmd, vlanType);
if (isAllocated || (vlanType == VlanType.VirtualNetwork && (caller.getType() != Account.ACCOUNT_TYPE_ADMIN || cmd.getDomainId() != null))) {
_accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
}
if (associatedNetworkId != null) {
_accountMgr.checkAccess(caller, null, false, _networkDao.findById(associatedNetworkId));
sc.setParameters("associatedNetworkIdEq", associatedNetworkId);
}
if (vpcId != null) {
_accountMgr.checkAccess(caller, null, false, _vpcDao.findById(vpcId));
sc.setParameters("vpcId", vpcId);
}
// Allocated
addrs = _publicIpAddressDao.search(sc, searchFilter);
// Free IP addresses in system IP ranges
List<Long> freeAddrIds = new ArrayList<>();
if (!(isAllocated || vlanType == VlanType.DirectAttached)) {
Long zoneId = zone;
Account owner = _accountMgr.finalizeOwner(CallContext.current().getCallingAccount(), cmd.getAccountName(), cmd.getDomainId(), cmd.getProjectId());
if (associatedNetworkId != null) {
NetworkVO guestNetwork = _networkDao.findById(associatedNetworkId);
if (zoneId == null) {
zoneId = guestNetwork.getDataCenterId();
} else if (zoneId != guestNetwork.getDataCenterId()) {
InvalidParameterValueException ex = new InvalidParameterValueException("Please specify a valid associated network id in the specified zone.");
throw ex;
}
owner = _accountDao.findById(guestNetwork.getAccountId());
}
List<DataCenterVO> dcList = new ArrayList<>();
if (zoneId == null) {
dcList = ApiDBUtils.listZones();
} else {
dcList.add(ApiDBUtils.findZoneById(zoneId));
}
List<Long> vlanDbIds = null;
if (vlan != null) {
vlanDbIds = new ArrayList<>();
vlanDbIds.add(vlan);
}
List<IPAddressVO> freeAddrs = new ArrayList<>();
for (DataCenterVO dc : dcList) {
long dcId = dc.getId();
try {
freeAddrs.addAll(_ipAddressMgr.listAvailablePublicIps(dcId, null, vlanDbIds, owner, VlanType.VirtualNetwork, associatedNetworkId, false, false, false, null, null, false, cmd.getVpcId(), cmd.isDisplay(), false, // Free
false));
} catch (InsufficientAddressCapacityException e) {
s_logger.warn("no free address is found in zone " + dcId);
}
}
for (IPAddressVO addr : freeAddrs) {
freeAddrIds.add(addr.getId());
}
}
if (freeAddrIds.size() > 0) {
final SearchBuilder<IPAddressVO> sb2 = _publicIpAddressDao.createSearchBuilder();
buildParameters(sb2, cmd, false);
sb2.and("ids", sb2.entity().getId(), SearchCriteria.Op.IN);
SearchCriteria<IPAddressVO> sc2 = sb2.create();
setParameters(sc2, cmd, vlanType);
sc2.setParameters("ids", freeAddrIds.toArray());
// Allocated + Free
addrs.addAll(_publicIpAddressDao.search(sc2, searchFilter));
}
Collections.sort(addrs, Comparator.comparing(IPAddressVO::getAddress));
List<? extends IpAddress> wPagination = com.cloud.utils.StringUtils.applyPagination(addrs, cmd.getStartIndex(), cmd.getPageSizeVal());
if (wPagination != null) {
return new Pair<List<? extends IpAddress>, Integer>(wPagination, addrs.size());
}
return new Pair<>(addrs, addrs.size());
}
Aggregations