/*
 * Licensed to The OpenNMS Group, Inc (TOG) under one or more
 * contributor license agreements.  See the LICENSE.md file
 * distributed with this work for additional information
 * regarding copyright ownership.
 *
 * TOG licenses this file to You under the GNU Affero General
 * Public License Version 3 (the "License") or (at your option)
 * any later version.  You may not use this file except in
 * compliance with the License.  You may obtain a copy of the
 * License at:
 *
 *      https://www.gnu.org/licenses/agpl-3.0.txt
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied.  See the License for the specific
 * language governing permissions and limitations under the
 * License.
 */
package org.opennms.netmgt.poller.monitors;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.ConnectException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NoRouteToHostException;
import java.net.Socket;
import java.util.Map;

import org.opennms.core.utils.InetAddressUtils;
import org.opennms.core.utils.ParameterMap;
import org.opennms.core.utils.TimeoutTracker;
import org.opennms.netmgt.poller.MonitoredService;
import org.opennms.netmgt.poller.PollStatus;
import org.opennms.netmgt.poller.support.AbstractServiceMonitor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <P>
 * This class is designed to be used by the service poller framework to test the
 * availability of IIOP running on a Domino server service on. The class
 * implements the ServiceMonitor interface that allows it to be used along with
 * other plug-ins by the service poller framework.
 * </P>
 *
 * @author <A HREF="mailto:tarus@opennms.org">Tarus Balog </A>
 * @author <A HREF="mike@opennms.org">Mike </A>
 * @author <A HREF="weave@oculan.com">Weave </A>
 */
final public class DominoIIOPMonitor extends AbstractServiceMonitor {
    private static final Logger LOG = LoggerFactory.getLogger(DominoIIOPMonitor.class);

    /**
     * Default port.
     */
    private static final int DEFAULT_PORT = 63148;

    /**
     * Default port of where to find the IOR via HTTP
     */
    private static final int DEFAULT_IORPORT = 80;

    /**
     * Default retries.
     */
    private static final int DEFAULT_RETRY = 3;

    /**
     * Default timeout. Specifies how long (in milliseconds) to block waiting
     * for data from the monitored interface.
     */
    private static final int DEFAULT_TIMEOUT = 3000; // 3 second timeout on
                                                        // read()

    /**
     * {@inheritDoc}
     *
     * Poll the specified address for service availability.
     *
     * During the poll an attempt is made to connect on the specified port. If
     * the connection request is successful, the banner line generated by the
     * interface is parsed and if the banner text indicates that we are talking
     * to Provided that the interface's response is valid we set the service
     * status to SERVICE_AVAILABLE and return.
     */
    @Override
    public PollStatus poll(MonitoredService svc, Map<String, Object> parameters) {
        //
        // Process parameters
        //

        TimeoutTracker tracker = new TimeoutTracker(parameters, DEFAULT_RETRY, DEFAULT_TIMEOUT);
        int IORport = ParameterMap.getKeyedInteger(parameters, "ior-port", DEFAULT_IORPORT);

        // Port
        //
        int port = ParameterMap.getKeyedInteger(parameters, "port", DEFAULT_PORT);

        // Get the address instance.
        //
        InetAddress ipAddr = svc.getAddress();

        final String hostAddress = InetAddressUtils.str(ipAddr);

		LOG.debug("poll: address = {}, port = {}, {}", hostAddress, port, tracker);


        // Lets first try to the the IOR via HTTP, if we can't get that then any
        // other process that can
        // do it the right way won't be able to connect anyway
        //
        try {
            retrieveIORText(hostAddress, IORport);
        } catch (Throwable e) {
            String reason = "failed to get the corba IOR from " + ipAddr;
            LOG.debug(reason, e);
            return PollStatus.unavailable(reason);
        }

        PollStatus status = null;
        
        for(tracker.reset(); tracker.shouldRetry() && (status == null || !status.isAvailable()); tracker.nextAttempt()) {
            Socket socket = null;
            try {
                //
                // create a connected socket
                //
                
                tracker.startAttempt();
                
                socket = new Socket();
                socket.connect(new InetSocketAddress(ipAddr, port), tracker.getConnectionTimeout());
                socket.setSoTimeout(tracker.getSoTimeout());

                LOG.debug("DominoIIOPMonitor: connected to host: {} on port: {}", ipAddr, port);

                // got here so its up...
                
                return PollStatus.up(tracker.elapsedTimeInMillis());
                
            } catch (NoRouteToHostException e) {
                String reason = " No route to host exception for address " + hostAddress;
                LOG.debug(reason, e);
                status = PollStatus.unavailable(reason);
            } catch (InterruptedIOException e) {
                String reason = "did not connect to host with " + tracker;
                LOG.debug(reason);
                status = PollStatus.unavailable(reason);
            } catch (ConnectException e) {
                String reason = "Connection exception for address: " + ipAddr+" : "+e.getMessage();
                LOG.debug(reason);
                status = PollStatus.unavailable(reason);
            } catch (IOException e) {
                String reason = "IOException while polling address: " + ipAddr+" : "+e.getMessage();
                LOG.debug(reason);
                status = PollStatus.unavailable(reason);
            } finally {
                try {
                    // Close the socket
                    if (socket != null)
                        socket.close();
                } catch (IOException e) {
                    e.fillInStackTrace();

                    LOG.debug("DominoIIOPMonitor: Error closing socket.", e);
                }
            }
        }

        //
        // return the status of the service
        //
        return status;
    }

    /**
     * Method used to retrieve the IOR string from the Domino server.
     * 
     * @param host
     *            the host name which has the IOR
     * @param port
     *            the port to find the IOR via HTTP
     */
    private String retrieveIORText(String host, int port) throws IOException {
        String IOR = "";
        java.net.URL u = new java.net.URL("http://" + host + ":" + port + "/diiop_ior.txt");
        java.io.InputStream is = u.openStream();
        java.io.BufferedReader dis = new java.io.BufferedReader(new java.io.InputStreamReader(is));
        boolean done = false;
        while (!done) {
            String line = dis.readLine();
            if (line == null) {
                // end of stream
                done = true;
            } else {
                IOR += line;
                if (IOR.startsWith("IOR:")) {
                    // the IOR does not span a line, so we're done
                    done = true;
                }
            }
        }
        dis.close();

        if (!IOR.startsWith("IOR:"))
            throw new IOException("Invalid IOR: " + IOR);

        return IOR;
    }
    
}
