2 * Copyright 2016 ZTE, Inc. and others.
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.onap.msb.sdclient.wrapper;
18 import java.net.MalformedURLException;
20 import java.util.ArrayList;
21 import java.util.HashMap;
22 import java.util.HashSet;
23 import java.util.List;
27 import org.onap.msb.sdclient.core.KeyVaulePair;
28 import org.onap.msb.sdclient.core.MicroServiceFullInfo;
29 import org.onap.msb.sdclient.core.NodeInfo;
30 import org.onap.msb.sdclient.wrapper.consul.Consul;
31 import org.onap.msb.sdclient.wrapper.consul.HealthClient;
32 import org.onap.msb.sdclient.wrapper.consul.cache.HealthCache;
33 import org.onap.msb.sdclient.wrapper.consul.model.health.Service;
34 import org.onap.msb.sdclient.wrapper.consul.model.health.ServiceHealth;
35 import org.onap.msb.sdclient.wrapper.util.DiscoverUtil;
36 import org.onap.msb.sdclient.wrapper.util.JacksonJsonUtil;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
40 public class ConsulClientApp {
42 private final Consul consul;
43 private final HealthClient healthClient;
44 // private AtomicReference<List<HealthCache>> cacheList = new AtomicReference<List<HealthCache>>(
45 // new ArrayList<HealthCache>());
48 private static final Logger LOGGER = LoggerFactory.getLogger(ConsulClientApp.class);
50 public ConsulClientApp(String ip, int port) {
53 url = new URL("http", ip, port, "");
54 } catch (MalformedURLException e1) {
55 // TODO Auto-generated catch block
56 LOGGER.error("start ConsulClientApp throw exception", e1);
57 throw new RuntimeException(e1);
59 this.consul = Consul.builder().withUrl(url).build(); // connect to Consul on localhost
60 this.healthClient = consul.healthClient();
63 public Consul getConsul() {
72 * @Title startHealthNodeListen
73 * @Description TODO(开启某个服务的node变化监听,只返回健康状态服务)
78 public HealthCache startHealthNodeListen(final String serviceName) {
79 final HealthCache healthCache = HealthCache.newCache(healthClient, serviceName, 30);
80 healthCache.addListener(new HealthCache.Listener<String, ServiceHealth>() {
82 public void notify(Map<String, ServiceHealth> newValues) {
83 // do Something with updated server map
84 LOGGER.info(serviceName + "--new node notify--");
87 if (newValues.isEmpty()) {
88 LOGGER.warn(serviceName + "--nodeList is Empty--");
89 PublishAddressWrapper.publishApigateWayList.remove(serviceName);
93 LOGGER.info(serviceName + " Node Listen stopped");
94 } catch (Exception e) {
95 LOGGER.error(serviceName + " Node Listen stop throw exception", e);
101 List<MicroServiceFullInfo> nodeAddressList=new ArrayList<MicroServiceFullInfo>();
102 for (Map.Entry<String, ServiceHealth> entry : newValues.entrySet()) {
104 MicroServiceFullInfo microServiceInfo = new MicroServiceFullInfo();
106 ServiceHealth value = (ServiceHealth) entry.getValue();
107 Service service = value.getService();
109 NodeInfo node = new NodeInfo();
110 node.setIp(service.getAddress());
111 node.setPort(String.valueOf(service.getPort()));
112 Set<NodeInfo> nodes = new HashSet<NodeInfo>();
114 microServiceInfo.setNodes(nodes);
117 microServiceInfo.setServiceName(serviceName);
120 List<String> tagList = service.getTags();
123 for (String tag : tagList) {
125 if (tag.startsWith("\"ns\"")) {
126 String ms_ns_json = tag.split("\"ns\":")[1];
127 Map<String, String> nsMap =
128 (Map<String, String>) JacksonJsonUtil.jsonToBean(ms_ns_json, Map.class);
130 if (nsMap.get("namespace") != null) {
131 microServiceInfo.setNamespace(nsMap.get("namespace"));
137 if (tag.startsWith("\"labels\"")) {
138 String ms_labels_json = "{"+tag.split("\"labels\":\\{")[1];
139 Map<String, String> labelMap =
140 (Map<String, String>) JacksonJsonUtil.jsonToBean(ms_labels_json, Map.class);
142 List<String> nodeLabels = new ArrayList<String>();
143 for (Map.Entry<String, String> labelEntry : labelMap.entrySet()) {
144 if ("visualRange".equals(labelEntry.getKey())) {
145 microServiceInfo.setVisualRange(labelEntry.getValue());
146 } else if ("network_plane_type".equals(labelEntry.getKey())) {
147 microServiceInfo.setNetwork_plane_type( labelEntry.getValue());
149 nodeLabels.add(labelEntry.getKey() + ":" + labelEntry.getValue());
154 microServiceInfo.setLabels(nodeLabels);
158 if (tag.startsWith("\"metadata\"")) {
159 String ms_metadata_json = "{"+tag.split("\"metadata\":\\{")[1];
160 Map<String, String> metadataMap =
161 (Map<String, String>) JacksonJsonUtil.jsonToBean(ms_metadata_json, Map.class);
163 List<KeyVaulePair> ms_metadata = new ArrayList<KeyVaulePair>();
166 for (Map.Entry<String, String> metadataEntry : metadataMap.entrySet()) {
167 KeyVaulePair keyVaulePair = new KeyVaulePair();
168 keyVaulePair.setKey(metadataEntry.getKey());
169 keyVaulePair.setValue(metadataEntry.getValue());
170 ms_metadata.add(keyVaulePair);
172 microServiceInfo.setMetadata(ms_metadata);
179 } catch (Exception e) {
180 LOGGER.error(serviceName + " read tag throw exception", e);
183 nodeAddressList.add(microServiceInfo);
186 PublishAddressWrapper.publishApigateWayList.put(serviceName, nodeAddressList);
191 LOGGER.info(serviceName + " Node Listen start");
192 // cacheList.get().add(healthCache);
195 } catch (Exception e) {
196 // TODO Auto-generated catch block
197 LOGGER.error(serviceName + " Node Listen start throw exception", e);
205 public static void main(String[] args) {
206 ConsulClientApp consulTest = new ConsulClientApp("127.0.0.1", 8500);
208 consulTest.startHealthNodeListen("apigateway");