Search in sources :

Example 1 with SystemEventType

use of com.serotonin.m2m2.rt.event.type.SystemEventType in project ma-core-public by infiniteautomation.

the class EventManagerImpl method resetHighestAlarmLevel.

private void resetHighestAlarmLevel(long time) {
    int max = 0;
    activeEventsLock.readLock().lock();
    try {
        ListIterator<EventInstance> it = activeEvents.listIterator();
        while (it.hasNext()) {
            EventInstance e = it.next();
            if (e.getAlarmLevel() > max)
                max = e.getAlarmLevel();
        }
    } finally {
        activeEventsLock.readLock().unlock();
    }
    if (max > highestActiveAlarmLevel) {
        int oldValue = highestActiveAlarmLevel;
        highestActiveAlarmLevel = max;
        SystemEventType.raiseEvent(new SystemEventType(SystemEventType.TYPE_MAX_ALARM_LEVEL_CHANGED), time, false, getAlarmLevelChangeMessage("event.alarmMaxIncreased", oldValue));
    } else if (max < highestActiveAlarmLevel) {
        int oldValue = highestActiveAlarmLevel;
        highestActiveAlarmLevel = max;
        SystemEventType.raiseEvent(new SystemEventType(SystemEventType.TYPE_MAX_ALARM_LEVEL_CHANGED), time, false, getAlarmLevelChangeMessage("event.alarmMaxDecreased", oldValue));
    }
}
Also used : EventInstance(com.serotonin.m2m2.rt.event.EventInstance) SystemEventType(com.serotonin.m2m2.rt.event.type.SystemEventType)

Example 2 with SystemEventType

use of com.serotonin.m2m2.rt.event.type.SystemEventType in project ma-core-public by infiniteautomation.

the class EventManagerImpl method raiseEvent.

// 
// 
// Basic event management.
// 
/**
 * Raise Event
 * @param type
 * @param time
 * @param rtnApplicable - does this event return to normal?
 * @param alarmLevel
 * @param message
 * @param context
 */
