All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.addc.server.commons.monitored.MonitoringClient Maven / Gradle / Ivy

Go to download

Supplies the classes required for monitoring a server with the Amentet Monitoring Service

There is a newer version: 2.9
Show newest version
package com.addc.server.commons.monitored;

import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;

import org.omg.CORBA.ORB;
import org.omg.CORBA.SystemException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.addc.commons.Mutex;
import com.addc.commons.alerts.Notifier;
import com.addc.commons.i18n.I18nTextFactory;
import com.addc.commons.iiop.OrbHolder;
import com.addc.commons.shutdown.Stoppable;
import com.addc.server.commons.ManagedObject;
import com.addc.server.commons.alerts.AlertFactory;
import com.addc.server.monitoring.Monitor;
import com.addc.server.monitoring.MonitorHelper;

/**
 * The MonitoringClient runs a timer that keeps the current service leases
 * updated with an Amentet Monitoring Service. An instance of this class is
 * created in the {@link com.addc.server.commons.domain.OrbWrapper}
 * initialization and accessed by the {@link MonitoredImpl} object by looking up
 * the Application Context.
 */
public class MonitoringClient extends TimerTask implements Stoppable {
    private static final Logger LOGGER= LoggerFactory.getLogger(MonitoringClient.class);
    private static final String I18N_NAME= "com.addc.server.Messages";
    private final Map monitoredComponents= new ConcurrentHashMap<>();
    private final ORB orb;
    private final Notifier notifier;
    private final Set sourceIds;
    private final Mutex lock= new Mutex();
    private final int leaseTime;
    private Timer monitorTimer;
    private final MonitoringClientState state;
    private Monitor remoteMonitor;
    private String monitoredCobaloc;

    /**
     * 
     * Create a new MonitoringClient
     * 
     * @param notifier
     *            The Notifier to use
     * @param leaseTime
     *            The lease time for objects registered with the Amentet Service
     * @param failCount
     *            The number of times a connection can fail before raising
     *            alerts
     */
    public MonitoringClient(Notifier notifier, int leaseTime, int failCount) {
        this.orb= OrbHolder.getInstance().getOrb();
        this.notifier= notifier;
        sourceIds= new HashSet<>();
        sourceIds.add(getClass().getSimpleName());
        this.leaseTime= leaseTime;
        if (leaseTime > 0) {
            monitorTimer= new Timer(getClass().getSimpleName());
        }
        state= new MonitoringClientState(notifier, failCount);
    }

    /**
     * Set the corbaloc url of the monitoredCobaloc object
     * 
     * @param corbaloc
     *            the corbaloc url of the monitoredCobaloc object
     */
    public void setMonitoredCobaloc(String corbaloc) {
        LOGGER.info("Set the Monitored object to {}", corbaloc);
        this.monitoredCobaloc= corbaloc;
    }

    /**
     * Add a component to remoteMonitor
     * 
     * @param mo
     *            The component to remoteMonitor
     */
    public void addComponent(ManagedObject mo) {
        synchronized (lock) {
            if (!monitoredComponents.containsKey(mo.getCorbaloc())) {
                LOGGER.info("Add {} to check list", mo.getCorbaloc());
                monitoredComponents.put(mo.getCorbaloc(), mo);
            }
        }
    }

    /**
     * Stop monitoring a component
     * 
     * @param mo
     *            The component to stop monitoring
     */
    public void removeComponent(ManagedObject mo) {
        synchronized (lock) {
            if (monitoredComponents.containsKey(mo.getCorbaloc())) {
                LOGGER.info("Remove {} from check list", mo.getCorbaloc());
                monitoredComponents.remove(mo.getCorbaloc());
            }
        }
    }

    /**
     * Get an array of monitoredCobaloc components' corbaloc urls
     * 
     * @return an array of corbaloc urls
     */
    public String[] getMonitoredComponentCorbalocs() {
        synchronized (lock) {
            return new LinkedList<>(monitoredComponents.keySet()).toArray(new String[0]);
        }
    }

    /**
     * Get a list of monitoredCobaloc components.
     *
     * @return a list of monitoredCobaloc components
     */
    public List getMonitoredComponents() {
        synchronized (lock) {
            return new LinkedList<>(monitoredComponents.values());
        }
    }

