use of com.cloud.network.VpnUserVO in project cloudstack by apache.
the class UsageServiceImpl method getUsageRecords.
@Override
public Pair<List<? extends Usage>, Integer> getUsageRecords(GetUsageRecordsCmd cmd) {
Long accountId = cmd.getAccountId();
Long domainId = cmd.getDomainId();
String accountName = cmd.getAccountName();
Account userAccount = null;
Account caller = CallContext.current().getCallingAccount();
Long usageType = cmd.getUsageType();
Long projectId = cmd.getProjectId();
String usageId = cmd.getUsageId();
if (projectId != null) {
if (accountId != null) {
throw new InvalidParameterValueException("Projectid and accountId can't be specified together");
}
Project project = _projectMgr.getProject(projectId);
if (project == null) {
throw new InvalidParameterValueException("Unable to find project by id " + projectId);
}
accountId = project.getProjectAccountId();
}
//if accountId is not specified, use accountName and domainId
if ((accountId == null) && (accountName != null) && (domainId != null)) {
if (_domainDao.isChildDomain(caller.getDomainId(), domainId)) {
Filter filter = new Filter(AccountVO.class, "id", Boolean.FALSE, null, null);
List<AccountVO> accounts = _accountDao.listAccounts(accountName, domainId, filter);
if (accounts.size() > 0) {
userAccount = accounts.get(0);
}
if (userAccount != null) {
accountId = userAccount.getId();
} else {
throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain " + domainId);
}
} else {
throw new PermissionDeniedException("Invalid Domain Id or Account");
}
}
boolean isAdmin = false;
boolean isDomainAdmin = false;
//If accountId couldn't be found using accountName and domainId, get it from userContext
if (accountId == null) {
accountId = caller.getId();
//If account_id or account_name is explicitly mentioned, list records for the specified account only even if the caller is of type admin
if (_accountService.isRootAdmin(caller.getId())) {
isAdmin = true;
} else if (_accountService.isDomainAdmin(caller.getId())) {
isDomainAdmin = true;
}
s_logger.debug("Account details not available. Using userContext accountId: " + accountId);
}
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 && !isAdmin && !isDomainAdmin) {
sc.addAnd("accountId", SearchCriteria.Op.EQ, accountId);
}
if (isDomainAdmin) {
SearchCriteria<DomainVO> sdc = _domainDao.createSearchCriteria();
sdc.addOr("path", SearchCriteria.Op.LIKE, _domainDao.findById(caller.getDomainId()).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());
}
if (domainId != null) {
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:
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));
}
}
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());
}
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 RemoteAccessVpnManagerImpl method applyVpnUsers.
@DB
@Override
public boolean applyVpnUsers(long vpnOwnerId, String userName) throws ResourceUnavailableException {
Account caller = CallContext.current().getCallingAccount();
Account owner = _accountDao.findById(vpnOwnerId);
_accountMgr.checkAccess(caller, null, true, owner);
s_logger.debug("Applying vpn users for " + owner);
List<RemoteAccessVpnVO> vpns = _remoteAccessVpnDao.findByAccount(vpnOwnerId);
RemoteAccessVpnVO vpnTemp = null;
List<VpnUserVO> users = _vpnUsersDao.listByAccount(vpnOwnerId);
//If user is in Active state, we still have to resend them therefore their status has to be Add
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 (int i = 0; i < results.length; i++) {
indexUser++;
if (indexUser == users.size()) {
// results on multiple VPC routers are combined in commit 13eb789, reset user index if one VR is done.
indexUser = 0;
}
s_logger.debug("VPN User " + users.get(indexUser) + (results[i] == null ? " is set on " : (" couldn't be set due to " + results[i]) + " on ") + vpn.getUuid());
if (results[i] == null) {
if (finals[indexUser] == null) {
finals[indexUser] = true;
}
} else {
finals[indexUser] = false;
success = false;
vpnTemp = vpn;
}
}
}
} catch (Exception e) {
s_logger.warn("Unable to apply vpn users ", 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("Failed to apply vpn for user " + user.getUsername() + ", accountId=" + user.getAccountId());
}
}
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 AccountManagerImpl method cleanupAccount.
protected boolean cleanupAccount(AccountVO account, long callerUserId, Account caller) {
long accountId = account.getId();
boolean accountCleanupNeeded = false;
try {
// cleanup the users from the account
List<UserVO> users = _userDao.listByAccount(accountId);
for (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 global load balancer rules for the account.
List<org.apache.cloudstack.region.gslb.GlobalLoadBalancerRuleVO> gslbRules = _gslbRuleDao.listByAccount(accountId);
if (gslbRules != null && !gslbRules.isEmpty()) {
_gslbService.revokeAllGslbRulesForAccount(caller, accountId);
}
// 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
List<InstanceGroupVO> groups = _vmGroupDao.listByAccountId(accountId);
for (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.
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
List<VMTemplateVO> userTemplates = _templateDao.listByAccountId(accountId);
boolean allTemplatesDeleted = true;
for (VMTemplateVO template : userTemplates) {
if (template.getRemoved() == null) {
try {
allTemplatesDeleted = _tmpltMgr.delete(callerUserId, template.getId(), null);
} catch (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
List<VMSnapshotVO> vmSnapshots = _vmSnapshotDao.listByAccountId(Long.valueOf(accountId));
for (VMSnapshot vmSnapshot : vmSnapshots) {
try {
_vmSnapshotMgr.deleteVMSnapshot(vmSnapshot.getId());
} catch (Exception e) {
s_logger.debug("Failed to cleanup vm snapshot " + vmSnapshot.getId() + " due to " + e.toString());
}
}
// Destroy the account's VMs
List<UserVmVO> vms = _userVmDao.listByAccountId(accountId);
if (s_logger.isDebugEnabled()) {
s_logger.debug("Expunging # of vms (accountId=" + accountId + "): " + vms.size());
}
for (UserVmVO vm : vms) {
if (vm.getState() != VirtualMachine.State.Destroyed && vm.getState() != VirtualMachine.State.Expunging) {
try {
_vmMgr.destroyVm(vm.getId(), false);
} catch (Exception e) {
e.printStackTrace();
s_logger.warn("Failed destroying instance " + vm.getUuid() + " as part of account deletion.");
}
}
// should pass in order to perform further cleanup
if (!_vmMgr.expunge(vm, callerUserId, caller)) {
s_logger.error("Unable to expunge vm: " + vm.getId());
accountCleanupNeeded = true;
}
}
// Mark the account's volumes as destroyed
List<VolumeVO> volumes = _volumeDao.findDetachedByAccount(accountId);
for (VolumeVO volume : volumes) {
if (!volume.getState().equals(Volume.State.Destroy)) {
try {
volumeService.deleteVolume(volume.getId(), caller);
} catch (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
List<RemoteAccessVpnVO> remoteAccessVpns = _remoteAccessVpnDao.findByAccount(accountId);
List<VpnUserVO> vpnUsers = _vpnUser.listByAccount(accountId);
for (VpnUserVO vpnUser : vpnUsers) {
_remoteAccessVpnMgr.removeVpnUser(accountId, vpnUser.getUsername(), caller);
}
try {
for (RemoteAccessVpnVO vpn : remoteAccessVpns) {
_remoteAccessVpnMgr.destroyRemoteAccessVpnForIp(vpn.getServerAddressId(), caller, false);
}
} catch (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 security groups
int numRemoved = _securityGroupDao.removeByAccountId(accountId);
s_logger.info("deleteAccount: Deleted " + numRemoved + " network groups for account " + accountId);
// Cleanup affinity groups
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());
List<NetworkVO> networks = _networkDao.listByOwner(accountId);
if (networks != null) {
for (NetworkVO network : networks) {
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());
List<? extends Vpc> vpcs = _vpcMgr.getVpcsForAccount(account.getId());
for (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
List<? extends IpAddress> ipsToRelease = _ipAddressDao.listByAccount(accountId);
for (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);
}
// Delete autoscale resources if any
try {
_autoscaleMgr.cleanUpAutoScaleResources(accountId);
} catch (CloudRuntimeException ex) {
s_logger.warn("Failed to cleanup AutoScale resources as a part of account id=" + accountId + " cleanup due to exception:", ex);
accountCleanupNeeded = true;
}
// 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
List<AccountGuestVlanMapVO> maps = _accountGuestVlanMapDao.listAccountGuestVlanMapsByAccount(accountId);
for (AccountGuestVlanMapVO map : maps) {
_dataCenterVnetDao.releaseDedicatedGuestVlans(map.getId());
}
int vlansReleased = _accountGuestVlanMapDao.removeByAccountId(accountId);
s_logger.info("deleteAccount: Released " + vlansReleased + " dedicated guest vlan ranges from account " + accountId);
// release account specific acquired portable IP's. Since all the portable IP's must have been already
// disassociated with VPC/guest network (due to deletion), so just mark portable IP as free.
List<? extends IpAddress> ipsToRelease = _ipAddressDao.listByAccount(accountId);
for (IpAddress ip : ipsToRelease) {
if (ip.isPortable()) {
s_logger.debug("Releasing portable ip " + ip + " as a part of account id=" + accountId + " cleanup");
_ipAddrMgr.releasePortableIpAddress(ip.getId());
}
}
// release dedication if any
List<DedicatedResourceVO> dedicatedResources = _dedicatedDao.listByAccountId(accountId);
if (dedicatedResources != null && !dedicatedResources.isEmpty()) {
s_logger.debug("Releasing dedicated resources for account " + accountId);
for (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.
List<ResourceCountVO> resourceCounts = _resourceCountDao.listByOwnerId(accountId, ResourceOwnerType.Account);
for (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 (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);
}
}
}
Aggregations