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