use of com.cloud.network.dao.LoadBalancerVO 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());
}
use of com.cloud.network.dao.LoadBalancerVO in project cloudstack by apache.
the class VirtualNetworkApplianceManagerImpl method updateWithLbRules.
private void updateWithLbRules(final DomainRouterJoinVO routerJoinVO, final StringBuilder loadBalancingData) {
List<? extends FirewallRuleVO> loadBalancerVOs = this.getLBRules(routerJoinVO);
for (FirewallRuleVO firewallRuleVO : loadBalancerVOs) {
List<LoadBalancerVMMapVO> vmMapVOs = _loadBalancerVMMapDao.listByLoadBalancerId(firewallRuleVO.getId(), false);
if (vmMapVOs.size() > 0) {
final NetworkOffering offering = _networkOfferingDao.findById(_networkDao.findById(routerJoinVO.getNetworkId()).getNetworkOfferingId());
if (offering.getConcurrentConnections() == null) {
loadBalancingData.append("maxconn=").append(_configDao.getValue(Config.NetworkLBHaproxyMaxConn.key()));
} else {
loadBalancingData.append("maxconn=").append(offering.getConcurrentConnections().toString());
}
loadBalancingData.append(",sourcePortStart=").append(firewallRuleVO.getSourcePortStart()).append(",sourcePortEnd=").append(firewallRuleVO.getSourcePortEnd());
if (firewallRuleVO instanceof LoadBalancerVO) {
LoadBalancerVO loadBalancerVO = (LoadBalancerVO) firewallRuleVO;
loadBalancingData.append(",sourceIp=").append(_ipAddressDao.findById(loadBalancerVO.getSourceIpAddressId()).getAddress().toString()).append(",destPortStart=").append(loadBalancerVO.getDefaultPortStart()).append(",destPortEnd=").append(loadBalancerVO.getDefaultPortEnd()).append(",algorithm=").append(loadBalancerVO.getAlgorithm()).append(",protocol=").append(loadBalancerVO.getLbProtocol());
} else if (firewallRuleVO instanceof ApplicationLoadBalancerRuleVO) {
ApplicationLoadBalancerRuleVO appLoadBalancerVO = (ApplicationLoadBalancerRuleVO) firewallRuleVO;
loadBalancingData.append(",sourceIp=").append(appLoadBalancerVO.getSourceIp()).append(",destPortStart=").append(appLoadBalancerVO.getDefaultPortStart()).append(",destPortEnd=").append(appLoadBalancerVO.getDefaultPortEnd()).append(",algorithm=").append(appLoadBalancerVO.getAlgorithm()).append(",protocol=").append(appLoadBalancerVO.getLbProtocol());
}
loadBalancingData.append(",stickiness=").append(getStickinessPolicies(firewallRuleVO.getId()));
loadBalancingData.append(",keepAliveEnabled=").append(offering.isKeepAliveEnabled()).append(",vmIps=");
for (LoadBalancerVMMapVO vmMapVO : vmMapVOs) {
loadBalancingData.append(vmMapVO.getInstanceIp()).append(" ");
}
loadBalancingData.setCharAt(loadBalancingData.length() - 1, ';');
}
}
}
use of com.cloud.network.dao.LoadBalancerVO in project cloudstack by apache.
the class LoadBalancingRulesManagerImpl method assignCertToLoadBalancer.
@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_LB_CERT_ASSIGN, eventDescription = "assigning certificate to load balancer", async = true)
public boolean assignCertToLoadBalancer(long lbRuleId, Long certId) {
CallContext caller = CallContext.current();
LoadBalancerVO loadBalancer = _lbDao.findById(Long.valueOf(lbRuleId));
if (loadBalancer == null) {
throw new InvalidParameterException("Invalid load balancer id: " + lbRuleId);
}
SslCertVO certVO = _entityMgr.findById(SslCertVO.class, certId);
if (certVO == null) {
throw new InvalidParameterException("Invalid certificate id: " + certId);
}
_accountMgr.checkAccess(caller.getCallingAccount(), null, true, loadBalancer);
// check if LB and Cert belong to the same account
if (loadBalancer.getAccountId() != certVO.getAccountId()) {
throw new InvalidParameterValueException("Access denied for account " + certVO.getAccountId());
}
String capability = getLBCapability(loadBalancer.getNetworkId(), Capability.SslTermination.getName());
if (capability == null) {
throw new InvalidParameterValueException("Ssl termination not supported by the loadbalancer");
}
// check if the lb is already bound
LoadBalancerCertMapVO certMapRule = _lbCertMapDao.findByLbRuleId(loadBalancer.getId());
if (certMapRule != null)
throw new InvalidParameterValueException("Another certificate is already bound to the LB");
// check for correct port
if (loadBalancer.getLbProtocol() == null || !(loadBalancer.getLbProtocol().equals(NetUtils.SSL_PROTO)))
throw new InvalidParameterValueException("Bad LB protocol: Expected ssl got " + loadBalancer.getLbProtocol());
boolean success = false;
FirewallRule.State backupState = loadBalancer.getState();
try {
loadBalancer.setState(FirewallRule.State.Add);
_lbDao.persist(loadBalancer);
LoadBalancerCertMapVO certMap = new LoadBalancerCertMapVO(lbRuleId, certId, false);
_lbCertMapDao.persist(certMap);
applyLoadBalancerConfig(loadBalancer.getId());
success = true;
} catch (ResourceUnavailableException e) {
if (isRollBackAllowedForProvider(loadBalancer)) {
loadBalancer.setState(backupState);
_lbDao.persist(loadBalancer);
LoadBalancerCertMapVO certMap = _lbCertMapDao.findByLbRuleId(lbRuleId);
_lbCertMapDao.remove(certMap.getId());
s_logger.debug("LB Rollback rule id: " + loadBalancer.getId() + " while adding cert");
}
s_logger.warn("Unable to apply the load balancer config because resource is unavaliable.", e);
}
return success;
}
use of com.cloud.network.dao.LoadBalancerVO in project cloudstack by apache.
the class LoadBalancingRulesManagerImpl method applyLBHealthCheckPolicy.
@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_LB_HEALTHCHECKPOLICY_CREATE, eventDescription = "Apply HealthCheckPolicy to load balancer ", async = true)
public boolean applyLBHealthCheckPolicy(CreateLBHealthCheckPolicyCmd cmd) {
boolean success = true;
LoadBalancerVO loadBalancer = _lbDao.findById(cmd.getLbRuleId());
if (loadBalancer == null) {
throw new InvalidParameterException("Invalid Load balancer Id:" + cmd.getLbRuleId());
}
_accountMgr.checkAccess(CallContext.current().getCallingAccount(), null, true, loadBalancer);
FirewallRule.State backupState = loadBalancer.getState();
loadBalancer.setState(FirewallRule.State.Add);
_lbDao.persist(loadBalancer);
try {
applyLoadBalancerConfig(cmd.getLbRuleId());
} catch (ResourceUnavailableException e) {
s_logger.warn("Unable to apply healthcheck policy to the lb rule: " + cmd.getLbRuleId() + " because resource is unavaliable:", e);
if (isRollBackAllowedForProvider(loadBalancer)) {
loadBalancer.setState(backupState);
_lbDao.persist(loadBalancer);
s_logger.debug("LB Rollback rule id: " + loadBalancer.getId() + " lb state rolback while creating healthcheck policy");
}
deleteLBHealthCheckPolicy(cmd.getEntityId(), false);
success = false;
}
return success;
}
use of com.cloud.network.dao.LoadBalancerVO in project cloudstack by apache.
the class LoadBalancingRulesManagerImpl method getLbInstances.
@Override
public Map<Ip, UserVm> getLbInstances(long lbId) {
Map<Ip, UserVm> dstList = new HashMap<Ip, UserVm>();
List<LoadBalancerVMMapVO> lbVmMaps = _lb2VmMapDao.listByLoadBalancerId(lbId);
LoadBalancerVO lb = _lbDao.findById(lbId);
for (LoadBalancerVMMapVO lbVmMap : lbVmMaps) {
UserVm vm = _vmDao.findById(lbVmMap.getInstanceId());
Nic nic = _nicDao.findByInstanceIdAndNetworkIdIncludingRemoved(lb.getNetworkId(), vm.getId());
Ip ip = new Ip(nic.getIPv4Address());
dstList.put(ip, vm);
}
return dstList;
}
Aggregations