CuratorZookeeperRepository.java 11.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * 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.
 */

18
package org.apache.shardingsphere.orchestration.repository.zookeeper;
19 20 21 22 23 24 25 26

import com.google.common.base.Charsets;
import com.google.common.base.Strings;
import lombok.Getter;
import lombok.Setter;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.ACLProvider;
27
import org.apache.curator.framework.api.transaction.TransactionOp;
28
import org.apache.curator.framework.recipes.cache.ChildData;
29 30
import org.apache.curator.framework.recipes.cache.CuratorCache;
import org.apache.curator.framework.recipes.cache.CuratorCacheListener;
31 32
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.utils.CloseableUtils;
33 34
import org.apache.shardingsphere.orchestration.repository.api.ConfigurationRepository;
import org.apache.shardingsphere.orchestration.repository.api.RegistryRepository;
35
import org.apache.shardingsphere.orchestration.repository.api.config.OrchestrationCenterConfiguration;
36
import org.apache.shardingsphere.orchestration.repository.api.listener.DataChangedEvent;
37
import org.apache.shardingsphere.orchestration.repository.api.listener.DataChangedEvent.ChangedType;
38
import org.apache.shardingsphere.orchestration.repository.api.listener.DataChangedEventListener;
39
import org.apache.shardingsphere.orchestration.repository.zookeeper.handler.CuratorZookeeperExceptionHandler;
40 41 42 43 44
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException.OperationTimeoutException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.data.ACL;

45
import java.nio.charset.StandardCharsets;
46 47 48 49 50
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
51
import java.util.Map.Entry;
52
import java.util.Optional;
53 54 55
import java.util.Properties;
import java.util.concurrent.TimeUnit;

56
/**
57
 * Orchestration repository of ZooKeeper.
58
 */
59
public final class CuratorZookeeperRepository implements ConfigurationRepository, RegistryRepository {
60
    
61
    private final Map<String, CuratorCache> caches = new HashMap<>();
62 63
    
    private CuratorFramework client;
孙不服 已提交
64
    
65 66
    @Getter
    @Setter
L
Liang Zhang 已提交
67
    private Properties props = new Properties();
68 69
    
    @Override
70
    public void init(final String name, final OrchestrationCenterConfiguration config) {
L
Liang Zhang 已提交
71
        ZookeeperProperties zookeeperProperties = new ZookeeperProperties(props);
M
menghaoranss 已提交
72
        client = buildCuratorClient(name, config, zookeeperProperties);
73
        initCuratorClient(zookeeperProperties);
74 75
    }
    
M
menghaoranss 已提交
76
    private CuratorFramework buildCuratorClient(final String namespace, final OrchestrationCenterConfiguration config, final ZookeeperProperties zookeeperProperties) {
77 78 79 80 81
        int retryIntervalMilliseconds = zookeeperProperties.getValue(ZookeeperPropertyKey.RETRY_INTERVAL_MILLISECONDS);
        int maxRetries = zookeeperProperties.getValue(ZookeeperPropertyKey.MAX_RETRIES);
        int timeToLiveSeconds = zookeeperProperties.getValue(ZookeeperPropertyKey.TIME_TO_LIVE_SECONDS);
        int operationTimeoutMilliseconds = zookeeperProperties.getValue(ZookeeperPropertyKey.OPERATION_TIMEOUT_MILLISECONDS);
        String digest = zookeeperProperties.getValue(ZookeeperPropertyKey.DIGEST);
82
        CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder()
孙不服 已提交
83
            .connectString(config.getServerLists())
M
menghaoranss 已提交
84 85
            .retryPolicy(new ExponentialBackoffRetry(retryIntervalMilliseconds, maxRetries, retryIntervalMilliseconds * maxRetries))
            .namespace(namespace);
孙不服 已提交
86 87
        if (0 != timeToLiveSeconds) {
            builder.sessionTimeoutMs(timeToLiveSeconds * 1000);
88
        }
孙不服 已提交
89 90
        if (0 != operationTimeoutMilliseconds) {
            builder.connectionTimeoutMs(operationTimeoutMilliseconds);
91
        }
孙不服 已提交
92 93
        if (!Strings.isNullOrEmpty(digest)) {
            builder.authorization("digest", digest.getBytes(Charsets.UTF_8))
孙不服 已提交
94 95 96 97 98 99 100 101 102 103 104 105
                .aclProvider(new ACLProvider() {
                    
                    @Override
                    public List<ACL> getDefaultAcl() {
                        return ZooDefs.Ids.CREATOR_ALL_ACL;
                    }
                    
                    @Override
                    public List<ACL> getAclForPath(final String path) {
                        return ZooDefs.Ids.CREATOR_ALL_ACL;
                    }
                });
106 107 108 109
        }
        return builder.build();
    }
    
110
    private void initCuratorClient(final ZookeeperProperties zookeeperProperties) {
111 112
        client.start();
        try {
113 114
            int retryIntervalMilliseconds = zookeeperProperties.getValue(ZookeeperPropertyKey.RETRY_INTERVAL_MILLISECONDS);
            int maxRetries = zookeeperProperties.getValue(ZookeeperPropertyKey.MAX_RETRIES);
孙不服 已提交
115
            if (!client.blockUntilConnected(retryIntervalMilliseconds * maxRetries, TimeUnit.MILLISECONDS)) {
116 117 118 119 120 121 122 123 124 125
                client.close();
                throw new OperationTimeoutException();
            }
        } catch (final InterruptedException | OperationTimeoutException ex) {
            CuratorZookeeperExceptionHandler.handleException(ex);
        }
    }
    