    /**
     * Updates all the {@link ManagedObject}s with the Amentet Monitoring
     * Service,
     * 
     * @see java.util.TimerTask#run()
     */
    @Override
    public void run() {
        if (!state.isShutdown()) {
            updateRefsToService();
        }
    }

    /**
     * Cancels the timer and un-registers all the objects with the Amentet
     * Monitoring Service
     * 
     * @see com.addc.commons.shutdown.Stoppable#shutdown()
     */
    @Override
    public void shutdown() {
        if (!state.isShutdown()) {
            state.setShutdown(true);
            monitorTimer.cancel();
            unregisterAll();
            monitoredComponents.clear();
        }
    }

    /**
     * Start active monitoring updating the Amentet Monitor Service using a
     * Timer set to 95% of the lease time.
     */
    public void start() {
        if (leaseTime > 0) {
            monitorTimer.schedule(this, 1000L, leaseTime * 950L);
        }
    }

    private void connect() {
        if ((monitoredCobaloc != null) && !state.isConnected()) {
            try {
                remoteMonitor= MonitorHelper.narrow(orb.resolve_initial_references("MonitoringService"));
                state.resetConnFailCounter();
                state.setConnected(true);
            } catch (Exception e) {
                state.incConnFailCounter(e);
            }
            if (!state.isRegistered() && state.isConnected()) {
                try {
                    remoteMonitor.componentStarts(monitoredCobaloc, leaseTime);
                    state.setRegistered(true);
                    LOGGER.info("Registered local Monitored with Amentet Monitoring Service");
                } catch (SystemException e) {
                    LOGGER.error("Failed to register with Amentet Monitoring Service", e);
                    notifier.notifyAlert(AlertFactory.getMonitorRegisterFailed(sourceIds, e.getMessage()),
                            I18nTextFactory.getTranslator(I18N_NAME));
                    state.setConnected(false);
                }
            }
        }
    }

    private void disconnect() {
        if ((monitoredCobaloc != null) && state.isConnected()) {
            if (state.isRegistered()) {
                try {
                    remoteMonitor.componentStops(monitoredCobaloc);
                    LOGGER.info("Disconnected Monitored from Amentet Monitoring Service");
                } catch (SystemException e) {
                    LOGGER.error("Failed to disconnect from Monitor", e);
                    notifier.notifyAlert(AlertFactory.getMonitorDisconnFailed(sourceIds, e.getMessage()),
                            I18nTextFactory.getTranslator(I18N_NAME));
                }
            }
            try {
                remoteMonitor._release();
            } catch (Exception e) {
                LOGGER.debug("", e);
            }
            state.setConnected(false);
            state.setRegistered(false);
        }
        remoteMonitor= null;
    }

    private void updateRefsToService() {
        connect();
        if (state.isConnected()) {
            checkComponents();
            try {
                remoteMonitor.componentRefresh(monitoredCobaloc);
            } catch (SystemException e) {
                LOGGER.error("Failed to refresh Monitor", e);
                notifier.notifyAlert(AlertFactory.getMonitorInvokeFailed(sourceIds, e.getMessage()),
                        I18nTextFactory.getTranslator(I18N_NAME));
                state.setConnected(false);
                state.setRegistered(false);
            }
        }
    }

    private void checkComponents() {
        synchronized (lock) {
            List lost= new LinkedList<>();
            for (Entry entry : monitoredComponents.entrySet()) {
                try {
                    if (entry.getValue().getObjectRef()._non_existent()) {
                        LOGGER.warn(entry.getKey() + " has died.");
                        lost.add(entry.getKey());
                    }
                } catch (SystemException e) {
                    LOGGER.error("Unexpected CORBA Exception", e);
                }
            }
            for (String cloc : lost) {
                monitoredComponents.remove(cloc);
            }
        }
    }

    private void unregisterAll() {
        connect();
        if (remoteMonitor != null) {
            try {
                remoteMonitor.componentStops(monitoredCobaloc);
                state.setRegistered(false);
            } catch (SystemException e) {
                state.setConnected(false);
            }
            disconnect();
        }
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy