Search in sources :

Example 6 with UsageEventVO

use of com.cloud.event.UsageEventVO in project cloudstack by apache.

the class Upgrade218to22 method convertISOEvent.

private UsageEventVO convertISOEvent(EventVO event) throws IOException {
    Properties isoEventParams = new Properties();
    long isoId = -1L;
    long isoSize = -1L;
    long zoneId = -1L;
    UsageEventVO usageEvent = null;
    isoEventParams.load(new StringReader(event.getParameters()));
    isoId = Long.parseLong(isoEventParams.getProperty("id"));
    if (isoEventParams.getProperty("dcId") != null) {
        zoneId = Long.parseLong(isoEventParams.getProperty("dcId"));
    }
    if (EventTypes.EVENT_ISO_CREATE.equals(event.getType()) || EventTypes.EVENT_ISO_COPY.equals(event.getType())) {
        isoSize = Long.parseLong(isoEventParams.getProperty("size"));
        usageEvent = new UsageEventVO(event.getType(), event.getAccountId(), zoneId, isoId, "", null, null, isoSize);
    } else if (EventTypes.EVENT_ISO_DELETE.equals(event.getType())) {
        usageEvent = new UsageEventVO(event.getType(), event.getAccountId(), zoneId, isoId, null);
    }
    return usageEvent;
}
Also used : StringReader(java.io.StringReader) UsageEventVO(com.cloud.event.UsageEventVO) Properties(java.util.Properties)

Example 7 with UsageEventVO

use of com.cloud.event.UsageEventVO in project cloudstack by apache.

the class UsageEventDaoImpl method listLatestEvents.

@Override
public List<UsageEventVO> listLatestEvents(Date endDate) {
    Filter filter = new Filter(UsageEventVO.class, "createDate", Boolean.TRUE, null, null);
    SearchCriteria<UsageEventVO> sc = latestEventsSearch.create();
    sc.setParameters("processed", false);
    sc.setParameters("enddate", endDate);
    return listBy(sc, filter);
}
Also used : Filter(com.cloud.utils.db.Filter) UsageEventVO(com.cloud.event.UsageEventVO)

Example 8 with UsageEventVO

use of com.cloud.event.UsageEventVO in project CloudStack-archive by CloudStack-extras.

the class UsageManagerImpl method parse.

