Issue-id: OCS-9
[msb/apigateway.git] / msb-core / apiroute / apiroute-service / src / main / java / org / openo / msb / wrapper / IuiRouteServiceWrapper.java
1 /**
2  * Copyright 2016 2015-2016 ZTE, Inc. and others. All rights reserved.
3  *
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
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16 package org.openo.msb.wrapper;
17
18 import java.util.HashMap;
19 import java.util.Map;
20 import java.util.Set;
21
22 import org.apache.commons.lang3.StringUtils;
23 import org.openo.msb.api.IuiRouteInfo;
24 import org.openo.msb.api.RouteServer;
25 import org.openo.msb.api.exception.ExtendedInternalServerErrorException;
26 import org.openo.msb.api.exception.ExtendedNotFoundException;
27 import org.openo.msb.api.exception.ExtendedNotSupportedException;
28 import org.openo.msb.wrapper.util.JedisUtil;
29 import org.openo.msb.wrapper.util.RegExpTestUtil;
30 import org.openo.msb.wrapper.util.RouteUtil;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33
34 import redis.clients.jedis.Jedis;
35
36 public class IuiRouteServiceWrapper {
37
38
39     private static final Logger LOGGER = LoggerFactory.getLogger(IuiRouteServiceWrapper.class);
40
41     private static IuiRouteServiceWrapper instance = new IuiRouteServiceWrapper();
42
43     private IuiRouteServiceWrapper() {}
44
45     public static IuiRouteServiceWrapper getInstance() {
46         return instance;
47     }
48
49
50     /**
51      * @Title: getAllIuiRouteService
52      * @Description: TODO(获取全部内容服务列表)
53      * @param: @return
54      * @return: IuiRouteInfo[]
55      */
56     public IuiRouteInfo[] getAllIuiRouteInstances() {
57
58
59         Jedis jedis = null;
60         IuiRouteInfo[] iuiRouteList = null;
61         try {
62             jedis = JedisUtil.borrowJedisInstance();
63             if (jedis == null) {
64                 throw new ExtendedInternalServerErrorException(
65                         "fetch from jedis pool failed,null object!");
66             }
67
68             // 获取全部服务列表
69             String routekey =
70                     RouteUtil
71                             .getPrefixedKey("", RouteUtil.IUIROUTE, "*", RouteUtil.ROUTE_PATH_INFO);
72             Set<String> routeSet = jedis.keys(routekey);
73             iuiRouteList = new IuiRouteInfo[routeSet.size()];
74
75             int i = 0;
76             for (String routePath : routeSet) {
77                 String[] routePathArray = routePath.split(":");
78                 IuiRouteInfo iuiRoute = getIuiRouteInstance(routePathArray[3], jedis);
79                 iuiRouteList[i] = iuiRoute;
80                 i++;
81             }
82
83
84         } catch (Exception e) {
85             LOGGER.error("call redis throw exception", e);
86             throw new ExtendedInternalServerErrorException("call redis throw exception:"
87                     + e.getMessage());
88         } finally {
89             JedisUtil.returnJedisInstance(jedis);
90         }
91
92         return iuiRouteList;
93     }
94
95
96
97     /**
98      * @Title: getIuiRouteInstance
99      * @Description: TODO(通过服务名获取单个内容服务对象信息)
100      * @param: @param serviceName
101      * @param: @return
102      * @return: IuiRouteInfo
103      */
104     public IuiRouteInfo getIuiRouteInstance(String serviceName) {
105
106         if (StringUtils.isBlank(serviceName)) {
107             throw new ExtendedNotSupportedException("serviceName  can't be empty");
108         }
109
110         IuiRouteInfo iuiRouteInfo = null;
111
112         Jedis jedis = null;
113         try {
114             jedis = JedisUtil.borrowJedisInstance();
115             if (jedis == null) {
116                 throw new ExtendedInternalServerErrorException(
117                         "fetch from jedis pool failed,null object!");
118             }
119
120             iuiRouteInfo = getIuiRouteInstance(serviceName, jedis);
121
122
123         } catch (Exception e) {
124             LOGGER.error("call redis throw exception", e);
125             throw new ExtendedInternalServerErrorException("call redis throw exception:"
126                     + e.getMessage());
127         } finally {
128             JedisUtil.returnJedisInstance(jedis);
129         }
130
131         if (null == iuiRouteInfo) {
132             String errInfo = "iuiRouteInfo not found: serviceName-" + serviceName;
133             LOGGER.warn(errInfo);
134             throw new ExtendedNotFoundException(errInfo);
135
136         }
137
138         return iuiRouteInfo;
139
140     }
141
142     public IuiRouteInfo getIuiRouteInstance(String serviceName, Jedis jedis) throws Exception {
143
144
145         IuiRouteInfo iuiRouteInfo = null;
146
147
148         // 获取info信息
149         String routekey =
150                 RouteUtil.getPrefixedKey("", RouteUtil.IUIROUTE, serviceName,
151                         RouteUtil.ROUTE_PATH_INFO);
152         Map<String, String> infomap = jedis.hgetAll(routekey);
153         if (!infomap.isEmpty()) {
154             iuiRouteInfo = new IuiRouteInfo();
155             iuiRouteInfo.setServiceName(serviceName);
156             iuiRouteInfo.setUrl(infomap.get("url"));
157             iuiRouteInfo.setControl(infomap.get("control"));
158             iuiRouteInfo.setStatus(infomap.get("status"));
159             iuiRouteInfo.setVisualRange(infomap.get("visualRange"));
160             iuiRouteInfo.setUseOwnUpstream(infomap.get("useOwnUpstream"));
161
162
163             // 获取负载均衡信息
164             String serviceLBkey =
165                     RouteUtil.getPrefixedKey("", RouteUtil.IUIROUTE, serviceName,
166                             RouteUtil.ROUTE_PATH_LOADBALANCE);
167             Set<String> serviceLBset = jedis.keys(serviceLBkey + ":*");
168             int serverNum = serviceLBset.size();
169             RouteServer[] iuiRouteServerList = new RouteServer[serverNum];
170             int i = 0;
171             for (String serviceInfo : serviceLBset) {
172                 Map<String, String> serviceLBmap = jedis.hgetAll(serviceInfo);
173                 RouteServer server = new RouteServer();
174                 server.setIp(serviceLBmap.get("ip"));
175                 server.setPort(serviceLBmap.get("port"));
176                 server.setWeight(Integer.parseInt(serviceLBmap.get("weight")));
177                 iuiRouteServerList[i] = server;
178                 i++;
179             }
180
181             iuiRouteInfo.setServers(iuiRouteServerList);
182         }
183
184
185         return iuiRouteInfo;
186     }
187
188     /**
189      * @Title: updateIuiRouteInstance
190      * @Description: TODO(更新单个服务信息)
191      * @param: @param serviceName
192      * @param: @param IuiRouteInfo
193      * @param: @return
194      * @return: IuiRouteInfo
195      */
196     public synchronized IuiRouteInfo updateIuiRouteInstance(String serviceName,
197             IuiRouteInfo iuiRouteInfo) {
198
199         if (StringUtils.isBlank(serviceName)) {
200             throw new ExtendedNotSupportedException("serviceName  can't be empty");
201         }
202
203         try {
204             if (serviceName.equals(iuiRouteInfo.getServiceName())) {
205                 // 删除已存在负载均衡服务器信息
206                 deleteIuiRoute(serviceName, RouteUtil.ROUTE_PATH_LOADBALANCE + "*");
207
208             } else {
209                 // 如果已修改服务名,先删除此服务全部已有信息
210                 deleteIuiRoute(serviceName, "*");
211             }
212             saveIuiRouteInstance(iuiRouteInfo);
213
214         } catch (ExtendedNotSupportedException e) {
215             throw e;
216         } catch (Exception e) {
217             LOGGER.error("updateIuiRoute throw exception", e);
218             throw new ExtendedInternalServerErrorException("update IuiRouteInfo throw exception"
219                     + e.getMessage());
220         }
221
222         return iuiRouteInfo;
223
224     }
225
226     /**
227      * @Title updateIuiRouteStatus
228      * @Description TODO(更新单个服务状态)
229      * @param serviceName
230      * @param status
231      * @return
232      * @return RouteResult
233      */
234     public synchronized IuiRouteInfo updateIuiRouteStatus(String serviceName, String status) {
235
236
237         if (StringUtils.isBlank(serviceName)) {
238             throw new ExtendedNotSupportedException("serviceName  can't be empty");
239         }
240
241         if (!RouteUtil.contain(RouteUtil.statusRangeMatches, status)) {
242             throw new ExtendedNotSupportedException(
243                     "save IuiRouteInfo Status FAIL:status is wrong,value range:("
244                             + RouteUtil.show(RouteUtil.statusRangeMatches) + ")");
245         }
246
247         IuiRouteInfo new_iuiRouteInfo = getIuiRouteInstance(serviceName);
248
249         // 准备info信息
250         String serviceInfokey =
251                 RouteUtil.getPrefixedKey("", RouteUtil.IUIROUTE, serviceName,
252                         RouteUtil.ROUTE_PATH_INFO);
253         Map<String, String> serviceInfoMap = new HashMap<String, String>();
254         serviceInfoMap.put("status", status);
255
256
257         Jedis jedis = null;
258         try {
259             jedis = JedisUtil.borrowJedisInstance();
260             if (jedis == null) {
261                 throw new ExtendedInternalServerErrorException(
262                         "fetch from jedis pool failed,null object!");
263             }
264             // 保存info信息
265             jedis.hmset(serviceInfokey, serviceInfoMap);
266             new_iuiRouteInfo.setStatus(status);
267
268         } catch (Exception e) {
269             LOGGER.error("update IuiRoute status throw exception", e);
270             throw new ExtendedInternalServerErrorException(
271                     "update IuiRouteInfo status throw exception" + e.getMessage());
272
273         } finally {
274             JedisUtil.returnJedisInstance(jedis);
275         }
276
277         return new_iuiRouteInfo;
278     }
279
280     /**
281      * @Title: saveIuiRouteInstance
282      * @Description: TODO(存储单个服务信息)
283      * @param: @param IuiRouteInfo
284      * @param: @return
285      * @return: IuiRouteInfo
286      */
287     public synchronized IuiRouteInfo saveIuiRouteInstance(IuiRouteInfo iuiRouteInfo) {
288
289         if (StringUtils.isBlank(iuiRouteInfo.getServiceName())
290                 || iuiRouteInfo.getServers().length == 0) {
291             throw new ExtendedNotSupportedException(
292                     "save iuiRouteInfo FAIL: Some required fields are empty");
293         }
294
295         if (StringUtils.isNotBlank(iuiRouteInfo.getUrl())){
296             if (!RegExpTestUtil.urlRegExpTest(iuiRouteInfo.getUrl())) {
297                 throw new ExtendedNotSupportedException(
298                         "save iuiRouteInfo FAIL:url is not a valid format(url must be begin with /)");
299     
300             }
301         }
302
303         if (!RouteUtil.contain(RouteUtil.visualRangeRange, iuiRouteInfo.getVisualRange())) {
304             throw new ExtendedNotSupportedException(
305                     "save iuiRouteInfo FAIL:VisualRange is wrong,value range:("
306                             + RouteUtil.show(RouteUtil.visualRangeMatches) + ")");
307         }
308
309         if (!RouteUtil.contain(RouteUtil.controlRangeMatches, iuiRouteInfo.getControl())) {
310             throw new ExtendedNotSupportedException(
311                     "save iuiRouteInfo FAIL:control is wrong,value range:("
312                             + RouteUtil.show(RouteUtil.controlRangeMatches) + ")");
313         }
314
315         if (!RouteUtil.contain(RouteUtil.statusRangeMatches, iuiRouteInfo.getStatus())) {
316             throw new ExtendedNotSupportedException(
317                     "save iuiRouteInfo FAIL:status is wrong,value range:("
318                             + RouteUtil.show(RouteUtil.statusRangeMatches) + ")");
319         }
320
321         if (!RouteUtil.contain(RouteUtil.useOwnUpstreamRangeMatches, iuiRouteInfo.getUseOwnUpstream())) {
322             throw new ExtendedNotSupportedException(
323                     "save apiRouteInfo FAIL:useOwnUpstream is wrong,value range:("
324                             + RouteUtil.show(RouteUtil.useOwnUpstreamRangeMatches) + ")");
325         }
326
327         // 检查服务实例格式
328         RouteServer[] serverList = iuiRouteInfo.getServers();
329         for (int i = 0; i < serverList.length; i++) {
330             RouteServer server = serverList[i];
331             if (!RegExpTestUtil.ipRegExpTest(server.getIp())) {
332                 throw new ExtendedNotSupportedException("save iuiRouteInfo FAIL:IP("
333                         + server.getIp() + ")is not a valid ip address");
334             }
335
336             if (!RegExpTestUtil.portRegExpTest(server.getPort())) {
337                 throw new ExtendedNotSupportedException("save iuiRouteInfo FAIL:Port("
338                         + server.getPort() + ")is not a valid Port address");
339             }
340         }
341
342
343         // 准备info信息
344         String serviceInfokey =
345                 RouteUtil.getPrefixedKey("", RouteUtil.IUIROUTE, iuiRouteInfo.getServiceName().trim(),
346                         RouteUtil.ROUTE_PATH_INFO);
347         Map<String, String> serviceInfoMap = new HashMap<String, String>();
348         serviceInfoMap.put("url", "/".equals(iuiRouteInfo.getUrl().trim()) ? "" : iuiRouteInfo
349                 .getUrl().trim());
350         serviceInfoMap.put("control", iuiRouteInfo.getControl());
351         serviceInfoMap.put("status", iuiRouteInfo.getStatus());
352         serviceInfoMap.put("visualRange", iuiRouteInfo.getVisualRange());
353         serviceInfoMap.put("useOwnUpstream", iuiRouteInfo.getUseOwnUpstream());
354
355
356         // 准备负载均衡信息
357         String serviceLBkey =
358                 RouteUtil.getPrefixedKey("", RouteUtil.IUIROUTE, iuiRouteInfo.getServiceName(),
359                         RouteUtil.ROUTE_PATH_LOADBALANCE);
360
361
362         Jedis jedis = null;
363         try {
364             jedis = JedisUtil.borrowJedisInstance();
365             if (jedis == null) {
366                 throw new ExtendedInternalServerErrorException(
367                         "fetch from jedis pool failed,null object!");
368             }
369             // 保存info信息
370             jedis.hmset(serviceInfokey, serviceInfoMap);
371
372             // 保存负载均衡信息
373             for (int i = 0; i < serverList.length; i++) {
374                 Map<String, String> servermap = new HashMap<String, String>();
375                 RouteServer server = serverList[i];
376
377                 servermap.put("ip", server.getIp());
378                 servermap.put("port", server.getPort());
379                 servermap.put("weight", Integer.toString(server.getWeight()));
380
381                 jedis.hmset(serviceLBkey + ":server" + (i + 1), servermap);
382             }
383
384
385         } catch (Exception e) {
386             LOGGER.error("call redis throw exception", e);
387             throw new ExtendedInternalServerErrorException("call redis throw exception:"
388                     + e.getMessage());
389         } finally {
390             JedisUtil.returnJedisInstance(jedis);;
391         }
392
393         return iuiRouteInfo;
394     }
395
396
397
398     /**
399      * @Title: deleteIuiRoute
400      * @Description: TODO(删除单个服务信息)
401      * @param: @param type
402      * @param: @param serviceName
403      * @param: @param delKey
404      * @param: @return
405      * @return: void
406      */
407     public synchronized void deleteIuiRoute(String serviceName, String delKey) {
408
409         if (StringUtils.isBlank(serviceName)) {
410             throw new ExtendedNotSupportedException("serviceName  can't be empty");
411         }
412
413         Jedis jedis = null;
414         try {
415             jedis = JedisUtil.borrowJedisInstance();
416             if (jedis == null) {
417                 throw new ExtendedInternalServerErrorException(
418                         "fetch from jedis pool failed,null object!");
419             }
420
421             // 获取info信息
422             String routekey = RouteUtil.getPrefixedKey("", RouteUtil.IUIROUTE, serviceName, delKey);
423             Set<String> infoSet = jedis.keys(routekey);
424
425             if (infoSet.isEmpty()) {
426                 throw new ExtendedNotFoundException("delete IuiRoute FAIL:serviceName-"
427                         + serviceName + " not fond ");
428             }
429
430             String[] paths = new String[infoSet.size()];
431
432             // Set-->数组
433             infoSet.toArray(paths);
434
435             jedis.del(paths);
436
437
438         } catch (ExtendedNotFoundException e) {
439             throw e;
440         } catch (Exception e) {
441             LOGGER.error("delete IuiRoute throw exception", e);
442             throw new ExtendedInternalServerErrorException("delete IuiRoute throw exception:"
443                     + e.getMessage());
444         } finally {
445             JedisUtil.returnJedisInstance(jedis);
446         }
447
448
449     }
450
451
452
453 }