2 * Copyright 2016 2015-2016 ZTE, Inc. and others. All rights reserved.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package org.openo.msb.wrapper.consul.cache;
19 import static com.google.common.base.Preconditions.checkState;
21 import java.math.BigInteger;
22 import java.util.HashSet;
23 import java.util.Iterator;
24 import java.util.List;
27 import java.util.concurrent.CopyOnWriteArrayList;
28 import java.util.concurrent.CountDownLatch;
29 import java.util.concurrent.Executors;
30 import java.util.concurrent.ScheduledExecutorService;
31 import java.util.concurrent.TimeUnit;
32 import java.util.concurrent.atomic.AtomicReference;
34 import org.openo.msb.wrapper.consul.async.ConsulResponseCallback;
35 import org.openo.msb.wrapper.consul.model.ConsulResponse;
36 import org.openo.msb.wrapper.consul.model.catalog.CatalogService;
37 import org.openo.msb.wrapper.consul.model.catalog.ServiceInfo;
38 import org.openo.msb.wrapper.consul.option.QueryOptions;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
42 import com.google.common.annotations.VisibleForTesting;
43 import com.google.common.collect.ImmutableList;
46 * A cache structure that can provide an up-to-date read-only
47 * map backed by consul data
51 public class ConsulCache4Map<K, V> {
53 enum State {latent, starting, started, stopped }
55 private final static Logger LOGGER = LoggerFactory.getLogger(ConsulCache4Map.class);
57 private final AtomicReference<BigInteger> latestIndex = new AtomicReference<BigInteger>(null);
58 private final AtomicReference<ImmutableList<ServiceInfo>> lastResponse = new AtomicReference<ImmutableList<ServiceInfo>>(ImmutableList.<ServiceInfo>of());
59 private final AtomicReference<State> state = new AtomicReference<State>(State.latent);
60 private final CountDownLatch initLatch = new CountDownLatch(1);
61 private final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
62 private final CopyOnWriteArrayList<Listener<K, V>> listeners = new CopyOnWriteArrayList<Listener<K, V>>();
64 private final CallbackConsumer<V> callBackConsumer;
65 private final ConsulResponseCallback<Map<String,List<String>>> responseCallback;
67 ConsulCache4Map(CallbackConsumer<V> callbackConsumer) {
68 this( callbackConsumer, 10, TimeUnit.SECONDS);
72 CallbackConsumer<V> callbackConsumer,
73 final long backoffDelayQty,
74 final TimeUnit backoffDelayUnit) {
76 this.callBackConsumer = callbackConsumer;
78 this.responseCallback = new ConsulResponseCallback<Map<String,List<String>>>() {
80 public void onComplete(ConsulResponse<Map<String,List<String>>> consulResponse) {
85 updateIndex(consulResponse);
86 ImmutableList<ServiceInfo> full = convertToList(consulResponse);
87 List<ServiceInfo> oldList=lastResponse.get();
88 boolean changed = !full.equals(lastResponse.get());
89 // LOGGER.info("service changed:"+changed+"----"+full);
92 lastResponse.set(full);
96 for (Listener<K, V> l : listeners) {
97 l.notify(oldList,full);
101 if (state.compareAndSet(State.starting, State.started)) {
102 initLatch.countDown();
108 public void onFailure(Throwable throwable) {
113 LOGGER.error(String.format("Error getting response from consul. will retry in %d %s", backoffDelayQty, backoffDelayUnit), throwable);
115 executorService.schedule(new Runnable() {
120 }, backoffDelayQty, backoffDelayUnit);
125 public void start() throws Exception {
126 checkState(state.compareAndSet(State.latent, State.starting),"Cannot transition from state %s to %s", state.get(), State.starting);
130 public void stop() throws Exception {
131 State previous = state.getAndSet(State.stopped);
132 if (previous != State.stopped) {
133 executorService.shutdownNow();
137 private void runCallback() {
139 callBackConsumer.consume(latestIndex.get(), responseCallback);
143 private boolean isRunning() {
144 return state.get() == State.started || state.get() == State.starting;
147 public boolean awaitInitialized(long timeout, TimeUnit unit) throws InterruptedException {
148 return initLatch.await(timeout, unit);
151 public ImmutableList<ServiceInfo> getMap() {
152 return lastResponse.get();
156 ImmutableList<ServiceInfo> convertToList(final ConsulResponse<Map<String,List<String>>> response) {
157 if (response == null || response.getResponse() == null || response.getResponse().isEmpty()) {
158 return ImmutableList.of();
161 final ImmutableList.Builder<ServiceInfo> builder = ImmutableList.builder();
162 final Set<String> keySet = new HashSet<>();
164 for(Map.Entry<String,List<String>> entry : response.getResponse().entrySet()) {
166 String key = entry.getKey();
168 if (key != null && !"consul".equals(key)) {
169 if (!keySet.contains(key)) {
170 ServiceInfo serviceInfo=new ServiceInfo();
171 serviceInfo.setServiceName(key);
173 List<String> value=entry.getValue();
174 for(String tag:value){
176 if(tag.startsWith("version")){
178 if(tag.split(":").length==2)
180 version = tag.split(":")[1];
186 serviceInfo.setVersion(version);
191 builder.add(serviceInfo);
193 System.out.println(key.toString());
194 LOGGER.warn("Duplicate service encountered. May differ by tags. Try using more specific tags? " + key.toString());
202 return builder.build();
205 private void updateIndex(ConsulResponse<Map<String,List<String>>> consulResponse) {
206 if (consulResponse != null && consulResponse.getIndex() != null) {
207 this.latestIndex.set(consulResponse.getIndex());
211 protected static QueryOptions watchParams(BigInteger index, int blockSeconds) {
213 return QueryOptions.BLANK;
215 return QueryOptions.blockSeconds(blockSeconds, index).build();
220 * passed in by creators to vary the content of the cached values
224 protected interface CallbackConsumer<V> {
225 void consume(BigInteger index, ConsulResponseCallback<Map<String,List<String>>> callback);
229 * Implementers can register a listener to receive
230 * a new map when it changes
234 public interface Listener<K, V> {
235 void notify(List<ServiceInfo> oldValues,List<ServiceInfo> newValues);
238 public boolean addListener(Listener<K, V> listener) {
239 boolean added = listeners.add(listener);
240 if (state.get() == State.started) {
241 listener.notify(lastResponse.get(),lastResponse.get());
246 public boolean removeListener(Listener<K, V> listener) {
247 return listeners.remove(listener);
251 protected State getState() {