public void raiseEvent(EventType type, long time, boolean rtnApplicable, int alarmLevel, TranslatableMessage message, Map<String, Object> context) {
    if (state != RUNNING)
        return;
    if (alarmLevel == AlarmLevels.IGNORE)
        return;
    // Check if there is an event for this type already active.
    EventInstance dup = get(type);
    if (dup != null) {
        // Check the duplicate handling.
        boolean discard = canDiscard(type, message);
        if (discard)
            return;
    // Otherwise we just continue...
    } else if (!rtnApplicable) {
        // Check if we've already seen this type recently.
        boolean recent = isRecent(type, message);
        if (recent)
            return;
    }
    // Determine if the event should be suppressed.
    TranslatableMessage autoAckMessage = null;
    for (EventManagerListenerDefinition l : listeners) {
        autoAckMessage = l.autoAckEventWithMessage(type);
        if (autoAckMessage != null)
            break;
    }
    EventInstance evt = new EventInstance(type, time, rtnApplicable, alarmLevel, message, context);
    if (autoAckMessage == null)
        setHandlers(evt);
    // Check to see if we are Not Logging these
    if (alarmLevel != AlarmLevels.DO_NOT_LOG) {
        eventDao.saveEvent(evt);
    }
    // Create user alarm records for all applicable users
    List<Integer> eventUserIds = new ArrayList<Integer>();
    Set<String> emailUsers = new HashSet<String>();
    for (User user : userDao.getActiveUsers()) {
        // user should be skipped.
        if (type.excludeUser(user))
            continue;
        if (Permissions.hasEventTypePermission(user, type)) {
            eventUserIds.add(user.getId());
            if (user.getReceiveAlarmEmails() > AlarmLevels.IGNORE && alarmLevel >= user.getReceiveAlarmEmails() && !StringUtils.isEmpty(user.getEmail()))
                emailUsers.add(user.getEmail());
            // Notify All User Event Listeners of the new event
            if ((alarmLevel != AlarmLevels.DO_NOT_LOG) && (!evt.getEventType().getEventType().equals(EventType.EventTypeNames.AUDIT))) {
                for (UserEventListener l : this.userEventListeners) {
                    if (l.getUserId() == user.getId()) {
                        Common.backgroundProcessing.addWorkItem(new EventNotifyWorkItem(user, l, evt, true, false, false, false));
                    }
                }
                // Add to the UserEventCache if the user has recently accessed their events
                this.userEventCache.addEvent(user.getId(), evt);
            }
        }
    }
    DateTime now = new DateTime(Common.timer.currentTimeMillis());
    for (MailingList ml : MailingListDao.instance.getAlarmMailingLists(alarmLevel)) {
        ml.appendAddresses(emailUsers, now);
    }
    // No Audit or Do Not Log events are User Events
    if ((eventUserIds.size() > 0) && (alarmLevel != AlarmLevels.DO_NOT_LOG) && (!evt.getEventType().getEventType().equals(EventType.EventTypeNames.AUDIT))) {
        eventDao.insertUserEvents(evt.getId(), eventUserIds, true);
        if (autoAckMessage == null)
            lastAlarmTimestamp = Common.timer.currentTimeMillis();
    }
    if (evt.isRtnApplicable()) {
        activeEventsLock.writeLock().lock();
        try {
            activeEvents.add(evt);
        } finally {
            activeEventsLock.writeLock().unlock();
        }
    } else if (evt.getEventType().isRateLimited()) {
        recentEventsLock.writeLock().lock();
        try {
            recentEvents.add(evt);
        } finally {
            recentEventsLock.writeLock().unlock();
        }
    }
    if ((autoAckMessage != null) && (alarmLevel != AlarmLevels.DO_NOT_LOG) && (!evt.getEventType().getEventType().equals(EventType.EventTypeNames.AUDIT)))
        this.acknowledgeEvent(evt, time, null, autoAckMessage);
    else {
        if (evt.isRtnApplicable()) {
            if (alarmLevel > highestActiveAlarmLevel) {
                int oldValue = highestActiveAlarmLevel;
                highestActiveAlarmLevel = alarmLevel;
                SystemEventType.raiseEvent(new SystemEventType(SystemEventType.TYPE_MAX_ALARM_LEVEL_CHANGED), time, false, getAlarmLevelChangeMessage("event.alarmMaxIncreased", oldValue));
            }
        }
        // Call raiseEvent handlers.
        handleRaiseEvent(evt, emailUsers);
        if (log.isDebugEnabled())
            log.trace("Event raised: type=" + type + ", message=" + message.translate(Common.getTranslations()));
    }
}
Also used : EventInstance(com.serotonin.m2m2.rt.event.EventInstance) SystemEventType(com.serotonin.m2m2.rt.event.type.SystemEventType) User(com.serotonin.m2m2.vo.User) ArrayList(java.util.ArrayList) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) MailingList(com.serotonin.m2m2.vo.mailingList.MailingList) DateTime(org.joda.time.DateTime) UserEventListener(com.serotonin.m2m2.rt.event.UserEventListener) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) EventManagerListenerDefinition(com.serotonin.m2m2.module.EventManagerListenerDefinition) HashSet(java.util.HashSet)

Example 3 with SystemEventType

use of com.serotonin.m2m2.rt.event.type.SystemEventType in project ma-core-public by infiniteautomation.

the class SystemEventType method returnToNormal.

public static void returnToNormal(SystemEventType type, long time) {
    EventTypeVO vo = getEventType(type.getSystemEventType());
    Common.eventManager.returnToNormal(type, time, vo.getAlarmLevel());
}
Also used : EventTypeVO(com.serotonin.m2m2.vo.event.EventTypeVO)

Example 4 with SystemEventType

use of com.serotonin.m2m2.rt.event.type.SystemEventType in project ma-core-public by infiniteautomation.

the class SystemEventType method raiseEvent.

public static void raiseEvent(SystemEventType type, long time, boolean rtn, TranslatableMessage message) {
    EventTypeVO vo = getEventType(type.getSystemEventType());
    if (vo == null) {
        LOG.warn("Unkown event type null");
        return;
    }
    int alarmLevel = vo.getAlarmLevel();
    Common.eventManager.raiseEvent(type, time, rtn, alarmLevel, message, null);
}
Also used : EventTypeVO(com.serotonin.m2m2.vo.event.EventTypeVO)

Example 5 with SystemEventType

use of com.serotonin.m2m2.rt.event.type.SystemEventType in project ma-core-public by infiniteautomation.

the class BackupWorkItem method execute.

