001/*
002 * (C) Copyright 2013 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Florent Guillaume
018 */
019package org.nuxeo.ecm.core.redis;
020
021import org.apache.commons.lang.StringUtils;
022import org.apache.commons.logging.Log;
023import org.apache.commons.logging.LogFactory;
024import org.nuxeo.common.xmap.annotation.XNode;
025import org.nuxeo.common.xmap.annotation.XObject;
026import org.nuxeo.ecm.core.api.NuxeoException;
027import redis.clients.jedis.Jedis;
028import redis.clients.jedis.JedisPool;
029import redis.clients.jedis.JedisPoolConfig;
030import redis.clients.jedis.Protocol;
031import redis.clients.jedis.exceptions.JedisException;
032
033/**
034 * Descriptor for a Redis configuration.
035 *
036 * @since 5.8
037 */
038@XObject("server")
039public class RedisServerDescriptor extends RedisPoolDescriptor {
040
041    private static final Log log = LogFactory.getLog(RedisServerDescriptor.class);
042
043    @XNode("host")
044    public String host;
045
046    @XNode("port")
047    public int port = Protocol.DEFAULT_PORT;
048
049    @XNode("failoverTimeout")
050    public int failoverTimeout = 300;
051
052    protected boolean canConnect(String name, int port) {
053        try (Jedis jedis = new Jedis(name, port)) {
054            if (StringUtils.isNotBlank(password)) {
055                jedis.auth(password);
056            }
057            return canPing(jedis);
058        }
059    }
060
061    protected boolean canPing(Jedis jedis) {
062        try {
063            String pong = jedis.ping();
064            return "PONG".equals(pong);
065        } catch (JedisException cause) {
066            log.debug("Exception during ping", cause);
067            return false;
068        }
069    }
070
071    @Override
072    public RedisExecutor newExecutor() {
073        if (!canConnect(host, port)) {
074            throw new NuxeoException("Cannot connect to Redis host: " + host + ":" + port);
075        }
076        JedisPoolConfig conf = new JedisPoolConfig();
077        conf.setMaxTotal(maxTotal);
078        conf.setMaxIdle(maxIdle);
079        RedisExecutor base = new RedisPoolExecutor(new JedisPool(conf, host, port, timeout,
080                StringUtils.defaultIfBlank(password, null), database));
081        return new RedisFailoverExecutor(failoverTimeout, base);
082    }
083
084}