    @Override
    public String get(final String key) {
126
        CuratorCache cache = findTreeCache(key);
127 128 129
        if (null == cache) {
            return getDirectly(key);
        }
130 131 132
        Optional<ChildData> resultInCache = cache.get(key);
        if (resultInCache.isPresent()) {
            return null == resultInCache.get().getData() ? null : new String(resultInCache.get().getData(), Charsets.UTF_8);
133 134 135 136
        }
        return getDirectly(key);
    }
    
137
    private CuratorCache findTreeCache(final String key) {
138
        return caches.entrySet().stream().filter(entry -> key.startsWith(entry.getKey())).findFirst().map(Entry::getValue).orElse(null);
139 140
    }
    
141 142 143 144 145 146 147 148 149 150 151 152 153 154
    @Override
    public List<String> getChildrenKeys(final String key) {
        try {
            List<String> result = client.getChildren().forPath(key);
            result.sort(Comparator.reverseOrder());
            return result;
            // CHECKSTYLE:OFF
        } catch (final Exception ex) {
            // CHECKSTYLE:ON
            CuratorZookeeperExceptionHandler.handleException(ex);
            return Collections.emptyList();
        }
    }
    
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
    @Override
    public void persist(final String key, final String value) {
        try {
            if (!isExisted(key)) {
                client.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath(key, value.getBytes(Charsets.UTF_8));
            } else {
                update(key, value);
            }
            // CHECKSTYLE:OFF
        } catch (final Exception ex) {
            // CHECKSTYLE:ON
            CuratorZookeeperExceptionHandler.handleException(ex);
        }
    }
    
    private void update(final String key, final String value) {
        try {
172 173
            TransactionOp transactionOp = client.transactionOp();
            client.transaction().forOperations(transactionOp.check().forPath(key), transactionOp.setData().forPath(key, value.getBytes(StandardCharsets.UTF_8)));
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
            // CHECKSTYLE:OFF
        } catch (final Exception ex) {
            // CHECKSTYLE:ON
            CuratorZookeeperExceptionHandler.handleException(ex);
        }
    }
    
    private String getDirectly(final String key) {
        try {
            return new String(client.getData().forPath(key), Charsets.UTF_8);
            // CHECKSTYLE:OFF
        } catch (final Exception ex) {
            // CHECKSTYLE:ON
            CuratorZookeeperExceptionHandler.handleException(ex);
            return null;
        }
    }
    