@Override
public void execute() {
    synchronized (lock) {
        LOG.info("Starting backup WorkItem.");
        // Create the filename
        String filename = "Mango-Configuration";
        String runtimeString = dateFormatter.format(new Date());
        int maxFiles = SystemSettingsDao.getIntValue(SystemSettingsDao.BACKUP_FILE_COUNT);
        // If > 1 then we will use a date in the filename
        if (maxFiles > 1) {
            // Create Mango-Configuration-date.json
            filename += "-";
            filename += runtimeString;
        }
        filename += ".json";
        // Fill the full path
        String fullFilePath = this.backupLocation;
        if (fullFilePath.endsWith(File.separator)) {
            fullFilePath += filename;
        } else {
            fullFilePath += File.separator;
            fullFilePath += filename;
        }
        if (cancelled)
            return;
        // Collect the json backup data
        String jsonData = getBackup();
        // Write to file
        try {
            File file = new File(fullFilePath);
            if (!file.exists())
                if (!file.createNewFile()) {
                    failed = true;
                    LOG.warn("Unable to create backup file: " + fullFilePath);
                    SystemEventType.raiseEvent(new SystemEventType(SystemEventType.TYPE_BACKUP_FAILURE), Common.timer.currentTimeMillis(), false, new TranslatableMessage("event.backup.failure", fullFilePath, "Unable to create backup file"));
                    return;
                }
            // Always replace if exists
            FileWriter fw = new FileWriter(file, false);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(jsonData);
            bw.close();
            // Save the filename
            this.filename = file.getAbsolutePath();
            // Store the last successful backup time
            SystemSettingsDao.instance.setValue(SystemSettingsDao.BACKUP_LAST_RUN_SUCCESS, runtimeString);
            // Clean up old files, keeping the correct number as the history
            File backupDir = new File(this.backupLocation);
            File[] files = backupDir.listFiles(new FilenameFilter() {

                public boolean accept(File dir, String name) {
                    return name.toLowerCase().endsWith(".json");
                }
            });
            // Sort the files by date
            Arrays.sort(files, LastModifiedFileComparator.LASTMODIFIED_REVERSE);
            // Keep the desired history
            for (int i = maxFiles; i < files.length; i++) {
                try {
                    // Remove it
                    files[i].delete();
                } catch (Exception e) {
                    LOG.warn("Unable to delete file: " + files[i].getAbsolutePath(), e);
                }
            }
        } catch (Exception e) {
            LOG.warn(e);
            failed = true;
            SystemEventType.raiseEvent(new SystemEventType(SystemEventType.TYPE_BACKUP_FAILURE), Common.timer.currentTimeMillis(), false, new TranslatableMessage("event.backup.failure", fullFilePath, e.getMessage()));
        } finally {
            this.finished = true;
            LOG.info("Finished backup WorkItem.");
        }
    }
}
Also used : SystemEventType(com.serotonin.m2m2.rt.event.type.SystemEventType) FilenameFilter(java.io.FilenameFilter) FileWriter(java.io.FileWriter) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) File(java.io.File) Date(java.util.Date) ShouldNeverHappenException(com.serotonin.ShouldNeverHappenException) ParseException(java.text.ParseException) BufferedWriter(java.io.BufferedWriter)

Aggregations

SystemEventType (com.serotonin.m2m2.rt.event.type.SystemEventType)9 TranslatableMessage (com.serotonin.m2m2.i18n.TranslatableMessage)6 DataPointEventType (com.serotonin.m2m2.rt.event.type.DataPointEventType)3 ShouldNeverHappenException (com.serotonin.ShouldNeverHappenException)2 PostEmailRunnable (com.serotonin.m2m2.email.PostEmailRunnable)2 EventTypeDefinition (com.serotonin.m2m2.module.EventTypeDefinition)2 EventInstance (com.serotonin.m2m2.rt.event.EventInstance)2 DataSourceEventType (com.serotonin.m2m2.rt.event.type.DataSourceEventType)2 EventType (com.serotonin.m2m2.rt.event.type.EventType)2 MissingEventType (com.serotonin.m2m2.rt.event.type.MissingEventType)2 PublisherEventType (com.serotonin.m2m2.rt.event.type.PublisherEventType)2 User (com.serotonin.m2m2.vo.User)2 EventTypeVO (com.serotonin.m2m2.vo.event.EventTypeVO)2 File (java.io.File)2 ArrayList (java.util.ArrayList)2 IntStringPair (com.serotonin.db.pair.IntStringPair)1 MangoEmailContent (com.serotonin.m2m2.email.MangoEmailContent)1 UsedImagesDirective (com.serotonin.m2m2.email.UsedImagesDirective)1 Translations (com.serotonin.m2m2.i18n.Translations)1 EventManagerListenerDefinition (com.serotonin.m2m2.module.EventManagerListenerDefinition)1