public void parse(UsageJobVO job, long startDateMillis, long endDateMillis) {
    // TODO: Shouldn't we also allow parsing by the type of usage?
    boolean success = false;
    long timeStart = System.currentTimeMillis();
    long deleteOldStatsTimeMillis = 0L;
    try {
        if ((endDateMillis == 0) || (endDateMillis > timeStart)) {
            endDateMillis = timeStart;
        }
        long lastSuccess = m_usageJobDao.getLastJobSuccessDateMillis();
        if (lastSuccess != 0) {
            // 1 millisecond after
            startDateMillis = lastSuccess + 1;
        }
        if (startDateMillis >= endDateMillis) {
            if (s_logger.isInfoEnabled()) {
                s_logger.info("not parsing usage records since start time mills (" + startDateMillis + ") is on or after end time millis (" + endDateMillis + ")");
            }
            Transaction jobUpdateTxn = Transaction.open(Transaction.USAGE_DB);
            try {
                jobUpdateTxn.start();
                // everything seemed to work...set endDate as the last success date
                m_usageJobDao.updateJobSuccess(job.getId(), startDateMillis, endDateMillis, System.currentTimeMillis() - timeStart, success);
                // create a new job if this is a recurring job
                if (job.getJobType() == UsageJobVO.JOB_TYPE_RECURRING) {
                    m_usageJobDao.createNewJob(m_hostname, m_pid, UsageJobVO.JOB_TYPE_RECURRING);
                }
                jobUpdateTxn.commit();
            } finally {
                jobUpdateTxn.close();
            }
            return;
        }
        deleteOldStatsTimeMillis = startDateMillis;
        Date startDate = new Date(startDateMillis);
        Date endDate = new Date(endDateMillis);
        if (s_logger.isInfoEnabled()) {
            s_logger.info("Parsing usage records between " + startDate + " and " + endDate);
        }
        List<AccountVO> accounts = null;
        List<UserStatisticsVO> userStats = null;
        Map<String, UsageNetworkVO> networkStats = null;
        Transaction userTxn = Transaction.open(Transaction.CLOUD_DB);
        try {
            Long limit = Long.valueOf(500);
            Long offset = Long.valueOf(0);
            Long lastAccountId = m_usageDao.getLastAccountId();
            if (lastAccountId == null) {
                lastAccountId = Long.valueOf(0);
            }
            do {
                Filter filter = new Filter(AccountVO.class, "id", true, offset, limit);
                accounts = m_accountDao.findActiveAccounts(lastAccountId, filter);
                if ((accounts != null) && !accounts.isEmpty()) {
                    // now update the accounts in the cloud_usage db
                    m_usageDao.updateAccounts(accounts);
                }
                offset = new Long(offset.longValue() + limit.longValue());
            } while ((accounts != null) && !accounts.isEmpty());
            // reset offset
            offset = Long.valueOf(0);
            do {
                Filter filter = new Filter(AccountVO.class, "id", true, offset, limit);
                accounts = m_accountDao.findRecentlyDeletedAccounts(lastAccountId, startDate, filter);
                if ((accounts != null) && !accounts.isEmpty()) {
                    // now update the accounts in the cloud_usage db
                    m_usageDao.updateAccounts(accounts);
                }
                offset = new Long(offset.longValue() + limit.longValue());
            } while ((accounts != null) && !accounts.isEmpty());
            // reset offset
            offset = Long.valueOf(0);
            do {
                Filter filter = new Filter(AccountVO.class, "id", true, offset, limit);
                accounts = m_accountDao.findNewAccounts(lastAccountId, filter);
                if ((accounts != null) && !accounts.isEmpty()) {
                    // now copy the accounts to cloud_usage db
                    m_usageDao.saveAccounts(accounts);
                }
                offset = new Long(offset.longValue() + limit.longValue());
            } while ((accounts != null) && !accounts.isEmpty());
            // reset offset
            offset = Long.valueOf(0);
            // get all the user stats to create usage records for the network usage
            Long lastUserStatsId = m_usageDao.getLastUserStatsId();
            if (lastUserStatsId == null) {
                lastUserStatsId = Long.valueOf(0);
            }
            SearchCriteria<UserStatisticsVO> sc2 = m_userStatsDao.createSearchCriteria();
            sc2.addAnd("id", SearchCriteria.Op.LTEQ, lastUserStatsId);
            do {
                Filter filter = new Filter(UserStatisticsVO.class, "id", true, offset, limit);
                userStats = m_userStatsDao.search(sc2, filter);
                if ((userStats != null) && !userStats.isEmpty()) {
                    // now copy the accounts to cloud_usage db
                    m_usageDao.updateUserStats(userStats);
                }
                offset = new Long(offset.longValue() + limit.longValue());
            } while ((userStats != null) && !userStats.isEmpty());
            // reset offset
            offset = Long.valueOf(0);
            sc2 = m_userStatsDao.createSearchCriteria();
            sc2.addAnd("id", SearchCriteria.Op.GT, lastUserStatsId);
            do {
                Filter filter = new Filter(UserStatisticsVO.class, "id", true, offset, limit);
                userStats = m_userStatsDao.search(sc2, filter);
                if ((userStats != null) && !userStats.isEmpty()) {
                    // now copy the accounts to cloud_usage db
                    m_usageDao.saveUserStats(userStats);
                }
                offset = new Long(offset.longValue() + limit.longValue());
            } while ((userStats != null) && !userStats.isEmpty());
        } finally {
            userTxn.close();
        }
        // TODO:  Fetch a maximum number of events and process them before moving on to the next range of events
        // - get a list of the latest events
        // - insert the latest events into the usage.events table
        List<UsageEventVO> events = _usageEventDao.getRecentEvents(new Date(endDateMillis));
        Transaction usageTxn = Transaction.open(Transaction.USAGE_DB);
        try {
            usageTxn.start();
            // to newest, so just test against the first event)
            if ((events != null) && (events.size() > 0)) {
                Date oldestEventDate = events.get(0).getCreateDate();
                if (oldestEventDate.getTime() < startDateMillis) {
                    startDateMillis = oldestEventDate.getTime();
                    startDate = new Date(startDateMillis);
                }
                // - create the usage records using the parse methods below
                for (UsageEventVO event : events) {
                    event.setProcessed(true);
                    _usageEventDao.update(event.getId(), event);
                    createHelperRecord(event);
                }
            }
            // TODO:  Fetch a maximum number of user stats and process them before moving on to the next range of user stats
            // get user stats in order to compute network usage
            networkStats = m_usageNetworkDao.getRecentNetworkStats();
            Calendar recentlyDeletedCal = Calendar.getInstance(m_usageTimezone);
            recentlyDeletedCal.setTimeInMillis(startDateMillis);
            recentlyDeletedCal.add(Calendar.MINUTE, -1 * THREE_DAYS_IN_MINUTES);
            Date recentlyDeletedDate = recentlyDeletedCal.getTime();
            // Keep track of user stats for an account, across all of its public IPs
            Map<String, UserStatisticsVO> aggregatedStats = new HashMap<String, UserStatisticsVO>();
            int startIndex = 0;
            do {
                userStats = m_userStatsDao.listActiveAndRecentlyDeleted(recentlyDeletedDate, startIndex, 500);
                if (userStats != null) {
                    for (UserStatisticsVO userStat : userStats) {
                        if (userStat.getDeviceId() != null) {
                            String hostKey = userStat.getDataCenterId() + "-" + userStat.getAccountId() + "-Host-" + userStat.getDeviceId();
                            UserStatisticsVO hostAggregatedStat = aggregatedStats.get(hostKey);
                            if (hostAggregatedStat == null) {
                                hostAggregatedStat = new UserStatisticsVO(userStat.getAccountId(), userStat.getDataCenterId(), userStat.getPublicIpAddress(), userStat.getDeviceId(), userStat.getDeviceType(), userStat.getNetworkId());
                            }
                            hostAggregatedStat.setAggBytesSent(hostAggregatedStat.getAggBytesSent() + userStat.getAggBytesSent());
                            hostAggregatedStat.setAggBytesReceived(hostAggregatedStat.getAggBytesReceived() + userStat.getAggBytesReceived());
                            aggregatedStats.put(hostKey, hostAggregatedStat);
                        }
                    }
                }
                startIndex += 500;
            } while ((userStats != null) && !userStats.isEmpty());
            // loop over the user stats, create delta entries in the usage_network helper table
            int numAcctsProcessed = 0;
            for (String key : aggregatedStats.keySet()) {
                UsageNetworkVO currentNetworkStats = null;
                if (networkStats != null) {
                    currentNetworkStats = networkStats.get(key);
                }
                createNetworkHelperEntry(aggregatedStats.get(key), currentNetworkStats, endDateMillis);
                numAcctsProcessed++;
            }
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("created network stats helper entries for " + numAcctsProcessed + " accts");
            }
            // commit the helper records, then start a new transaction
            usageTxn.commit();
            usageTxn.start();
            boolean parsed = false;
            numAcctsProcessed = 0;
            Date currentStartDate = startDate;
            Date currentEndDate = endDate;
            Date tempDate = endDate;
            Calendar aggregateCal = Calendar.getInstance(m_usageTimezone);
            while ((tempDate.after(startDate)) && ((tempDate.getTime() - startDate.getTime()) > 60000)) {
                currentEndDate = tempDate;
                aggregateCal.setTime(tempDate);
                aggregateCal.add(Calendar.MINUTE, -m_aggregationDuration);
                tempDate = aggregateCal.getTime();
            }
            while (!currentEndDate.after(endDate) || (currentEndDate.getTime() - endDate.getTime() < 60000)) {
                Long offset = Long.valueOf(0);
                Long limit = Long.valueOf(500);
                do {
                    Filter filter = new Filter(AccountVO.class, "id", true, offset, limit);
                    accounts = m_accountDao.listAll(filter);
                    if ((accounts != null) && !accounts.isEmpty()) {
                        for (AccountVO account : accounts) {
                            parsed = parseHelperTables(account, currentStartDate, currentEndDate);
                            numAcctsProcessed++;
                        }
                    }
                    offset = new Long(offset.longValue() + limit.longValue());
                } while ((accounts != null) && !accounts.isEmpty());
                if (s_logger.isDebugEnabled()) {
                    s_logger.debug("processed VM/Network Usage for " + numAcctsProcessed + " ACTIVE accts");
                }
                numAcctsProcessed = 0;
                // reset offset
                offset = Long.valueOf(0);
                do {
                    Filter filter = new Filter(AccountVO.class, "id", true, offset, limit);
                    accounts = m_accountDao.findRecentlyDeletedAccounts(null, recentlyDeletedDate, filter);
                    if ((accounts != null) && !accounts.isEmpty()) {
                        for (AccountVO account : accounts) {
                            parsed = parseHelperTables(account, currentStartDate, currentEndDate);
                            List<Long> publicTemplates = m_usageDao.listPublicTemplatesByAccount(account.getId());
                            for (Long templateId : publicTemplates) {
                                //mark public templates owned by deleted accounts as deleted
                                List<UsageStorageVO> storageVOs = m_usageStorageDao.listById(account.getId(), templateId, StorageTypes.TEMPLATE);
                                if (storageVOs.size() > 1) {
                                    s_logger.warn("More that one usage entry for storage: " + templateId + " assigned to account: " + account.getId() + "; marking them all as deleted...");
                                }
                                for (UsageStorageVO storageVO : storageVOs) {
                                    if (s_logger.isDebugEnabled()) {
                                        s_logger.debug("deleting template: " + storageVO.getId() + " from account: " + storageVO.getAccountId());
                                    }
                                    storageVO.setDeleted(account.getRemoved());
                                    m_usageStorageDao.update(storageVO);
                                }
                            }
                            numAcctsProcessed++;
                        }
                    }
                    offset = new Long(offset.longValue() + limit.longValue());
                } while ((accounts != null) && !accounts.isEmpty());
                currentStartDate = new Date(currentEndDate.getTime() + 1);
                aggregateCal.setTime(currentEndDate);
                aggregateCal.add(Calendar.MINUTE, m_aggregationDuration);
                currentEndDate = aggregateCal.getTime();
            }
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("processed Usage for " + numAcctsProcessed + " RECENTLY DELETED accts");
            }
            //        do we want to break out of processing accounts and rollback if there are errors?
            if (!parsed) {
                usageTxn.rollback();
            } else {
                success = true;
            }
        } catch (Exception ex) {
            s_logger.error("Exception in usage manager", ex);
            usageTxn.rollback();
        } finally {
            // everything seemed to work...set endDate as the last success date
            m_usageJobDao.updateJobSuccess(job.getId(), startDateMillis, endDateMillis, System.currentTimeMillis() - timeStart, success);
            // create a new job if this is a recurring job
            if (job.getJobType() == UsageJobVO.JOB_TYPE_RECURRING) {
                m_usageJobDao.createNewJob(m_hostname, m_pid, UsageJobVO.JOB_TYPE_RECURRING);
            }
            usageTxn.commit();
            usageTxn.close();
            // switch back to CLOUD_DB
            Transaction swap = Transaction.open(Transaction.CLOUD_DB);
            if (!success) {
                _alertMgr.sendAlert(AlertManager.ALERT_TYPE_USAGE_SERVER_RESULT, 0, new Long(0), "Usage job failed. Job id: " + job.getId(), "Usage job failed. Job id: " + job.getId());
            } else {
                _alertMgr.clearAlert(AlertManager.ALERT_TYPE_USAGE_SERVER_RESULT, 0, 0);
            }
            swap.close();
        }
    } catch (Exception e) {
        s_logger.error("Usage Manager error", e);
    }
}
Also used : HashMap(java.util.HashMap) Calendar(java.util.Calendar) UsageEventVO(com.cloud.event.UsageEventVO) AccountVO(com.cloud.user.AccountVO) Date(java.util.Date) ConfigurationException(javax.naming.ConfigurationException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) SQLException(java.sql.SQLException) Transaction(com.cloud.utils.db.Transaction) Filter(com.cloud.utils.db.Filter) UserStatisticsVO(com.cloud.user.UserStatisticsVO)

