001/**
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *      http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018
019package org.apache.oozie.event.listener;
020
021import org.apache.curator.framework.CuratorFramework;
022import org.apache.curator.framework.state.ConnectionState;
023import org.apache.curator.framework.state.ConnectionStateListener;
024import org.apache.oozie.service.ConfigurationService;
025import org.apache.oozie.service.Services;
026import org.apache.oozie.util.XLog;
027
028/**
029 * ZKConnectionListener listens on ZK connection status.
030 */
031public class ZKConnectionListener implements ConnectionStateListener {
032
033    private XLog LOG = XLog.getLog(getClass());
034    private static ConnectionState connectionState;
035    public static final String CONF_SHUTDOWN_ON_TIMEOUT = "oozie.zookeeper.server.shutdown.ontimeout";
036
037    public ZKConnectionListener() {
038        LOG.info("ZKConnectionListener started");
039    }
040
041    @Override
042    public void stateChanged(final CuratorFramework client, final ConnectionState newState) {
043        connectionState = newState;
044        LOG.trace("ZK connection status  = " + newState.toString());
045        // if (newState == ConnectionState.CONNECTED) {
046        // ZK connected
047        // }
048        if (newState == ConnectionState.SUSPENDED) {
049            LOG.warn("ZK connection is suspended, waiting to reconnect.");
050        }
051
052        if (newState == ConnectionState.RECONNECTED) {
053            // ZK connected is reconnected.
054            LOG.warn("ZK connection is reestablished");
055        }
056
057        if (newState == ConnectionState.LOST) {
058            LOG.fatal("ZK is not reconnected");
059            if (ConfigurationService.getBoolean(CONF_SHUTDOWN_ON_TIMEOUT)) {
060                LOG.fatal("Shutting down Oozie server");
061                Services.get().destroy();
062                System.exit(1);
063            }
064        }
065    }
066
067    public static ConnectionState getZKConnectionState() {
068        return connectionState;
069    }
070}