    private boolean isExisted(final String key) {
        try {
            return null != client.checkExists().forPath(key);
            // CHECKSTYLE:OFF
        } catch (final Exception ex) {
            // CHECKSTYLE:ON
            CuratorZookeeperExceptionHandler.handleException(ex);
            return false;
        }
    }
    
    @Override
    public void persistEphemeral(final String key, final String value) {
        try {
            if (isExisted(key)) {
                client.delete().deletingChildrenIfNeeded().forPath(key);
            }
            client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(key, value.getBytes(Charsets.UTF_8));
            // CHECKSTYLE:OFF
        } catch (final Exception ex) {
            // CHECKSTYLE:ON
            CuratorZookeeperExceptionHandler.handleException(ex);
        }
    }
    
    @Override
218
    public void delete(final String key) {
219
        try {
220 221 222
            if (isExisted(key)) {
                client.delete().deletingChildrenIfNeeded().forPath(key);
            }
223
            // CHECKSTYLE:OFF
L
Liang Zhang 已提交
224
        } catch (final Exception ex) {
225 226 227 228 229 230
            // CHECKSTYLE:ON
            CuratorZookeeperExceptionHandler.handleException(ex);
        }
    }
    
    @Override
231
    public void watch(final String key, final DataChangedEventListener listener) {
L
Liang Zhang 已提交
232
        String path = key + "/";
233 234 235
        if (!caches.containsKey(path)) {
            addCacheData(key);
        }
236 237 238 239 240
        CuratorCache cache = caches.get(path);
        cache.listenable().addListener((type, oldData, data) -> {
            String eventPath = CuratorCacheListener.Type.NODE_DELETED == type ? oldData.getPath() : data.getPath();
            byte[] eventDataByte = CuratorCacheListener.Type.NODE_DELETED == type ? oldData.getData() : data.getData();
            DataChangedEvent.ChangedType changedType = getChangedType(type);
241
            if (ChangedType.IGNORED != changedType) {
242
                listener.onChange(new DataChangedEvent(eventPath, null == eventDataByte ? null : new String(eventDataByte, Charsets.UTF_8), changedType));
243 244 245 246
            }
        });
    }
    
247
    private void addCacheData(final String cachePath) {
248
        CuratorCache cache = CuratorCache.build(client, cachePath);
249
        try {
250
            cache.start();
251
            // CHECKSTYLE:OFF
252
        } catch (final Exception ex) {
253 254 255
            // CHECKSTYLE:ON
            CuratorZookeeperExceptionHandler.handleException(ex);
        }
256
        caches.put(cachePath + "/", cache);
257 258
    }
    
259 260 261
    private ChangedType getChangedType(final CuratorCacheListener.Type type) {
        switch (type) {
            case NODE_CREATED:
262
                return ChangedType.ADDED;
263
            case NODE_CHANGED:
264
                return ChangedType.UPDATED;
265
            case NODE_DELETED:
266
                return ChangedType.DELETED;
267
            default:
268
                return ChangedType.IGNORED;
269 270 271 272 273
        }
    }
    
    @Override
    public void close() {
274
        caches.values().forEach(CuratorCache::close);
275 276 277 278
        waitForCacheClose();
        CloseableUtils.closeQuietly(client);
    }
    
279
    /* TODO wait 500ms, close cache before close client, or will throw exception
孙不服 已提交
280
     * Because of asynchronous processing, may cause client to close
281 282
     * first and cache has not yet closed the end.
     * Wait for new version of Curator to fix this.
L
Liang Zhang 已提交
283
     * BUG address: https://issues.apache.org/jira/browse/CURATOR-157
284 285 286 287 288 289 290 291 292 293 294
     */
    private void waitForCacheClose() {
        try {
            Thread.sleep(500L);
        } catch (final InterruptedException ex) {
            Thread.currentThread().interrupt();
        }
    }
    
    @Override
    public String getType() {
T
terrymanu 已提交
295
        return "ZooKeeper";
296 297
    }
}