@Override public void updateUserStats(List<UserStatisticsVO> userStats) { Transaction txn = Transaction.currentTxn(); try { txn.start(); String sql = UPDATE_USER_STATS; PreparedStatement pstmt = null; pstmt = txn.prepareAutoCloseStatement( sql); // in reality I just want CLOUD_USAGE dataSource connection for (UserStatisticsVO userStat : userStats) { pstmt.setLong(1, userStat.getNetBytesReceived()); pstmt.setLong(2, userStat.getNetBytesSent()); pstmt.setLong(3, userStat.getCurrentBytesReceived()); pstmt.setLong(4, userStat.getCurrentBytesSent()); pstmt.setLong(5, userStat.getAggBytesReceived()); pstmt.setLong(6, userStat.getAggBytesSent()); pstmt.setLong(7, userStat.getId()); pstmt.addBatch(); } pstmt.executeBatch(); txn.commit(); } catch (Exception ex) { txn.rollback(); s_logger.error("error saving user stats to cloud_usage db", ex); throw new CloudRuntimeException(ex.getMessage()); } }
@Override @DB public long addTemplateToZone(VMTemplateVO tmplt, long zoneId) { Transaction txn = Transaction.currentTxn(); txn.start(); VMTemplateVO tmplt2 = findById(tmplt.getId()); if (tmplt2 == null) { if (persist(tmplt) == null) { throw new CloudRuntimeException("Failed to persist the template " + tmplt); } if (tmplt.getDetails() != null) { _templateDetailsDao.persist(tmplt.getId(), tmplt.getDetails()); } } VMTemplateZoneVO tmpltZoneVO = _templateZoneDao.findByZoneTemplate(zoneId, tmplt.getId()); if (tmpltZoneVO == null) { tmpltZoneVO = new VMTemplateZoneVO(zoneId, tmplt.getId(), new Date()); _templateZoneDao.persist(tmpltZoneVO); } else { tmpltZoneVO.setRemoved(null); tmpltZoneVO.setLastUpdated(new Date()); _templateZoneDao.update(tmpltZoneVO.getId(), tmpltZoneVO); } txn.commit(); return tmplt.getId(); }
@Override public void updateAccounts(List<AccountVO> accounts) { Transaction txn = Transaction.currentTxn(); try { txn.start(); String sql = UPDATE_ACCOUNT; PreparedStatement pstmt = null; pstmt = txn.prepareAutoCloseStatement( sql); // in reality I just want CLOUD_USAGE dataSource connection for (AccountVO acct : accounts) { pstmt.setString(1, acct.getAccountName()); Date removed = acct.getRemoved(); if (removed == null) { pstmt.setString(2, null); } else { pstmt.setString( 2, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), acct.getRemoved())); } pstmt.setLong(3, acct.getId()); pstmt.addBatch(); } pstmt.executeBatch(); txn.commit(); } catch (Exception ex) { txn.rollback(); s_logger.error("error saving account to cloud_usage db", ex); throw new CloudRuntimeException(ex.getMessage()); } }
@Override @DB public boolean prepare( Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { Host host = dest.getHost(); if (host == null || host.getHypervisorType() != HypervisorType.BareMetal) { return true; } Transaction txn = Transaction.currentTxn(); txn.start(); nic.setMacAddress(host.getPrivateMacAddress()); NicVO vo = _nicDao.findById(nic.getId()); assert vo != null : "Where ths nic " + nic.getId() + " going???"; vo.setMacAddress(nic.getMacAddress()); _nicDao.update(vo.getId(), vo); txn.commit(); s_logger.debug( "Bare Metal changes mac address of nic " + nic.getId() + " to " + nic.getMacAddress()); return _dhcpMgr.addVirtualMachineIntoNetwork(network, nic, vm, dest, context); }
@Override public void saveUsageNetworks(List<UsageNetworkVO> usageNetworks) { Transaction txn = Transaction.currentTxn(); try { txn.start(); String sql = INSERT_USAGE_NETWORK; PreparedStatement pstmt = null; pstmt = txn.prepareAutoCloseStatement( sql); // in reality I just want CLOUD_USAGE dataSource connection for (UsageNetworkVO usageNetwork : usageNetworks) { pstmt.setLong(1, usageNetwork.getAccountId()); pstmt.setLong(2, usageNetwork.getZoneId()); pstmt.setLong(3, usageNetwork.getHostId()); pstmt.setString(4, usageNetwork.getHostType()); pstmt.setLong(5, usageNetwork.getNetworkId()); pstmt.setLong(6, usageNetwork.getBytesSent()); pstmt.setLong(7, usageNetwork.getBytesReceived()); pstmt.setLong(8, usageNetwork.getAggBytesReceived()); pstmt.setLong(9, usageNetwork.getAggBytesSent()); pstmt.setLong(10, usageNetwork.getEventTimeMillis()); pstmt.addBatch(); } pstmt.executeBatch(); txn.commit(); } catch (Exception ex) { txn.rollback(); s_logger.error("error saving usage_network to cloud_usage db", ex); throw new CloudRuntimeException(ex.getMessage()); } }
@Override @DB public RemoteAccessVpnVO startRemoteAccessVpn(long vpnId, boolean openFirewall) throws ResourceUnavailableException { Account caller = UserContext.current().getCaller(); RemoteAccessVpnVO vpn = _remoteAccessVpnDao.findById(vpnId); if (vpn == null) { throw new InvalidParameterValueException("Unable to find your vpn: " + vpnId); } _accountMgr.checkAccess(caller, null, true, vpn); Network network = _networkMgr.getNetwork(vpn.getNetworkId()); boolean started = false; try { boolean firewallOpened = true; if (openFirewall) { firewallOpened = _firewallMgr.applyIngressFirewallRules(vpn.getServerAddressId(), caller); } if (firewallOpened) { for (RemoteAccessVPNServiceProvider element : _vpnServiceProviders) { if (element.startVpn(network, vpn)) { started = true; break; } } } return vpn; } finally { if (started) { Transaction txn = Transaction.currentTxn(); txn.start(); vpn.setState(RemoteAccessVpn.State.Running); _remoteAccessVpnDao.update(vpn.getServerAddressId(), vpn); // Start billing of existing VPN users in ADD and Active state List<VpnUserVO> vpnUsers = _vpnUsersDao.listByAccount(vpn.getAccountId()); for (VpnUserVO user : vpnUsers) { if (user.getState() != VpnUser.State.Revoke) { UsageEventUtils.publishUsageEvent( EventTypes.EVENT_VPN_USER_ADD, user.getAccountId(), 0, user.getId(), user.getUsername(), user.getClass().getName(), user.getUuid()); } } txn.commit(); } } }
@DB protected boolean applyLoadBalancerRules(List<LoadBalancerVO> lbs) throws ResourceUnavailableException { Transaction txn = Transaction.currentTxn(); List<LoadBalancingRule> rules = new ArrayList<LoadBalancingRule>(); for (LoadBalancerVO lb : lbs) { List<LbDestination> dstList = getExistingDestinations(lb.getId()); LoadBalancingRule loadBalancing = new LoadBalancingRule(lb, dstList); rules.add(loadBalancing); } if (!_networkMgr.applyRules(rules, false)) { s_logger.debug("LB rules are not completely applied"); return false; } for (LoadBalancerVO lb : lbs) { txn.start(); if (lb.getState() == FirewallRule.State.Revoke) { _lbDao.remove(lb.getId()); s_logger.warn("LB " + lb.getId() + " is successfully removed"); } else if (lb.getState() == FirewallRule.State.Add) { lb.setState(FirewallRule.State.Active); s_logger.warn("LB rule " + lb.getId() + " state is set to Active"); _lbDao.persist(lb); } // remove LB-Vm mappings that were state to revoke List<LoadBalancerVMMapVO> lbVmMaps = _lb2VmMapDao.listByLoadBalancerId(lb.getId(), true); List<Long> instanceIds = new ArrayList<Long>(); for (LoadBalancerVMMapVO lbVmMap : lbVmMaps) { instanceIds.add(lbVmMap.getInstanceId()); } if (!instanceIds.isEmpty()) { _lb2VmMapDao.remove(lb.getId(), instanceIds, null); s_logger.debug( "Load balancer rule id " + lb.getId() + " is removed for vms " + instanceIds); } if (_lb2VmMapDao.listByLoadBalancerId(lb.getId()).isEmpty()) { lb.setState(FirewallRule.State.Add); _lbDao.persist(lb); s_logger.debug( "LB rule " + lb.getId() + " state is set to Add as there are no more active LB-VM mappings"); } txn.commit(); } return true; }
@Override @DB public boolean addInstanceToGroups(final Long userVmId, final List<Long> groups) { if (!isVmSecurityGroupEnabled(userVmId)) { s_logger.warn( "User vm " + userVmId + " is not security group enabled, can't add it to security group"); return false; } if (groups != null && !groups.isEmpty()) { final Transaction txn = Transaction.currentTxn(); txn.start(); UserVm userVm = _userVMDao.acquireInLockTable( userVmId); // ensures that duplicate entries are not created. List<SecurityGroupVO> sgs = new ArrayList<SecurityGroupVO>(); for (Long sgId : groups) { sgs.add(_securityGroupDao.findById(sgId)); } final Set<SecurityGroupVO> uniqueGroups = new TreeSet<SecurityGroupVO>(new SecurityGroupVOComparator()); uniqueGroups.addAll(sgs); if (userVm == null) { s_logger.warn("Failed to acquire lock on user vm id=" + userVmId); } try { for (SecurityGroupVO securityGroup : uniqueGroups) { // don't let the group be deleted from under us. SecurityGroupVO ngrpLock = _securityGroupDao.lockRow(securityGroup.getId(), false); if (ngrpLock == null) { s_logger.warn( "Failed to acquire lock on network group id=" + securityGroup.getId() + " name=" + securityGroup.getName()); txn.rollback(); return false; } if (_securityGroupVMMapDao.findByVmIdGroupId(userVmId, securityGroup.getId()) == null) { SecurityGroupVMMapVO groupVmMapVO = new SecurityGroupVMMapVO(securityGroup.getId(), userVmId); _securityGroupVMMapDao.persist(groupVmMapVO); } } txn.commit(); return true; } finally { if (userVm != null) { _userVMDao.releaseFromLockTable(userVmId); } } } return false; }
@DB public void handleDownloadEvent(HostVO host, VolumeVO volume, Status dnldStatus) { if ((dnldStatus == VMTemplateStorageResourceAssoc.Status.DOWNLOADED) || (dnldStatus == Status.ABANDONED)) { VolumeHostVO volumeHost = new VolumeHostVO(host.getId(), volume.getId()); synchronized (_listenerVolumeMap) { _listenerVolumeMap.remove(volumeHost); } } VolumeHostVO volumeHost = _volumeHostDao.findByHostVolume(host.getId(), volume.getId()); Transaction txn = Transaction.currentTxn(); txn.start(); if (dnldStatus == Status.DOWNLOADED) { // Create usage event long size = -1; if (volumeHost != null) { size = volumeHost.getSize(); volume.setSize(size); this._volumeDao.update(volume.getId(), volume); } else { s_logger.warn("Failed to get size for volume" + volume.getName()); } String eventType = EventTypes.EVENT_VOLUME_UPLOAD; if (volume.getAccountId() != Account.ACCOUNT_ID_SYSTEM) { UsageEventUtils.publishUsageEvent( eventType, volume.getAccountId(), host.getDataCenterId(), volume.getId(), volume.getName(), null, 0l, size, volume.getClass().getName(), volume.getUuid()); } } else if (dnldStatus == Status.DOWNLOAD_ERROR || dnldStatus == Status.ABANDONED || dnldStatus == Status.UNKNOWN) { // Decrement the volume and secondary storage space count _resourceLimitMgr.decrementResourceCount( volume.getAccountId(), com.cloud.configuration.Resource.ResourceType.volume); _resourceLimitMgr.recalculateResourceCount( volume.getAccountId(), volume.getDomainId(), com.cloud.configuration.Resource.ResourceType.secondary_storage.getOrdinal()); } txn.commit(); }
@Override @DB public boolean remove(Long vpcOffId) { Transaction txn = Transaction.currentTxn(); txn.start(); VpcOfferingVO offering = findById(vpcOffId); offering.setUniqueName(null); update(vpcOffId, offering); boolean result = super.remove(vpcOffId); txn.commit(); return result; }
@Override @DB @ActionEvent( eventType = EventTypes.EVENT_NETWORK_ACL_ITEM_CREATE, eventDescription = "creating network ACL Item", create = true) public NetworkACLItem createNetworkACLItem( Integer portStart, Integer portEnd, String protocol, List<String> sourceCidrList, Integer icmpCode, Integer icmpType, NetworkACLItem.TrafficType trafficType, Long aclId, String action, Integer number) { NetworkACLItem.Action ruleAction = NetworkACLItem.Action.Allow; if ("deny".equalsIgnoreCase(action)) { ruleAction = NetworkACLItem.Action.Deny; } // If number is null, set it to currentMax + 1 (for backward compatibility) if (number == null) { number = _networkACLItemDao.getMaxNumberByACL(aclId) + 1; } Transaction txn = Transaction.currentTxn(); txn.start(); NetworkACLItemVO newRule = new NetworkACLItemVO( portStart, portEnd, protocol.toLowerCase(), aclId, sourceCidrList, icmpCode, icmpType, trafficType, ruleAction, number); newRule = _networkACLItemDao.persist(newRule); if (!_networkACLItemDao.setStateToAdd(newRule)) { throw new CloudRuntimeException("Unable to update the state to add for " + newRule); } CallContext.current().setEventDetails("ACL Item Id: " + newRule.getId()); txn.commit(); return getNetworkACLItem(newRule.getId()); }
@Override @DB public boolean remove(Long id) { Transaction txn = Transaction.currentTxn(); txn.start(); StaticRouteVO entry = findById(id); if (entry != null) { _tagsDao.removeByIdAndType(id, TaggedResourceType.StaticRoute); } boolean result = super.remove(id); txn.commit(); return result; }
@Override @DB public boolean update(Long networkId, NetworkVO network, Map<String, String> serviceProviderMap) { Transaction txn = Transaction.currentTxn(); txn.start(); super.update(networkId, network); if (serviceProviderMap != null) { _ntwkSvcMap.deleteByNetworkId(networkId); persistNetworkServiceProviders(networkId, serviceProviderMap); } txn.commit(); return true; }
@Override @DB public StoragePoolVO persist(StoragePoolVO pool, Map<String, String> details) { Transaction txn = Transaction.currentTxn(); txn.start(); pool = super.persist(pool); if (details != null) { for (Map.Entry<String, String> detail : details.entrySet()) { StoragePoolDetailVO vo = new StoragePoolDetailVO(pool.getId(), detail.getKey(), detail.getValue()); _detailsDao.persist(vo); } } txn.commit(); return pool; }
@Override public void deleteOldStats(long maxEventTime) { Transaction txn = Transaction.currentTxn(); String sql = DELETE_OLD_STATS; PreparedStatement pstmt = null; try { txn.start(); pstmt = txn.prepareAutoCloseStatement(sql); pstmt.setLong(1, maxEventTime); pstmt.executeUpdate(); txn.commit(); } catch (Exception ex) { txn.rollback(); s_logger.error("error deleting old usage network stats", ex); } }
@Override @DB public void persistNetworkServiceProviders( long networkId, Map<String, String> serviceProviderMap) { Transaction txn = Transaction.currentTxn(); txn.start(); for (String service : serviceProviderMap.keySet()) { NetworkServiceMapVO serviceMap = new NetworkServiceMapVO( networkId, Service.getService(service), Provider.getProvider(serviceProviderMap.get(service))); _ntwkSvcMap.persist(serviceMap); } txn.commit(); }
@DB @Override @ActionEvent( eventType = EventTypes.EVENT_SECURITY_GROUP_DELETE, eventDescription = "deleting security group") public boolean deleteSecurityGroup(DeleteSecurityGroupCmd cmd) throws ResourceInUseException { Long groupId = cmd.getId(); Account caller = UserContext.current().getCaller(); SecurityGroupVO group = _securityGroupDao.findById(groupId); if (group == null) { throw new InvalidParameterValueException( "Unable to find network group: " + groupId + "; failed to delete group."); } // check permissions _accountMgr.checkAccess(caller, null, group); final Transaction txn = Transaction.currentTxn(); txn.start(); group = _securityGroupDao.lockRow(groupId, true); if (group == null) { throw new InvalidParameterValueException("Unable to find security group by id " + groupId); } if (group.getName().equalsIgnoreCase(SecurityGroupManager.DEFAULT_GROUP_NAME)) { throw new InvalidParameterValueException("The network group default is reserved"); } List<IngressRuleVO> allowingRules = _ingressRuleDao.listByAllowedSecurityGroupId(groupId); List<SecurityGroupVMMapVO> securityGroupVmMap = _securityGroupVMMapDao.listBySecurityGroup(groupId); if (!allowingRules.isEmpty()) { throw new ResourceInUseException( "Cannot delete group when there are ingress rules that allow this group"); } else if (!securityGroupVmMap.isEmpty()) { throw new ResourceInUseException("Cannot delete group when it's in use by virtual machines"); } _securityGroupDao.expunge(groupId); txn.commit(); s_logger.debug("Deleted security group id=" + groupId); return true; }
@Override @DB public boolean revokeSecurityGroupIngress(RevokeSecurityGroupIngressCmd cmd) { // input validation Account caller = UserContext.current().getCaller(); Long id = cmd.getId(); IngressRuleVO rule = _ingressRuleDao.findById(id); if (rule == null) { s_logger.debug("Unable to find ingress rule with id " + id); throw new InvalidParameterValueException("Unable to find ingress rule with id " + id); } // Check permissions SecurityGroup securityGroup = _securityGroupDao.findById(rule.getSecurityGroupId()); _accountMgr.checkAccess(caller, null, securityGroup); SecurityGroupVO groupHandle = null; final Transaction txn = Transaction.currentTxn(); try { txn.start(); // acquire lock on parent group (preserving this logic) groupHandle = _securityGroupDao.acquireInLockTable(rule.getSecurityGroupId()); if (groupHandle == null) { s_logger.warn("Could not acquire lock on security group id: " + rule.getSecurityGroupId()); return false; } _ingressRuleDao.remove(id); s_logger.debug("revokeSecurityGroupIngress succeeded for ingress rule id: " + id); final ArrayList<Long> affectedVms = new ArrayList<Long>(); affectedVms.addAll(_securityGroupVMMapDao.listVmIdsBySecurityGroup(groupHandle.getId())); scheduleRulesetUpdateToHosts(affectedVms, true, null); return true; } catch (Exception e) { s_logger.warn("Exception caught when deleting ingress rules ", e); throw new CloudRuntimeException("Exception caught when deleting ingress rules", e); } finally { if (groupHandle != null) { _securityGroupDao.releaseFromLockTable(groupHandle.getId()); } txn.commit(); } }
@Override @DB public VpnUser addVpnUser(long vpnOwnerId, String username, String password) { Account caller = UserContext.current().getCaller(); if (!username.matches("^[a-zA-Z0-9][a-zA-Z0-9@._-]{2,63}$")) { throw new InvalidParameterValueException( "Username has to be begin with an alphabet have 3-64 characters including alphabets, numbers and the set '@.-_'"); } if (!password.matches("^[a-zA-Z0-9][a-zA-Z0-9@#+=._-]{2,31}$")) { throw new InvalidParameterValueException( "Password has to be 3-32 characters including alphabets, numbers and the set '@#+=.-_'"); } Transaction txn = Transaction.currentTxn(); txn.start(); Account owner = _accountDao.lockRow(vpnOwnerId, true); if (owner == null) { throw new InvalidParameterValueException("Unable to add vpn user: Another operation active"); } _accountMgr.checkAccess(caller, null, true, owner); // don't allow duplicated user names for the same account VpnUserVO vpnUser = _vpnUsersDao.findByAccountAndUsername(owner.getId(), username); if (vpnUser != null) { throw new InvalidParameterValueException( "VPN User with name " + username + " is already added for account " + owner); } long userCount = _vpnUsersDao.getVpnUserCount(owner.getId()); if (userCount >= _userLimit) { throw new AccountLimitException( "Cannot add more than " + _userLimit + " remote access vpn users"); } VpnUser user = _vpnUsersDao.persist(new VpnUserVO(vpnOwnerId, owner.getDomainId(), username, password)); UsageEventUtils.publishUsageEvent( EventTypes.EVENT_VPN_USER_ADD, user.getAccountId(), 0, user.getId(), user.getUsername(), user.getClass().getName(), user.getUuid()); txn.commit(); return user; }
@Override @DB public StorageNetworkIpAddressVO takeIpAddress(long rangeId) { SearchCriteria<StorageNetworkIpAddressVO> sc = untakenIp.create(); sc.setParameters("rangeId", rangeId); Transaction txn = Transaction.currentTxn(); txn.start(); StorageNetworkIpAddressVO ip = lockOneRandomRow(sc, true); if (ip == null) { txn.rollback(); return null; } ip.setTakenAt(new Date()); update(ip.getId(), ip); txn.commit(); return ip; }
/** * This request registers the user Cloud.com account holder to the S3 service. The Cloud.com * account holder saves his API access and secret keys with the S3 service so that each rest call * he makes can be verified was originated from him. The given API access and secret key are saved * into the "usercredentials" database table. * * <p>This is an unauthenticated REST call. The only required parameters are 'accesskey' and * 'secretkey'. * * <p>To verify that the given keys represent an existing account they are used to execute the * Cloud.com's listAccounts API function. If the keys do not represent a valid account the * listAccounts function will fail. * * <p>A user can call this REST function any number of times, on each call the Cloud.com secret * key is simply over writes any previously stored value. * * <p>As with all REST calls HTTPS should be used to ensure their security. */ @DB private void setUserKeys(HttpServletRequest request, HttpServletResponse response) { String[] accessKey = null; String[] secretKey = null; try { // -> both these parameters are required accessKey = request.getParameterValues("accesskey"); if (null == accessKey || 0 == accessKey.length) { response.sendError(530, "Missing accesskey parameter"); return; } secretKey = request.getParameterValues("secretkey"); if (null == secretKey || 0 == secretKey.length) { response.sendError(530, "Missing secretkey parameter"); return; } } catch (Exception e) { logger.error("SetUserKeys exception " + e.getMessage(), e); response.setStatus(500); endResponse(response, "SetUserKeys exception " + e.getMessage()); return; } try { // -> use the keys to see if the account actually exists // ServiceProvider.getInstance().getEC2Engine().validateAccount( accessKey[0], secretKey[0] ); // UserCredentialsDaoImpl credentialDao = new UserCredentialsDao(); Transaction txn = Transaction.open(Transaction.AWSAPI_DB); txn.start(); UserCredentialsVO user = new UserCredentialsVO(accessKey[0], secretKey[0]); user = ucDao.persist(user); txn.commit(); txn.close(); // credentialDao.setUserKeys( accessKey[0], secretKey[0] ); } catch (Exception e) { logger.error("SetUserKeys " + e.getMessage(), e); response.setStatus(401); endResponse(response, e.toString()); return; } response.setStatus(200); endResponse(response, "User keys set successfully"); }
@Override public CloudStackServiceOfferingVO getSvcOfferingById(String id) { SearchBuilder<CloudStackServiceOfferingVO> searchByID = createSearchBuilder(); searchByID.and("uuid", searchByID.entity().getUuid(), SearchCriteria.Op.EQ); searchByID.done(); Transaction txn = Transaction.open(Transaction.CLOUD_DB); try { txn.start(); SearchCriteria<CloudStackServiceOfferingVO> sc = searchByID.create(); sc.setParameters("uuid", id); return findOneBy(sc); } finally { txn.commit(); txn.close(); } }
@DB public void handleDownloadEvent(HostVO host, VMTemplateVO template, Status dnldStatus) { if ((dnldStatus == VMTemplateStorageResourceAssoc.Status.DOWNLOADED) || (dnldStatus == Status.ABANDONED)) { VMTemplateHostVO vmTemplateHost = new VMTemplateHostVO(host.getId(), template.getId()); synchronized (_listenerMap) { _listenerMap.remove(vmTemplateHost); } } VMTemplateHostVO vmTemplateHost = _vmTemplateHostDao.findByHostTemplate(host.getId(), template.getId()); Transaction txn = Transaction.currentTxn(); txn.start(); if (dnldStatus == Status.DOWNLOADED) { long size = -1; if (vmTemplateHost != null) { size = vmTemplateHost.getPhysicalSize(); template.setSize(size); this._templateDao.update(template.getId(), template); } else { s_logger.warn("Failed to get size for template" + template.getName()); } String eventType = EventTypes.EVENT_TEMPLATE_CREATE; if ((template.getFormat()).equals(ImageFormat.ISO)) { eventType = EventTypes.EVENT_ISO_CREATE; } if (template.getAccountId() != Account.ACCOUNT_ID_SYSTEM) { UsageEventUtils.publishUsageEvent( eventType, template.getAccountId(), host.getDataCenterId(), template.getId(), template.getName(), null, template.getSourceTemplateId(), size, template.getClass().getName(), template.getUuid()); } } txn.commit(); }
@Override @DB public NetworkVO persist(NetworkVO network, boolean gc, Map<String, String> serviceProviderMap) { Transaction txn = Transaction.currentTxn(); txn.start(); // 1) create network NetworkVO newNetwork = super.persist(network); // 2) add account to the network addAccountToNetwork(network.getId(), network.getAccountId(), true); // 3) add network to gc monitor table NetworkOpVO op = new NetworkOpVO(network.getId(), gc); _opDao.persist(op); // 4) add services/providers for the network persistNetworkServiceProviders(newNetwork.getId(), serviceProviderMap); txn.commit(); return newNetwork; }
@Override public void saveUserStats(List<UserStatisticsVO> userStats) { Transaction txn = Transaction.currentTxn(); try { txn.start(); String sql = INSERT_USER_STATS; PreparedStatement pstmt = null; pstmt = txn.prepareAutoCloseStatement( sql); // in reality I just want CLOUD_USAGE dataSource connection for (UserStatisticsVO userStat : userStats) { pstmt.setLong(1, userStat.getId()); pstmt.setLong(2, userStat.getDataCenterId()); pstmt.setLong(3, userStat.getAccountId()); pstmt.setString(4, userStat.getPublicIpAddress()); if (userStat.getDeviceId() != null) { pstmt.setLong(5, userStat.getDeviceId()); } else { pstmt.setNull(5, Types.BIGINT); } pstmt.setString(6, userStat.getDeviceType()); if (userStat.getNetworkId() != null) { pstmt.setLong(7, userStat.getNetworkId()); } else { pstmt.setNull(7, Types.BIGINT); } pstmt.setLong(8, userStat.getNetBytesReceived()); pstmt.setLong(9, userStat.getNetBytesSent()); pstmt.setLong(10, userStat.getCurrentBytesReceived()); pstmt.setLong(11, userStat.getCurrentBytesSent()); pstmt.setLong(12, userStat.getAggBytesReceived()); pstmt.setLong(13, userStat.getAggBytesSent()); pstmt.addBatch(); } pstmt.executeBatch(); txn.commit(); } catch (Exception ex) { txn.rollback(); s_logger.error("error saving user stats to cloud_usage db", ex); throw new CloudRuntimeException(ex.getMessage()); } }
@Override public void deleteRecordsForAccount(Long accountId) { String sql = ((accountId == null) ? DELETE_ALL : DELETE_ALL_BY_ACCOUNTID); Transaction txn = Transaction.open(Transaction.USAGE_DB); PreparedStatement pstmt = null; try { txn.start(); pstmt = txn.prepareAutoCloseStatement(sql); if (accountId != null) { pstmt.setLong(1, accountId.longValue()); } pstmt.executeUpdate(); txn.commit(); } catch (Exception ex) { txn.rollback(); s_logger.error("error retrieving usage vm instances for account id: " + accountId); } finally { txn.close(); } }
@Override @DB public void deallocate( Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm) { if (s_logger.isDebugEnabled()) { s_logger.debug( "Deallocate network: networkId: " + nic.getNetworkId() + ", ip: " + nic.getIp4Address()); } IPAddressVO ip = _ipAddressDao.findByIpAndSourceNetworkId(nic.getNetworkId(), nic.getIp4Address()); if (ip != null) { Transaction txn = Transaction.currentTxn(); txn.start(); _networkMgr.markIpAsUnavailable(ip.getId()); _ipAddressDao.unassignIpAddress(ip.getId()); txn.commit(); } nic.deallocate(); }
@Override @DB public void removeInstanceFromGroups(Long userVmId) { if (!isVmSecurityGroupEnabled(userVmId)) { return; } final Transaction txn = Transaction.currentTxn(); txn.start(); UserVm userVm = _userVMDao.acquireInLockTable( userVmId); // ensures that duplicate entries are not created in // addInstance if (userVm == null) { s_logger.warn("Failed to acquire lock on user vm id=" + userVmId); } int n = _securityGroupVMMapDao.deleteVM(userVmId); s_logger.info("Disassociated " + n + " network groups " + " from uservm " + userVmId); _userVMDao.releaseFromLockTable(userVmId); txn.commit(); }
@Override @DB public boolean remove(Long id) { Transaction txn = Transaction.currentTxn(); txn.start(); VMTemplateVO template = createForUpdate(); template.setRemoved(new Date()); VMTemplateVO vo = findById(id); if (vo != null) { if (vo.getFormat() == ImageFormat.ISO) { _tagsDao.removeByIdAndType(id, TaggedResourceType.ISO); } else { _tagsDao.removeByIdAndType(id, TaggedResourceType.Template); } } boolean result = update(id, template); txn.commit(); return result; }
public void update(UsageVPNUserVO usage) { Transaction txn = Transaction.open(Transaction.USAGE_DB); PreparedStatement pstmt = null; try { txn.start(); if (usage.getDeleted() != null) { pstmt = txn.prepareAutoCloseStatement(UPDATE_DELETED); pstmt.setString( 1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), usage.getDeleted())); pstmt.setLong(2, usage.getAccountId()); pstmt.setLong(3, usage.getUserId()); } pstmt.executeUpdate(); txn.commit(); } catch (Exception e) { txn.rollback(); s_logger.warn("Error updating UsageVPNUserVO", e); } finally { txn.close(); } }