use of com.cloud.network.VpnUserVO in project cosmic by MissionCriticalCloud.
the class RemoteAccessVpnManagerImpl method removeVpnUser.
@DB
@Override
public boolean removeVpnUser(final long vpnOwnerId, final String username, final Account caller) {
final VpnUserVO user = _vpnUsersDao.findByAccountAndUsername(vpnOwnerId, username);
if (user == null) {
throw new InvalidParameterValueException("Could not find vpn user " + username);
}
_accountMgr.checkAccess(caller, null, true, user);
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(final TransactionStatus status) {
user.setState(State.Revoke);
_vpnUsersDao.update(user.getId(), user);
}
});
return true;
}
use of com.cloud.network.VpnUserVO in project cosmic by MissionCriticalCloud.
the class AccountManagerImpl method cleanupAccount.
protected boolean cleanupAccount(final AccountVO account, final long callerUserId, final Account caller) {
final long accountId = account.getId();
boolean accountCleanupNeeded = false;
try {
// cleanup the users from the account
final List<UserVO> users = _userDao.listByAccount(accountId);
for (final UserVO user : users) {
if (!_userDao.remove(user.getId())) {
s_logger.error("Unable to delete user: " + user + " as a part of account " + account + " cleanup");
accountCleanupNeeded = true;
}
}
// delete the account from project accounts
_projectAccountDao.removeAccountFromProjects(accountId);
if (account.getType() != Account.ACCOUNT_TYPE_PROJECT) {
// delete the account from group
_messageBus.publish(_name, MESSAGE_REMOVE_ACCOUNT_EVENT, PublishScope.LOCAL, accountId);
}
// delete all vm groups belonging to accont
final List<InstanceGroupVO> groups = _vmGroupDao.listByAccountId(accountId);
for (final InstanceGroupVO group : groups) {
if (!_vmMgr.deleteVmGroup(group.getId())) {
s_logger.error("Unable to delete group: " + group.getId());
accountCleanupNeeded = true;
}
}
// Delete the snapshots dir for the account. Have to do this before destroying the VMs.
final boolean success = _snapMgr.deleteSnapshotDirsForAccount(accountId);
if (success) {
s_logger.debug("Successfully deleted snapshots directories for all volumes under account " + accountId + " across all zones");
}
// clean up templates
final List<VMTemplateVO> userTemplates = _templateDao.listByAccountId(accountId);
boolean allTemplatesDeleted = true;
for (final VMTemplateVO template : userTemplates) {
if (template.getRemoved() == null) {
try {
allTemplatesDeleted = _tmpltMgr.delete(callerUserId, template.getId(), null);
} catch (final Exception e) {
s_logger.warn("Failed to delete template while removing account: " + template.getName() + " due to: ", e);
allTemplatesDeleted = false;
}
}
}
if (!allTemplatesDeleted) {
s_logger.warn("Failed to delete templates while removing account id=" + accountId);
accountCleanupNeeded = true;
}
// Destroy VM Snapshots
final List<VMSnapshotVO> vmSnapshots = _vmSnapshotDao.listByAccountId(Long.valueOf(accountId));
for (final VMSnapshot vmSnapshot : vmSnapshots) {
try {
_vmSnapshotMgr.deleteVMSnapshot(vmSnapshot.getId());
} catch (final Exception e) {
s_logger.debug("Failed to cleanup vm snapshot " + vmSnapshot.getId() + " due to " + e.toString());
}
}
// Destroy the account's VMs
final List<UserVmVO> vms = _userVmDao.listByAccountId(accountId);
if (s_logger.isDebugEnabled()) {
s_logger.debug("Expunging # of vms (accountId=" + accountId + "): " + vms.size());
}
// no need to catch exception at this place as expunging vm should pass in order to perform further cleanup
for (final UserVmVO vm : vms) {
if (!_vmMgr.expunge(vm, callerUserId, caller)) {
s_logger.error("Unable to expunge vm: " + vm.getId());
accountCleanupNeeded = true;
}
}
// Mark the account's volumes as destroyed
final List<VolumeVO> volumes = _volumeDao.findDetachedByAccount(accountId);
for (final VolumeVO volume : volumes) {
if (!volume.getState().equals(Volume.State.Destroy)) {
try {
volumeService.deleteVolume(volume.getId(), caller);
} catch (final Exception ex) {
s_logger.warn("Failed to cleanup volumes as a part of account id=" + accountId + " cleanup due to Exception: ", ex);
accountCleanupNeeded = true;
}
}
}
// delete remote access vpns and associated users
final List<RemoteAccessVpnVO> remoteAccessVpns = _remoteAccessVpnDao.findByAccount(accountId);
final List<VpnUserVO> vpnUsers = _vpnUser.listByAccount(accountId);
for (final VpnUserVO vpnUser : vpnUsers) {
_remoteAccessVpnMgr.removeVpnUser(accountId, vpnUser.getUsername(), caller);
}
try {
for (final RemoteAccessVpnVO vpn : remoteAccessVpns) {
_remoteAccessVpnMgr.destroyRemoteAccessVpnForIp(vpn.getServerAddressId(), caller);
}
} catch (final ResourceUnavailableException ex) {
s_logger.warn("Failed to cleanup remote access vpn resources as a part of account id=" + accountId + " cleanup due to Exception: ", ex);
accountCleanupNeeded = true;
}
// Cleanup affinity groups
final int numAGRemoved = _affinityGroupDao.removeByAccountId(accountId);
s_logger.info("deleteAccount: Deleted " + numAGRemoved + " affinity groups for account " + accountId);
// Delete all the networks
boolean networksDeleted = true;
s_logger.debug("Deleting networks for account " + account.getId());
final List<NetworkVO> networks = _networkDao.listByOwner(accountId);
if (networks != null) {
for (final NetworkVO network : networks) {
final ReservationContext context = new ReservationContextImpl(null, null, getActiveUser(callerUserId), caller);
if (!_networkMgr.destroyNetwork(network.getId(), context, false)) {
s_logger.warn("Unable to destroy network " + network + " as a part of account id=" + accountId + " cleanup.");
accountCleanupNeeded = true;
networksDeleted = false;
} else {
s_logger.debug("Network " + network.getId() + " successfully deleted as a part of account id=" + accountId + " cleanup.");
}
}
}
// Delete all VPCs
boolean vpcsDeleted = true;
s_logger.debug("Deleting vpcs for account " + account.getId());
final List<? extends Vpc> vpcs = _vpcMgr.getVpcsForAccount(account.getId());
for (final Vpc vpc : vpcs) {
if (!_vpcMgr.destroyVpc(vpc, caller, callerUserId)) {
s_logger.warn("Unable to destroy VPC " + vpc + " as a part of account id=" + accountId + " cleanup.");
accountCleanupNeeded = true;
vpcsDeleted = false;
} else {
s_logger.debug("VPC " + vpc.getId() + " successfully deleted as a part of account id=" + accountId + " cleanup.");
}
}
if (networksDeleted && vpcsDeleted) {
// release ip addresses belonging to the account
final List<? extends IpAddress> ipsToRelease = _ipAddressDao.listByAccount(accountId);
for (final IpAddress ip : ipsToRelease) {
s_logger.debug("Releasing ip " + ip + " as a part of account id=" + accountId + " cleanup");
if (!_ipAddrMgr.disassociatePublicIpAddress(ip.getId(), callerUserId, caller)) {
s_logger.warn("Failed to release ip address " + ip + " as a part of account id=" + accountId + " clenaup");
accountCleanupNeeded = true;
}
}
}
// Delete Site 2 Site VPN customer gateway
s_logger.debug("Deleting site-to-site VPN customer gateways for account " + accountId);
if (!_vpnMgr.deleteCustomerGatewayByAccount(accountId)) {
s_logger.warn("Fail to delete site-to-site VPN customer gateways for account " + accountId);
}
// up successfully
if (networksDeleted) {
if (!_configMgr.releaseAccountSpecificVirtualRanges(accountId)) {
accountCleanupNeeded = true;
} else {
s_logger.debug("Account specific Virtual IP ranges " + " are successfully released as a part of account id=" + accountId + " cleanup.");
}
}
// release account specific guest vlans
final List<AccountGuestVlanMapVO> maps = _accountGuestVlanMapDao.listAccountGuestVlanMapsByAccount(accountId);
for (final AccountGuestVlanMapVO map : maps) {
_dataCenterVnetDao.releaseDedicatedGuestVlans(map.getId());
}
final int vlansReleased = _accountGuestVlanMapDao.removeByAccountId(accountId);
s_logger.info("deleteAccount: Released " + vlansReleased + " dedicated guest vlan ranges from account " + accountId);
// release dedication if any
final List<DedicatedResourceVO> dedicatedResources = _dedicatedDao.listByAccountId(accountId);
if (dedicatedResources != null && !dedicatedResources.isEmpty()) {
s_logger.debug("Releasing dedicated resources for account " + accountId);
for (final DedicatedResourceVO dr : dedicatedResources) {
if (!_dedicatedDao.remove(dr.getId())) {
s_logger.warn("Fail to release dedicated resources for account " + accountId);
}
}
}
// Updating and deleting the resourceLimit and resourceCount should be the last step in cleanupAccount
// process.
// Update resource count for this account and for parent domains.
final List<ResourceCountVO> resourceCounts = _resourceCountDao.listByOwnerId(accountId, ResourceOwnerType.Account);
for (final ResourceCountVO resourceCount : resourceCounts) {
_resourceLimitMgr.decrementResourceCount(accountId, resourceCount.getType(), resourceCount.getCount());
}
// Delete resource count and resource limits entries set for this account (if there are any).
_resourceCountDao.removeEntriesByOwner(accountId, ResourceOwnerType.Account);
_resourceLimitDao.removeEntriesByOwner(accountId, ResourceOwnerType.Account);
return true;
} catch (final Exception ex) {
s_logger.warn("Failed to cleanup account " + account + " due to ", ex);
accountCleanupNeeded = true;
return true;
} finally {
s_logger.info("Cleanup for account " + account.getId() + (accountCleanupNeeded ? " is needed." : " is not needed."));
if (accountCleanupNeeded) {
_accountDao.markForCleanup(accountId);
} else {
account.setNeedsCleanup(false);
_accountDao.update(accountId, account);
}
}
}
use of com.cloud.network.VpnUserVO in project cloudstack by apache.
the class RemoteAccessVpnManagerImpl method applyVpnUsers.
@DB
@Override
public boolean applyVpnUsers(long vpnOwnerId, String userName, boolean forRemove) throws ResourceUnavailableException {
Account caller = CallContext.current().getCallingAccount();
Account owner = _accountDao.findById(vpnOwnerId);
_accountMgr.checkAccess(caller, null, true, owner);
s_logger.debug(String.format("Applying VPN users for %s.", owner.toString()));
List<RemoteAccessVpnVO> vpns = getValidRemoteAccessVpnForAccount(vpnOwnerId);
if (CollectionUtils.isEmpty(vpns)) {
if (forRemove) {
return removeVpnUserWithoutRemoteAccessVpn(vpnOwnerId, userName);
}
s_logger.warn(String.format("Unable to apply VPN user due to there are no remote access VPNs configured on %s to apply VPN user.", owner.toString()));
return true;
}
RemoteAccessVpnVO vpnTemp = null;
List<VpnUserVO> users = _vpnUsersDao.listByAccount(vpnOwnerId);
for (VpnUserVO user : users) {
if (user.getState() == State.Active) {
user.setState(State.Add);
_vpnUsersDao.update(user.getId(), user);
}
}
boolean success = true;
Boolean[] finals = new Boolean[users.size()];
for (RemoteAccessVPNServiceProvider element : _vpnServiceProviders) {
s_logger.debug("Applying vpn access to " + element.getName());
for (RemoteAccessVpnVO vpn : vpns) {
try {
String[] results = element.applyVpnUsers(vpn, users);
if (results != null) {
int indexUser = -1;
for (String result : results) {
indexUser++;
if (indexUser == users.size()) {
indexUser = 0;
}
s_logger.debug("VPN User " + users.get(indexUser) + (result == null ? " is set on " : (" couldn't be set due to " + result) + " on ") + vpn.getUuid());
if (result == null) {
if (finals[indexUser] == null) {
finals[indexUser] = true;
}
} else {
finals[indexUser] = false;
success = false;
vpnTemp = vpn;
}
}
}
} catch (ResourceUnavailableException e) {
s_logger.warn(String.format("Unable to apply VPN users [%s] due to [%s].", users.stream().map(user -> user.toString()).collect(Collectors.joining(", ")), e.getMessage()), e);
success = false;
vpnTemp = vpn;
for (int i = 0; i < finals.length; i++) {
finals[i] = false;
}
}
}
}
for (int i = 0; i < finals.length; i++) {
final VpnUserVO user = users.get(i);
if (finals[i]) {
if (user.getState() == State.Add) {
user.setState(State.Active);
_vpnUsersDao.update(user.getId(), user);
} else if (user.getState() == State.Revoke) {
_vpnUsersDao.remove(user.getId());
}
} else {
if (user.getState() == State.Add && (user.getUsername()).equals(userName)) {
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
_vpnUsersDao.remove(user.getId());
UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VPN_USER_REMOVE, user.getAccountId(), 0, user.getId(), user.getUsername(), user.getClass().getName(), user.getUuid());
}
});
}
s_logger.warn(String.format("Failed to apply VPN for %s.", user.toString()));
}
}
if (!success) {
throw new ResourceUnavailableException("Failed add vpn user due to Resource unavailable ", RemoteAccessVPNServiceProvider.class, vpnTemp.getId());
}
return success;
}
use of com.cloud.network.VpnUserVO in project cloudstack by apache.
the class CommandSetupHelper method createApplyVpnCommands.
public void createApplyVpnCommands(final boolean isCreate, final RemoteAccessVpn vpn, final VirtualRouter router, final Commands cmds) {
final List<VpnUserVO> vpnUsers = _vpnUsersDao.listByAccount(vpn.getAccountId());
createApplyVpnUsersCommand(vpnUsers, router, cmds);
final IpAddress ip = _networkModel.getIp(vpn.getServerAddressId());
// This block is needed due to the line 206 of the
// RemoteAccessVpnManagenerImpl:
// TODO: assumes one virtual network / domr per account per zone
final String cidr;
final Network network = _networkDao.findById(vpn.getNetworkId());
if (network == null) {
final Vpc vpc = _vpcDao.findById(vpn.getVpcId());
cidr = vpc.getCidr();
} else {
cidr = network.getCidr();
}
final RemoteAccessVpnCfgCommand startVpnCmd = new RemoteAccessVpnCfgCommand(isCreate, ip.getAddress().addr(), vpn.getLocalIp(), vpn.getIpRange(), vpn.getIpsecPresharedKey(), vpn.getVpcId() != null);
startVpnCmd.setLocalCidr(cidr);
startVpnCmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, _routerControlHelper.getRouterControlIp(router.getId()));
startVpnCmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());
final DataCenterVO dcVo = _dcDao.findById(router.getDataCenterId());
startVpnCmd.setAccessDetail(NetworkElementCommand.ZONE_NETWORK_TYPE, dcVo.getNetworkType().toString());
cmds.addCommand("startVpn", startVpnCmd);
}
use of com.cloud.network.VpnUserVO in project cloudstack by apache.
the class UsageServiceImpl method getUsageRecords.
@Override
public Pair<List<? extends Usage>, Integer> getUsageRecords(ListUsageRecordsCmd cmd) {
Long accountId = cmd.getAccountId();
Long domainId = cmd.getDomainId();
String accountName = cmd.getAccountName();
Account caller = CallContext.current().getCallingAccount();
Long usageType = cmd.getUsageType();
Long projectId = cmd.getProjectId();
String usageId = cmd.getUsageId();
boolean projectRequested = false;
if (projectId != null) {
if (accountId != null) {
throw new InvalidParameterValueException("Projectid and accountId can't be specified together");
}
accountId = getAccountIdFromProject(projectId);
projectRequested = true;
} else if ((accountId == null) && (StringUtils.isNotBlank(accountName)) && (domainId != null)) {
accountId = getAccountIdFromDomainPlusName(domainId, accountName, caller);
}
boolean ignoreAccountId = false;
boolean isDomainAdmin = _accountService.isDomainAdmin(caller.getId());
boolean isNormalUser = _accountService.isNormalUser(caller.getId());
// If accountId couldn't be found using project or accountName and domainId, get it from userContext
if (accountId == null) {
accountId = caller.getId();
// List records for all the accounts if the caller account is of type admin.
// If account_id or account_name is explicitly mentioned, list records for the specified account only even if the caller is of type admin
ignoreAccountId = _accountService.isRootAdmin(caller.getId());
s_logger.debug("Account details not available. Using userContext accountId: " + accountId);
}
// Check if a domain admin is allowed to access the requested domain id
domainId = getDomainScopeForQuery(cmd, accountId, domainId, caller, isDomainAdmin);
// By default users do not have access to this API.
// Adding checks here in case someone changes the default access.
checkUserAccess(cmd, accountId, caller, isNormalUser);
Date startDate = cmd.getStartDate();
Date endDate = cmd.getEndDate();
if (startDate.after(endDate)) {
throw new InvalidParameterValueException("Incorrect Date Range. Start date: " + startDate + " is after end date:" + endDate);
}
TimeZone usageTZ = getUsageTimezone();
Date adjustedStartDate = computeAdjustedTime(startDate, usageTZ);
Date adjustedEndDate = computeAdjustedTime(endDate, usageTZ);
if (s_logger.isDebugEnabled()) {
s_logger.debug("getting usage records for account: " + accountId + ", domainId: " + domainId + ", between " + adjustedStartDate + " and " + adjustedEndDate + ", using pageSize: " + cmd.getPageSizeVal() + " and startIndex: " + cmd.getStartIndex());
}
Filter usageFilter = new Filter(UsageVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal());
SearchCriteria<UsageVO> sc = _usageDao.createSearchCriteria();
if (accountId != -1 && accountId != Account.ACCOUNT_ID_SYSTEM && !ignoreAccountId) {
if (!cmd.isRecursive() || cmd.getAccountId() != null || projectRequested) {
sc.addAnd("accountId", SearchCriteria.Op.EQ, accountId);
}
}
if (domainId != null) {
if (cmd.isRecursive()) {
SearchCriteria<DomainVO> sdc = _domainDao.createSearchCriteria();
sdc.addOr("path", SearchCriteria.Op.LIKE, _domainDao.findById(domainId).getPath() + "%");
List<DomainVO> domains = _domainDao.search(sdc, null);
List<Long> domainIds = new ArrayList<Long>();
for (DomainVO domain : domains) {
domainIds.add(domain.getId());
}
sc.addAnd("domainId", SearchCriteria.Op.IN, domainIds.toArray());
} else {
sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId);
}
}
if (usageType != null) {
sc.addAnd("usageType", SearchCriteria.Op.EQ, usageType);
}
if (usageId != null) {
if (usageType == null) {
throw new InvalidParameterValueException("Usageid must be specified together with usageType");
}
Long usageDbId = null;
switch(usageType.intValue()) {
case UsageTypes.NETWORK_BYTES_RECEIVED:
case UsageTypes.NETWORK_BYTES_SENT:
case UsageTypes.RUNNING_VM:
case UsageTypes.ALLOCATED_VM:
case UsageTypes.VM_SNAPSHOT:
case UsageTypes.BACKUP:
VMInstanceVO vm = _vmDao.findByUuidIncludingRemoved(usageId);
if (vm != null) {
usageDbId = vm.getId();
}
if (vm == null && (usageType == UsageTypes.NETWORK_BYTES_RECEIVED || usageType == UsageTypes.NETWORK_BYTES_SENT)) {
HostVO host = _hostDao.findByUuidIncludingRemoved(usageId);
if (host != null) {
usageDbId = host.getId();
}
}
break;
case UsageTypes.SNAPSHOT:
SnapshotVO snap = _snapshotDao.findByUuidIncludingRemoved(usageId);
if (snap != null) {
usageDbId = snap.getId();
}
break;
case UsageTypes.TEMPLATE:
case UsageTypes.ISO:
VMTemplateVO tmpl = _vmTemplateDao.findByUuidIncludingRemoved(usageId);
if (tmpl != null) {
usageDbId = tmpl.getId();
}
break;
case UsageTypes.LOAD_BALANCER_POLICY:
LoadBalancerVO lb = _lbDao.findByUuidIncludingRemoved(usageId);
if (lb != null) {
usageDbId = lb.getId();
}
break;
case UsageTypes.PORT_FORWARDING_RULE:
PortForwardingRuleVO pf = _pfDao.findByUuidIncludingRemoved(usageId);
if (pf != null) {
usageDbId = pf.getId();
}
break;
case UsageTypes.VOLUME:
case UsageTypes.VM_DISK_IO_READ:
case UsageTypes.VM_DISK_IO_WRITE:
case UsageTypes.VM_DISK_BYTES_READ:
case UsageTypes.VM_DISK_BYTES_WRITE:
VolumeVO volume = _volumeDao.findByUuidIncludingRemoved(usageId);
if (volume != null) {
usageDbId = volume.getId();
}
break;
case UsageTypes.VPN_USERS:
VpnUserVO vpnUser = _vpnUserDao.findByUuidIncludingRemoved(usageId);
if (vpnUser != null) {
usageDbId = vpnUser.getId();
}
break;
case UsageTypes.SECURITY_GROUP:
SecurityGroupVO sg = _sgDao.findByUuidIncludingRemoved(usageId);
if (sg != null) {
usageDbId = sg.getId();
}
break;
case UsageTypes.IP_ADDRESS:
IPAddressVO ip = _ipDao.findByUuidIncludingRemoved(usageId);
if (ip != null) {
usageDbId = ip.getId();
}
break;
default:
break;
}
if (usageDbId != null) {
sc.addAnd("usageId", SearchCriteria.Op.EQ, usageDbId);
} else {
// return an empty list if usageId was not found
return new Pair<List<? extends Usage>, Integer>(new ArrayList<Usage>(), new Integer(0));
}
}
// Filter out hidden usages
sc.addAnd("isHidden", SearchCriteria.Op.EQ, false);
if ((adjustedStartDate != null) && (adjustedEndDate != null) && adjustedStartDate.before(adjustedEndDate)) {
sc.addAnd("startDate", SearchCriteria.Op.BETWEEN, adjustedStartDate, adjustedEndDate);
sc.addAnd("endDate", SearchCriteria.Op.BETWEEN, adjustedStartDate, adjustedEndDate);
} else {
// return an empty list if we fail to validate the dates
return new Pair<List<? extends Usage>, Integer>(new ArrayList<Usage>(), new Integer(0));
}
Pair<List<UsageVO>, Integer> usageRecords = null;
TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.USAGE_DB);
try {
usageRecords = _usageDao.searchAndCountAllRecords(sc, usageFilter);
} finally {
txn.close();
// switch back to VMOPS_DB
TransactionLegacy swap = TransactionLegacy.open(TransactionLegacy.CLOUD_DB);
swap.close();
}
return new Pair<List<? extends Usage>, Integer>(usageRecords.first(), usageRecords.second());
}
Aggregations