aboutsummaryrefslogtreecommitdiffstats
path: root/msb-core/apiroute/apiroute-service/src/main/java/org/openo/msb/ConsulClientApp.java
blob: 4986e548bff2b662228e2662d38273d8f5d5b602 (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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
/**
 * Copyright 2016 2015-2016 ZTE, Inc. and others. All rights reserved.
 *
 * 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.openo.msb;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

import org.apache.commons.lang3.StringUtils;
import org.openo.msb.api.MicroServiceFullInfo;
import org.openo.msb.api.MicroServiceInfo;
import org.openo.msb.api.Node;
import org.openo.msb.wrapper.MicroServiceWrapper;
import org.openo.msb.wrapper.consul.CatalogClient;
import org.openo.msb.wrapper.consul.Consul;
import org.openo.msb.wrapper.consul.HealthClient;
import org.openo.msb.wrapper.consul.cache.CatalogCache;
import org.openo.msb.wrapper.consul.cache.ConsulCache;
import org.openo.msb.wrapper.consul.cache.ConsulCache4Map;
import org.openo.msb.wrapper.consul.cache.HealthCache;
import org.openo.msb.wrapper.consul.cache.ServiceCache;
import org.openo.msb.wrapper.consul.model.catalog.CatalogService;
import org.openo.msb.wrapper.consul.model.catalog.ServiceInfo;
import org.openo.msb.wrapper.consul.model.health.Service;
import org.openo.msb.wrapper.consul.model.health.ServiceHealth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ConsulClientApp {

    private final Consul consul;
    private final CatalogClient catalogClient;
    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.catalogClient = consul.catalogClient();
        this.healthClient = consul.healthClient();
    }

    public Consul getConsul() {
        return consul;
    }

    public CatalogClient getCatalogClient() {
        return catalogClient;
    }

    private void stopNodeListen(String serviceName) {
        try {

            ListIterator<HealthCache> cacheListLit = cacheList.get().listIterator();
            while (cacheListLit.hasNext()) {
                HealthCache cache = (HealthCache) cacheListLit.next();
                if (cache.getServiceName().equals(serviceName)) {

                    cache.stop();
                    cacheListLit.remove();
                    LOGGER.info(cache.getServiceName() + " NodeListen stoped");
                    break;
                }
            }

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


    }

    /**
     * @Title startServiceListen
     * @Description TODO(Open the consul registration services to monitor)
     * @return void
     */
    public void startServiceListen() {
        final ServiceCache serviceCache = ServiceCache.newCache(catalogClient, 30);
        serviceCache.addListener(new ConsulCache4Map.Listener<String, Map<String, List<String>>>() {
            @Override
            public void notify(List<ServiceInfo> oldValues, List<ServiceInfo> newValues) {
                // do Something with updated server List
                LOGGER.info("--new service notify--");

                List<ServiceInfo> deRegisterServiceList = getDiffrent(oldValues, newValues);


                for (ServiceInfo serviceInfo : deRegisterServiceList) {
                    try {
                       
                            MicroServiceWrapper.getInstance().deleteMicroService(
                                    serviceInfo.getServiceName(), serviceInfo.getVersion());
                        

                        stopNodeListen(serviceInfo.getServiceName());
                        LOGGER.info("Cancel MicroServiceInfo and stop node listen successs:"
                                + serviceInfo.getServiceName());
                    } catch (Exception e) {
                        LOGGER.error("Cancel MicroServiceInfo and stop node listen FAIL : ", e);

                    }

                }


                List<ServiceInfo> registerServiceList = getDiffrent(newValues, oldValues);
                for (ServiceInfo serviceInfo : registerServiceList) {

                    // if (deRegisterServiceList.contains(serviceInfo)) continue;


                    LOGGER.info(" new serviceName:" + serviceInfo.getServiceName() + "  version:"
                            + serviceInfo.getVersion());
                    // Open Node to monitor new registration service
                    startHealthNodeListen(serviceInfo.getServiceName(), serviceInfo.getVersion());

                }


            }

        });

        try {
            LOGGER.info("start...consul ... service..Listening.");
            serviceCache.start();

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


    /**
     * @Title startHealthNodeListen
     * @Description TODO(Open a service node changes to monitor, only to return to health service)
     * @param serviceName
     * @return
     * @return HealthCache
     */
    private HealthCache startHealthNodeListen(final String serviceName, final String version) {
        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.info(serviceName + "--nodeList is Empty--");

                  
                        MicroServiceWrapper.getInstance().deleteMicroService(serviceName, version);
                  
                    // try {
                    // healthCache.stop();
                    // } catch (Exception e) {
                    // LOGGER.equals(serviceName+"-- stop Node error:"+e.getMessage());
                    // }

                } else {

                    MicroServiceInfo microServiceInfo = new MicroServiceInfo();
                    HashSet<Node> nodes = new HashSet<Node>();
                    String url = "";
                    String version = "", visualRange = "", protocol = "",lb_policy="";

                    for (Map.Entry<String, ServiceHealth> entry : newValues.entrySet()) {
                        String nodeName = entry.getKey().toString();
                        ServiceHealth value = (ServiceHealth) entry.getValue();

                        Node node = new Node();
                        Service service = value.getService();
                        node.setIp(service.getAddress());
                        node.setPort(String.valueOf(service.getPort()));


                        try {
                            List<String> tagList = service.getTags();
                            for (String tag : tagList) {
                                if (tag.startsWith("url")) {
                                    if (tag.split(":").length == 2) {
                                        url = tag.split(":")[1];
                                    } else {
                                        url = "";
                                    }


                                    continue;
                                }
                                if (tag.startsWith("version")) {
                                    if (tag.split(":").length == 2) {
                                        version = tag.split(":")[1];
                                    } else {
                                        version = "";
                                    }
                                    continue;
                                }
                                if (tag.startsWith("protocol")) {
                                    protocol = tag.split(":")[1];
                                    continue;
                                }
                                if (tag.startsWith("visualRange")) {
                                    visualRange = tag.split(":")[1];
                                    continue;
                                }
                                
                                if (tag.startsWith("lb_policy")) {
                                    lb_policy = tag.split(":")[1];
                                    continue;
                                }

                            }


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

                        nodes.add(node);
                    }

                    microServiceInfo.setNodes(nodes);
                    microServiceInfo.setProtocol(protocol);
                    microServiceInfo.setUrl(url);
                    microServiceInfo.setServiceName(serviceName);
                    microServiceInfo.setLb_policy(lb_policy);
                    if (!visualRange.isEmpty()) {
                        microServiceInfo.setVisualRange(visualRange);
                    }
                    microServiceInfo.setVersion(version);

                    try {
                        MicroServiceFullInfo microServiceFullInfo =
                                MicroServiceWrapper.getInstance().saveMicroServiceInstance(
                                        microServiceInfo, false, "", "");
                        LOGGER.info("register MicroServiceInfo successs:"
                                + microServiceFullInfo.getServiceName());
                    } catch (Exception e) {
                        LOGGER.error("register MicroServiceInfo FAIL : " + serviceName, e);

                    }
                }
            }
        });
        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;
    }

    /**
     * @Title startNodeListen
     * @Description TODO(Open a service node changes to monitor)
     * @param serviceName
     * @return
     * @return CatalogCache
     */
    @Deprecated
    private CatalogCache startNodeListen(final String serviceName) {
        final CatalogCache catalogCache = CatalogCache.newCache(catalogClient, serviceName, 30);
        catalogCache.addListener(new ConsulCache.Listener<String, CatalogService>() {
            @Override
            public void notify(Map<String, CatalogService> newValues) {
                // do Something with updated server map
                System.out.println(serviceName + "--new node notify--");
                LOGGER.info(serviceName + "--new node notify--");

                if (newValues.isEmpty()) {
                    System.out.println(serviceName + "-- nodeList is Empty--");
                    LOGGER.info(serviceName + "--nodeList is Empty-stop service[" + serviceName
                            + "] listen-");
                    try {
                        catalogCache.stop();
                    } catch (Exception e) {
                        LOGGER.equals(serviceName + "-- stop Node error:" + e.getMessage());
                    }

                } else {

                    MicroServiceInfo microServiceInfo = new MicroServiceInfo();
                    HashSet<Node> nodes = new HashSet<Node>();
                    String url = "";
                    String version = "", visualRange = "", protocol = "";

                    for (Map.Entry<String, CatalogService> entry : newValues.entrySet()) {
                        String nodeName = entry.getKey().toString();
                        CatalogService value = (CatalogService) entry.getValue();

                        Node node = new Node();
                        node.setIp(value.getServiceAddress());
                        node.setPort(String.valueOf(value.getServicePort()));


                        try {
                            List<String> tagList = value.getServiceTags();
                            for (String tag : tagList) {
                                if (tag.startsWith("url")) {
                                    if (tag.split(":").length == 2) {
                                        url = tag.split(":")[1];
                                    } else {
                                        url = "";
                                    }


                                    continue;
                                }
                                if (tag.startsWith("version")) {
                                    if (tag.split(":").length == 2) {
                                        version = tag.split(":")[1];
                                    } else {
                                        version = "";
                                    }
                                    continue;
                                }
                                if (tag.startsWith("protocol")) {
                                    protocol = tag.split(":")[1];
                                    continue;
                                }
                                if (tag.startsWith("visualRange")) {
                                    visualRange = tag.split(":")[1];
                                    continue;
                                }
                                if (tag.startsWith("ttl")) {
                                    int ttl = Integer.parseInt(tag.split(":")[1]);
                                    node.setTtl(ttl);
                                    continue;
                                }
                            }


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

                        nodes.add(node);


                        System.out.println(nodeName + ":" + value.getServiceAddress() + " "
                                + value.getServicePort() + " " + value.getServiceTags());
                    }

                    microServiceInfo.setNodes(nodes);
                    microServiceInfo.setProtocol(protocol);
                    microServiceInfo.setUrl(url);
                    microServiceInfo.setServiceName(serviceName);
                    if (!visualRange.isEmpty()) {
                        microServiceInfo.setVisualRange(visualRange);
                    }
                    microServiceInfo.setVersion(version);

                    try {
                        MicroServiceFullInfo microServiceFullInfo =
                                MicroServiceWrapper.getInstance().saveMicroServiceInstance(
                                        microServiceInfo, false, "", "");
                        LOGGER.info("register MicroServiceInfo successs:" + microServiceFullInfo);
                        System.out.println("register MicroServiceInfo successs:" + serviceName);
                    } catch (Exception e) {
                        LOGGER.error("register MicroServiceInfo FAIL : ", e);

                    }
                }
            }
        });
        try {
            System.out.println(serviceName + " Node Listen start");
            LOGGER.info(serviceName + " Node Listen start");
            catalogCache.start();

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

        return catalogCache;
    }


    /**
     * @Title getDiffrent
     * @Description TODO(Extract the list1 and list2 different data sets)
     * @param list1
     * @param list2
     * @return
     * @return List<String>
     */
    private List<ServiceInfo> getDiffrent(List<ServiceInfo> list1, List<ServiceInfo> list2) {

        List<ServiceInfo> diff = new ArrayList<ServiceInfo>();



        for (ServiceInfo serviceInfo : list1) {
            if (!list2.contains(serviceInfo)) {
                diff.add(serviceInfo);
            }
        }

        return diff;
    }

    public static void main(String[] args) {
        ConsulClientApp consulTest = new ConsulClientApp("127.0.0.1", 10081);
        consulTest.startServiceListen();


    }


}