aboutsummaryrefslogtreecommitdiffstats
path: root/sdclient/discovery-service/src/main/java/org/onap/msb/sdclient/wrapper/ConsulClientApp.java
blob: 28937bc0ca31b23fe4a6eccb0a93a852636afa1a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
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
/**
 * Copyright 2016-2017 ZTE, Inc. and others.
 *
 * Licensed 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.
 */
package org.onap.msb.sdclient.wrapper;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.onap.msb.sdclient.core.KeyVaulePair;
import org.onap.msb.sdclient.core.MicroServiceFullInfo;
import org.onap.msb.sdclient.core.NodeInfo;
import org.onap.msb.sdclient.wrapper.consul.Consul;
import org.onap.msb.sdclient.wrapper.consul.HealthClient;
import org.onap.msb.sdclient.wrapper.consul.cache.HealthCache;
import org.onap.msb.sdclient.wrapper.consul.model.health.Service;
import org.onap.msb.sdclient.wrapper.consul.model.health.ServiceHealth;
import org.onap.msb.sdclient.wrapper.util.JacksonJsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ConsulClientApp {

    private final Consul consul;
    private final HealthClient healthClient;
    // private AtomicReference<List<HealthCache>> cacheList = new
    // AtomicReference<List<HealthCache>>(
    // new ArrayList<HealthCache>());


    private static final Logger LOGGER = LoggerFactory.getLogger(ConsulClientApp.class);

    public ConsulClientApp(String ip, int port) {
        URL url = null;
        try {
            url = new URL("http", ip, port, "");
        } catch (MalformedURLException e1) {
            // TODO Auto-generated catch block
            LOGGER.error("start  ConsulClientApp throw exception", e1);
            throw new RuntimeException(e1);
        }
        this.consul = Consul.builder().withUrl(url).build(); // connect to Consul on localhost
        this.healthClient = consul.healthClient();
    }

    public Consul getConsul() {
        return consul;
    }



    /**
     * @Title startHealthNodeListen
     * @Description TODO(开启某个服务的node变化监听,只返回健康状态服务)
     * @param serviceName
     * @return
     * @return HealthCache
     */
    public HealthCache startHealthNodeListen(final String serviceName) {
        final HealthCache healthCache = HealthCache.newCache(healthClient, serviceName, 30);
        healthCache.addListener(new HealthCache.Listener<String, ServiceHealth>() {
            @Override
            public void notify(Map<String, ServiceHealth> newValues) {
                // do Something with updated server map
                LOGGER.info(serviceName + "--new node notify--");


                if (newValues.isEmpty()) {
                    LOGGER.warn(serviceName + "--nodeList is Empty--");
                    PublishAddressWrapper.publishApigateWayList.remove(serviceName);

                    try {
                        healthCache.stop();
                        LOGGER.info(serviceName + " Node Listen stopped");
                    } catch (Exception e) {
                        LOGGER.error(serviceName + " Node Listen stop throw exception", e);
                    }

                    return;
                }
                // 服务发现变化
                List<MicroServiceFullInfo> nodeAddressList = new ArrayList<MicroServiceFullInfo>();
                for (Map.Entry<String, ServiceHealth> entry : newValues.entrySet()) {

                    MicroServiceFullInfo microServiceInfo = new MicroServiceFullInfo();

                    ServiceHealth value = (ServiceHealth) entry.getValue();
                    Service service = value.getService();

                    NodeInfo node = new NodeInfo();
                    node.setIp(service.getAddress());
                    node.setPort(String.valueOf(service.getPort()));
                    Set<NodeInfo> nodes = new HashSet<NodeInfo>();
                    nodes.add(node);
                    microServiceInfo.setNodes(nodes);


                    microServiceInfo.setServiceName(serviceName);

                    try {
                        List<String> tagList = service.getTags();


                        for (String tag : tagList) {

                            if (tag.startsWith("\"ns\"")) {
                                String ms_ns_json = tag.split("\"ns\":")[1];
                                Map<String, String> nsMap =
                                                (Map<String, String>) JacksonJsonUtil.jsonToBean(ms_ns_json, Map.class);

                                if (nsMap.get("namespace") != null) {
                                    microServiceInfo.setNamespace(nsMap.get("namespace"));
                                }

                                continue;
                            }

                            if (tag.startsWith("\"labels\"")) {
                                String ms_labels_json = "{" + tag.split("\"labels\":\\{")[1];
                                Map<String, String> labelMap = (Map<String, String>) JacksonJsonUtil
                                                .jsonToBean(ms_labels_json, Map.class);

                                List<String> nodeLabels = new ArrayList<String>();
                                for (Map.Entry<String, String> labelEntry : labelMap.entrySet()) {
                                    if ("visualRange".equals(labelEntry.getKey())) {
                                        microServiceInfo.setVisualRange(labelEntry.getValue());
                                    } else if ("network_plane_type".equals(labelEntry.getKey())) {
                                        microServiceInfo.setNetwork_plane_type(labelEntry.getValue());
                                    } else {
                                        nodeLabels.add(labelEntry.getKey() + ":" + labelEntry.getValue());
                                    }

                                }

                                microServiceInfo.setLabels(nodeLabels);
                                continue;
                            }

                            if (tag.startsWith("\"metadata\"")) {
                                String ms_metadata_json = "{" + tag.split("\"metadata\":\\{")[1];
                                Map<String, String> metadataMap = (Map<String, String>) JacksonJsonUtil
                                                .jsonToBean(ms_metadata_json, Map.class);

                                List<KeyVaulePair> ms_metadata = new ArrayList<KeyVaulePair>();


                                for (Map.Entry<String, String> metadataEntry : metadataMap.entrySet()) {
                                    KeyVaulePair keyVaulePair = new KeyVaulePair();
                                    keyVaulePair.setKey(metadataEntry.getKey());
                                    keyVaulePair.setValue(metadataEntry.getValue());
                                    ms_metadata.add(keyVaulePair);
                                }
                                microServiceInfo.setMetadata(ms_metadata);
                                continue;
                            }

                        }


                    } catch (Exception e) {
                        LOGGER.error(serviceName + " read tag  throw exception", e);
                    }

                    nodeAddressList.add(microServiceInfo);
                }

                PublishAddressWrapper.publishApigateWayList.put(serviceName, nodeAddressList);

            }
        });
        try {
            LOGGER.info(serviceName + " Node Listen start");
            // cacheList.get().add(healthCache);
            healthCache.start();

        } catch (Exception e) {
            // TODO Auto-generated catch block
            LOGGER.error(serviceName + " Node Listen start throw exception", e);
        }

        return healthCache;
    }



    public static void main(String[] args) {
        ConsulClientApp consulTest = new ConsulClientApp("127.0.0.1", 8500);
        // 监听服务变化
        consulTest.startHealthNodeListen("apigateway");


    }


}