Example 9 with UsageEventVO

use of com.cloud.event.UsageEventVO in project cloudstack by apache.

the class BareMetalTemplateAdapter method templateCreateUsage.

private void templateCreateUsage(VMTemplateVO template, long dcId) {
    if (template.getAccountId() != Account.ACCOUNT_ID_SYSTEM) {
        UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_TEMPLATE_CREATE, template.getAccountId(), dcId, template.getId(), template.getName(), null, template.getSourceTemplateId(), 0L);
        _usageEventDao.persist(usageEvent);
    }
}
Also used : UsageEventVO(com.cloud.event.UsageEventVO)

Example 10 with UsageEventVO

use of com.cloud.event.UsageEventVO in project cloudstack by apache.

the class HypervisorTemplateAdapterTest method setupUsageUtils.

public UsageEventUtils setupUsageUtils() throws EventBusException {
    Mockito.when(_configDao.getValue(eq("publish.usage.events"))).thenReturn("true");
    Mockito.when(_usageEventDao.persist(Mockito.any(UsageEventVO.class))).then(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            UsageEventVO vo = (UsageEventVO) invocation.getArguments()[0];
            usageEvents.add(vo);
            return null;
        }
    });
    Mockito.when(_usageEventDao.listAll()).thenReturn(usageEvents);
    doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            Event event = (Event) invocation.getArguments()[0];
            events.add(event);
            return null;
        }
    }).when(_bus).publish(any(Event.class));
    PowerMockito.mockStatic(ComponentContext.class);
    when(ComponentContext.getComponent(eq(EventBus.class))).thenReturn(_bus);
    UsageEventUtils utils = new UsageEventUtils();
    Map<String, String> usageUtilsFields = new HashMap<String, String>();
    usageUtilsFields.put("usageEventDao", "_usageEventDao");
    usageUtilsFields.put("accountDao", "_accountDao");
    usageUtilsFields.put("dcDao", "_dcDao");
    usageUtilsFields.put("configDao", "_configDao");
    for (String fieldName : usageUtilsFields.keySet()) {
        try {
            Field f = UsageEventUtils.class.getDeclaredField(fieldName);
            f.setAccessible(true);
            //Remember the old fields for cleanup later (see cleanupUsageUtils)
            Field staticField = UsageEventUtils.class.getDeclaredField("s_" + fieldName);
            staticField.setAccessible(true);
            oldFields.put(f.getName(), staticField.get(null));
            f.set(utils, this.getClass().getDeclaredField(usageUtilsFields.get(fieldName)).get(this));
        } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e) {
            e.printStackTrace();
        }
    }
    try {
        Method method = UsageEventUtils.class.getDeclaredMethod("init");
        method.setAccessible(true);
        method.invoke(utils);
    } catch (SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException e) {
        e.printStackTrace();
    }
    return utils;
}
Also used : HashMap(java.util.HashMap) UsageEventVO(com.cloud.event.UsageEventVO) EventBus(org.apache.cloudstack.framework.events.EventBus) Method(java.lang.reflect.Method) InvocationTargetException(java.lang.reflect.InvocationTargetException) Field(java.lang.reflect.Field) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Event(org.apache.cloudstack.framework.events.Event) UsageEventUtils(com.cloud.event.UsageEventUtils)

Aggregations

UsageEventVO (com.cloud.event.UsageEventVO)17 StringReader (java.io.StringReader)6 Properties (java.util.Properties)6 Filter (com.cloud.utils.db.Filter)4 PreparedStatement (java.sql.PreparedStatement)4 VMTemplateVO (com.cloud.storage.VMTemplateVO)3 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)3 ResultSet (java.sql.ResultSet)3 Date (java.util.Date)3 HashMap (java.util.HashMap)3 ConfigurationException (javax.naming.ConfigurationException)3 TemplateDataStoreVO (org.apache.cloudstack.storage.datastore.db.TemplateDataStoreVO)3 VMTemplateZoneVO (com.cloud.storage.VMTemplateZoneVO)2 VolumeVO (com.cloud.storage.VolumeVO)2 Account (com.cloud.user.Account)2 AccountVO (com.cloud.user.AccountVO)2 UserStatisticsVO (com.cloud.user.UserStatisticsVO)2 DB (com.cloud.utils.db.DB)2 SQLException (java.sql.SQLException)2 Calendar (java.util.Calendar)2