aboutsummaryrefslogtreecommitdiffstats
path: root/msb-core/apiroute/apiroute-service/src/main/java/org/openo/msb/ApiRouteApp.java
blob: e5a6394faa4539cdce5560b7e4a091cbf9eac7a7 (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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
/**
 * Copyright 2016 ZTE Corporation.
 *
 * 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 io.dropwizard.Application;
import io.dropwizard.assets.AssetsBundle;
import io.dropwizard.jetty.HttpConnectorFactory;
import io.dropwizard.server.SimpleServerFactory;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import io.swagger.jaxrs.config.BeanConfig;
import io.swagger.jaxrs.listing.ApiListingResource;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.util.List;

import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.openo.msb.api.ApiRouteInfo;
import org.openo.msb.api.ConsulInfo;
import org.openo.msb.api.CustomRouteInfo;
import org.openo.msb.api.DiscoverInfo;
import org.openo.msb.api.IuiRouteInfo;
import org.openo.msb.api.RouteServer;
import org.openo.msb.api.exception.ExtendedNotFoundException;
import org.openo.msb.health.ApiRouteHealthCheck;
import org.openo.msb.resources.ApiRouteResource;
import org.openo.msb.resources.CustomRouteResource;
import org.openo.msb.resources.IuiRouteResource;
import org.openo.msb.resources.MetricsResource;
import org.openo.msb.resources.MicroServiceResource;
import org.openo.msb.resources.ServiceAccessResource;
import org.openo.msb.wrapper.ApiRouteServiceWrapper;
import org.openo.msb.wrapper.CustomRouteServiceWrapper;
import org.openo.msb.wrapper.IuiRouteServiceWrapper;
import org.openo.msb.wrapper.serviceListener.MicroServiceChangeListener;
import org.openo.msb.wrapper.util.FileUtil;
import org.openo.msb.wrapper.util.JacksonJsonUtil;
import org.openo.msb.wrapper.util.JedisUtil;
import org.openo.msb.wrapper.util.MetricsUtil;
import org.openo.msb.wrapper.util.MicroServiceDB;
import org.openo.msb.wrapper.util.RegExpTestUtil;
import org.openo.msb.wrapper.util.RouteUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.annotation.JsonInclude;

public class ApiRouteApp extends Application<ApiRouteAppConfig> {

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

    public static void main(String[] args) throws Exception {
        new ApiRouteApp().run(args);

    }

    private ApiRouteAppConfig config;

    @Override
    public String getName() {
        return " MicroService Bus ";
    }

    @Override
    public void initialize(Bootstrap<ApiRouteAppConfig> bootstrap) {
        
        
    }

    @Override
    public void run(ApiRouteAppConfig configuration, Environment environment) {
        
        initRootPath();
        
      
        new AssetsBundle("/iui-metrics", "/"+RouteUtil.IUI_ROOT_PATH+"/microservices/metrics",
            "index.html", "iui-metrics").run(environment); 
        
        new AssetsBundle("/iui-route",  "/"+RouteUtil.IUI_ROOT_PATH+"/microservices", "index.html",
                "iui-microservices").run(environment); 
        
        new AssetsBundle("/api-doc",  "/"+RouteUtil.IUI_ROOT_PATH+"/microservices/api-doc",
            "index.html", "api-doc").run(environment);
        
        new AssetsBundle("/ext",  "/"+RouteUtil.IUI_ROOT_PATH+"/microservices/ext",
            "index.html", "ext").run(environment);
        
        
        

        final ApiRouteHealthCheck healthCheck =
                new ApiRouteHealthCheck(configuration.getDefaultWorkspace());
        environment.healthChecks().register("template", healthCheck);
        environment.jersey().register(new ApiRouteResource());
        environment.jersey().register(new IuiRouteResource());
        environment.jersey().register(new MetricsResource());
        environment.jersey().register(new CustomRouteResource());
        environment.jersey().register(new ServiceAccessResource());
        environment.jersey().register(new MicroServiceResource());

        config = configuration;

        initSwaggerConfig(environment, configuration);
        initRedisConfig(configuration);
        checkRedisConnect();
        initMetricsConfig(configuration);
        initVisualRangeMatches();

        registerServiceChangeListener();


    }

    private void initMetricsConfig(ApiRouteAppConfig configuration) {

        SimpleServerFactory simpleServerFactory =
                (SimpleServerFactory) configuration.getServerFactory();
        HttpConnectorFactory httpConnectorFactory =
                (HttpConnectorFactory) simpleServerFactory.getConnector();
        MetricsUtil.adminContextPath =
                "http://127.0.0.1:" + httpConnectorFactory.getPort()
                        + simpleServerFactory.getAdminContextPath() + "/metrics";
    }

    private void initSwaggerConfig(Environment environment, ApiRouteAppConfig configuration) {

        environment.jersey().register(new ApiListingResource());
        environment.getObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL);

        BeanConfig config = new BeanConfig();
        config.setTitle("MicroService Bus rest API");
        config.setVersion("1.0.0");
        config.setResourcePackage("org.openo.msb.resources");
        SimpleServerFactory simpleServerFactory =
                (SimpleServerFactory) configuration.getServerFactory();
        String basePath = simpleServerFactory.getApplicationContextPath();
        String rootPath = simpleServerFactory.getJerseyRootPath();

        rootPath = rootPath.substring(0, rootPath.indexOf("/*"));

        basePath =
                basePath.equals("/") ? rootPath : (new StringBuilder()).append(basePath)
                        .append(rootPath).toString();

        LOGGER.info("getApplicationContextPath: " + basePath);
        config.setBasePath(basePath);
        config.setScan(true);
    }
    
    
    private void initRootPath(){
        try {
            
            URL urlRootPath = ApiRouteApp.class.getResource("/ext/initUrlRootPath/initUrlRootPath.json");
            if (urlRootPath != null) {
                String path = urlRootPath.getPath();
    
                LOGGER.info("read initUrlRootPath:" + path);
              
                String fileContent = FileUtil.readFile(path);
                JSONObject jsonObj = JSONObject.fromObject(fileContent);
                RouteUtil.IUI_ROOT_PATH=jsonObj.get("iuiRootPath").toString();
                RouteUtil.API_ROOT_PATH=jsonObj.get("apiRootPath").toString();
                }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            LOGGER.error("read  initUrlRootPath Files throw exception", e);
        }
        
    }
    private void initRedisConfig(ApiRouteAppConfig configuration) {

        String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
        String jarPath = path.substring(0, path.lastIndexOf("/"));

        LOGGER.info("jarpath: " + jarPath);
        LOGGER.info("getDefaultWorkspace " + configuration.getDefaultWorkspace());

        String confDir =
                jarPath + "/" + configuration.getDefaultWorkspace() + "/"
                        + configuration.getPropertiesDir();
        String propertiesPath = confDir + "/" + configuration.getPropertiesName();

        JedisUtil.propertiesPath = propertiesPath;

        LOGGER.info("propertiesPath: " + propertiesPath);
        LOGGER.info("confDir: " + confDir);

        try {
            File dirFile = new File(confDir);

            if (!dirFile.exists()) {
                dirFile.mkdirs();
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            LOGGER.info("create RedisConfig confDir error: " + confDir + e.getMessage());
        }


        try {
            File propertiesFile = new File(propertiesPath);
            if (!propertiesFile.exists()) {


                propertiesFile.createNewFile();

                BufferedWriter output = new BufferedWriter(new FileWriter(propertiesFile));
                StringBuilder contentBuilder = new StringBuilder();
                contentBuilder.append("redis.host=127.0.0.1\n").append("redis.port=6379\n")
                        .append("#connectionTimeout\n").append("redis.connectionTimeout=2000\n")
                        .append("#redis dbIndex,defaule:0\n")
                        .append("redis.db_index=0\n\n")
                        .append("#--------------redis pool config--------------\n")
                        .append("#maxTotal\n").append("redis.pool.maxTotal=100\n")
                        .append("#maxIdle\n").append("redis.pool.maxIdle=20\n")
                        .append("#maxWaitMillis:ms\n")
                        .append("redis.pool.maxWaitMillis=1000\n")
                        .append("#testOnBorrow\n")
                        .append("redis.pool.testOnBorrow=false\n")
                        .append("#testOnReturn\n")
                        .append("redis.pool.testOnReturn=true\n")
                        .append("#nginx Port\n").append("server.port=10080\n");

                output.write(contentBuilder.toString());
                output.close();

            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            LOGGER.info("create RedisConfig File error: " + propertiesPath + e.getMessage());
        }
    }


    private void checkRedisConnect() {

        new Thread(new Runnable() {
            public void run() {
                int n = 0;
                while (true) {
                    if (ApiRouteServiceWrapper.checkRedisConnect() == false) {
                        n++;
                        System.out.println(n
                                + "/10 : Initial Route Configuration——redis connection fail...");

                        try {
                            Thread.sleep(10000);
                        } catch (InterruptedException e) {
                            LOGGER.error("Thread.sleep throw except:"+e.getMessage());
                        }


                        if (n >= 10) {
                            System.out.println("Initial Route Configuration fail,timeout exit");
                            LOGGER.error("Initial Route Configuration——redis connection fail,timeout exit...");
                            break;
                        }
                    } else {
                        System.out.println("starting to initial Route Configuration");
                        // initRouteInfoFromConfig();
                        initRouteInfoFromJson();
                        System.out.println("starting to initial consul Configuration");
                        runConsulClientApp();

                        break;
                    }
                }

            }
        }).start();
    }


    

    /**
     * @Title: initVisualRangeMatches
     * @Description: TODO(According to the environment variable or a JSON file configuration initialization VisualRange filter conditions)
     * @return: void
     */
    private void initVisualRangeMatches(){
        try {
            if(System.getenv("APIGATEWAY_VISUAL_RANGE")==null)
            {
            
            URL visualRangePath = ApiRouteApp.class.getResource("/ext/initVisualRange/initVisualRangeMatches.json");
            if (visualRangePath != null) {
                String path = visualRangePath.getPath();
    
                LOGGER.info("read initVisualRangeMatches:" + path);
              
                String fileContent = FileUtil.readFile(path);
                JSONObject jsonObj = JSONObject.fromObject(fileContent);
                String visualRangeArray=jsonObj.get("visualRange").toString();
                
            
                RouteUtil.visualRangeMatches=StringUtils.split(visualRangeArray, ",");  
             
                
               
                }
            }
            else{
                RouteUtil.visualRangeMatches=StringUtils.split(System.getenv("APIGATEWAY_VISUAL_RANGE"), ",");
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            LOGGER.error("read  initVisualRangeMatches Files or env(APIGATEWAY_VISUAL_RANGE) throw exception", e);
        }
    }

    /**
     * @Title: initRouteInfoFromJson
     * @Description: TODO(按照JSON文件配置初始化route数据)
     * @return: void
     */
    private void initRouteInfoFromJson() {

        URL apiDocsPath = ApiRouteApp.class.getResource("/ext/initServices");
        if (apiDocsPath != null) {
            String path = apiDocsPath.getPath();

            LOGGER.info("read JsonFilefolder:" + path);

            try {
                File[] files = FileUtil.readFileFolder(path);
                for (int i = 0; i < files.length; i++) {
                    File file = files[i];
                    if (file.isFile() && file.getName().endsWith(".json")) {
                        LOGGER.info("read JsonFile:" + file.getPath());
                        String fileContent = FileUtil.readFile(file.getPath());
                        saveInitService2redis(fileContent);
                    } else {
                        LOGGER.warn(file.getName() + " is not a right file");
                    }
                }



            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                LOGGER.error("read  initServices Files throw FileNotFoundException", e);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                LOGGER.error("read  initServices Files throw IOexception", e);
            }

        }



    }



    private void saveInitService2redis(String fileContent) {
        try {
            List<ApiRouteInfo> routeList =
                    (List<ApiRouteInfo>) JacksonJsonUtil.jsonToListBean(fileContent);
            for (ApiRouteInfo route : routeList) {
                String url = route.getUrl();

                if (RegExpTestUtil.urlRegExpTest(route.getServiceName())) {
                    
                    try{
                    CustomRouteInfo dbCustomRoute =
                            CustomRouteServiceWrapper.getInstance().getCustomRouteInstance(
                                    route.getServiceName());
                    }
                    catch(ExtendedNotFoundException e){

                        LOGGER.info("initCustomRoute: ServiceName--" + route.getServiceName());

                        CustomRouteInfo customRouteInfo = new CustomRouteInfo();
                        customRouteInfo.setControl(route.getControl());
                        customRouteInfo.setServers(route.getServers());
                        customRouteInfo.setServiceName(route.getServiceName());
                        customRouteInfo.setStatus(route.getStatus());
                        customRouteInfo.setUrl(route.getUrl());


                        CustomRouteServiceWrapper.getInstance().saveCustomRouteInstance(
                                customRouteInfo, "");


                    }
                } else {

                    if (RegExpTestUtil.apiRouteUrlRegExpTest(url) || url.startsWith("/api/microservices/")) {


                        try{
                        ApiRouteInfo dbApiRoute =
                                ApiRouteServiceWrapper.getInstance().getApiRouteInstance(
                                        route.getServiceName(), route.getVersion());
                        }
                        catch(ExtendedNotFoundException e){
                            LOGGER.info("initapiRoute: ServiceName--" + route.getServiceName());
                            ApiRouteServiceWrapper.getInstance().saveApiRouteInstance(route, "");
                        }

                       
                    } else if (RegExpTestUtil.iuiRouteUrlRegExpTest(url)  || url.equals("/iui/microservices")) {
                        
                        try{
                        IuiRouteInfo dbIuiRoute =
                                IuiRouteServiceWrapper.getInstance().getIuiRouteInstance(
                                        route.getServiceName());
                        }
                        catch(ExtendedNotFoundException e){
                    
                            LOGGER.info(" initiuiRoute: ServiceName--" + route.getServiceName());
                            IuiRouteInfo iuiRouteInfo = new IuiRouteInfo();
                            iuiRouteInfo.setControl(route.getControl());
                            iuiRouteInfo.setServers(route.getServers());
                            iuiRouteInfo.setServiceName(route.getServiceName());
                            iuiRouteInfo.setStatus(route.getStatus());
                            
                            if(url.equals("/iui/microservices")){
                                iuiRouteInfo.setUrl("/"+RouteUtil.IUI_ROOT_PATH+"/microservices");
                            }
                            else{
                            iuiRouteInfo.setUrl(route.getUrl());
                            }

                            IuiRouteServiceWrapper.getInstance().saveIuiRouteInstance(iuiRouteInfo);

                        }

                    } else {
                        LOGGER.error("init Service throw exception——serviceName: " + route.getServiceName()+",url:"+url);
                    }
                }



            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            LOGGER.error("read  initServices Files throw exception", e);
        }

    }



    /**
     * The listener registration service changes
     */
    private void registerServiceChangeListener() {
        MicroServiceDB.getInstance().addServiceChangeListener(new MicroServiceChangeListener());
    }

    // Open the consul to monitor subscription service
    private void runConsulClientApp() {
        DiscoverInfo config_discoverInfo = config.getDiscoverInfo();
        
        ConsulInfo config_consulInfo=config.getConsulInfo();
        
        RouteUtil.discoverInfo.setEnabled(config_discoverInfo.isEnabled());        
        
        if (config_discoverInfo.isEnabled()) {
            try{
            if(System.getenv("SDCLIENT_SVC_PORT")==null)
            {
                //yml          
                RouteUtil.discoverInfo.setIp(config_discoverInfo.getIp()); 
                RouteUtil.discoverInfo.setPort(config_discoverInfo.getPort());
                
            }
            else{
               
                 String  discoverAddress=System.getenv("SDCLIENT_SVC_PORT").split("//")[1];
                 String sdIP=discoverAddress.split(":")[0];
                 int sdPort=Integer
                         .parseInt(discoverAddress.split(":")[1]);
                 
                 RouteUtil.discoverInfo.setIp(sdIP);
                 RouteUtil.discoverInfo.setPort(sdPort);
                 
                 config_consulInfo.setIp(sdIP);
                 config_consulInfo.setPort(sdPort);
             
                
            }
            
           
               
                //Registration service discovery routing
                //api
                ApiRouteInfo discoverApiService=new ApiRouteInfo();
                discoverApiService.setServiceName("msdiscover");
                discoverApiService.setUrl("/api/microservices/v1");
                discoverApiService.setVersion("v1");
                discoverApiService.setMetricsUrl("/admin/metrics");
                discoverApiService.setApiJson("/api/microservices/v1/swagger.json");
                
                RouteServer[] servers=new RouteServer[1];
                servers[0]=new RouteServer(RouteUtil.discoverInfo.getIp(),String.valueOf(RouteUtil.discoverInfo.getPort()));
                discoverApiService.setServers(servers);
             
                ApiRouteServiceWrapper.getInstance().saveApiRouteInstance(discoverApiService, "");
               
                //iui
                IuiRouteInfo discoverIUIService=new IuiRouteInfo();
                discoverIUIService.setServiceName("msdiscover");
                discoverIUIService.setUrl("/iui/microservices");
                discoverIUIService.setServers(servers);
                IuiRouteServiceWrapper.getInstance().saveIuiRouteInstance(discoverIUIService);
                
               

            ConsulClientApp consulClientApp = new ConsulClientApp(config_consulInfo.getIp(), config_consulInfo.getPort());
            // Monitor service change
            consulClientApp.startServiceListen();
            LOGGER.info("start monitor consul service--" +config_consulInfo.getIp() + ":"
                    + config_consulInfo.getPort());
            }
            catch(Exception e){
                LOGGER.error("start monitor consul service fail:"+e.getMessage()); 
            }
        }
        
       
    }

}