msb protocol synch change
[msb/apigateway.git] / msb-core / apiroute / apiroute-service / src / main / java / org / openo / msb / wrapper / IuiRouteServiceWrapper.java
1 /**
2  * Copyright 2016 ZTE Corporation.
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     public IuiRouteInfo[] getAllIuiRouteInstances() {
50
51
52         Jedis jedis = null;
53         IuiRouteInfo[] iuiRouteList = null;
54         try {
55             jedis = JedisUtil.borrowJedisInstance();
56             if (jedis == null) {
57                 throw new ExtendedInternalServerErrorException(
58                         "fetch from jedis pool failed,null object!");
59             }
60
61             String routekey =
62                     RouteUtil
63                             .getPrefixedKey("", RouteUtil.IUIROUTE, "*", RouteUtil.ROUTE_PATH_INFO);
64             Set<String> routeSet = jedis.keys(routekey);
65             iuiRouteList = new IuiRouteInfo[routeSet.size()];
66
67             int i = 0;
68             for (String routePath : routeSet) {
69                 String[] routePathArray = routePath.split(":");
70                 IuiRouteInfo iuiRoute = getIuiRouteInstance(routePathArray[3], jedis);
71                 iuiRouteList[i] = iuiRoute;
72                 i++;
73             }
74
75
76         } catch (Exception e) {
77             LOGGER.error("call redis throw exception", e);
78             throw new ExtendedInternalServerErrorException("call redis throw exception:"
79                     + e.getMessage());
80         } finally {
81             JedisUtil.returnJedisInstance(jedis);
82         }
83
84         return iuiRouteList;
85     }
86
87
88     public IuiRouteInfo getIuiRouteInstance(String serviceName) {
89
90         if (StringUtils.isBlank(serviceName)) {
91             throw new ExtendedNotSupportedException("serviceName  can't be empty");
92         }
93
94         IuiRouteInfo iuiRouteInfo = null;
95
96         Jedis jedis = null;
97         try {
98             jedis = JedisUtil.borrowJedisInstance();
99             if (jedis == null) {
100                 throw new ExtendedInternalServerErrorException(
101                         "fetch from jedis pool failed,null object!");
102             }
103
104             iuiRouteInfo = getIuiRouteInstance(serviceName, jedis);
105
106
107         } catch (Exception e) {
108             LOGGER.error("call redis throw exception", e);
109             throw new ExtendedInternalServerErrorException("call redis throw exception:"
110                     + e.getMessage());
111         } finally {
112             JedisUtil.returnJedisInstance(jedis);
113         }
114
115         if (null == iuiRouteInfo) {
116             String errInfo = "iuiRouteInfo not found: serviceName-" + serviceName;
117             LOGGER.warn(errInfo);
118             throw new ExtendedNotFoundException(errInfo);
119
120         }
121
122         return iuiRouteInfo;
123
124     }
125
126     public IuiRouteInfo getIuiRouteInstance(String serviceName, Jedis jedis) throws Exception {
127
128
129         IuiRouteInfo iuiRouteInfo = null;
130
131
132         String routekey =
133                 RouteUtil.getPrefixedKey("", RouteUtil.IUIROUTE, serviceName,
134                         RouteUtil.ROUTE_PATH_INFO);
135         Map<String, String> infomap = jedis.hgetAll(routekey);
136         if (!infomap.isEmpty()) {
137             iuiRouteInfo = new IuiRouteInfo();
138             iuiRouteInfo.setServiceName(serviceName);
139             iuiRouteInfo.setUrl(infomap.get("url"));
140             iuiRouteInfo.setControl(infomap.get("control"));
141             iuiRouteInfo.setStatus(infomap.get("status"));
142             iuiRouteInfo.setVisualRange(infomap.get("visualRange"));
143             iuiRouteInfo.setUseOwnUpstream(infomap.get("useOwnUpstream"));
144
145
146             String serviceLBkey =
147                     RouteUtil.getPrefixedKey("", RouteUtil.IUIROUTE, serviceName,
148                             RouteUtil.ROUTE_PATH_LOADBALANCE);
149             Set<String> serviceLBset = jedis.keys(serviceLBkey + ":*");
150             int serverNum = serviceLBset.size();
151             RouteServer[] iuiRouteServerList = new RouteServer[serverNum];
152             int i = 0;
153             for (String serviceInfo : serviceLBset) {
154                 Map<String, String> serviceLBmap = jedis.hgetAll(serviceInfo);
155                 RouteServer server = new RouteServer();
156                 server.setIp(serviceLBmap.get("ip"));
157                 server.setPort(serviceLBmap.get("port"));
158                 server.setWeight(Integer.parseInt(serviceLBmap.get("weight")));
159                 iuiRouteServerList[i] = server;
160                 i++;
161             }
162
163             iuiRouteInfo.setServers(iuiRouteServerList);
164         }
165
166
167         return iuiRouteInfo;
168     }
169
170     public synchronized IuiRouteInfo updateIuiRouteInstance(String serviceName,
171             IuiRouteInfo iuiRouteInfo) {
172
173         if (StringUtils.isBlank(serviceName)) {
174             throw new ExtendedNotSupportedException("serviceName  can't be empty");
175         }
176
177         try {
178             if (serviceName.equals(iuiRouteInfo.getServiceName())) {
179                 deleteIuiRoute(serviceName, RouteUtil.ROUTE_PATH_LOADBALANCE + "*");
180
181             } else {
182                 deleteIuiRoute(serviceName, "*");
183             }
184             saveIuiRouteInstance(iuiRouteInfo);
185
186         } catch (ExtendedNotSupportedException e) {
187             throw e;
188         } catch (Exception e) {
189             LOGGER.error("updateIuiRoute throw exception", e);
190             throw new ExtendedInternalServerErrorException("update IuiRouteInfo throw exception"
191                     + e.getMessage());
192         }
193
194         return iuiRouteInfo;
195
196     }
197
198     public synchronized IuiRouteInfo updateIuiRouteStatus(String serviceName, String status) {
199
200
201         if (StringUtils.isBlank(serviceName)) {
202             throw new ExtendedNotSupportedException("serviceName  can't be empty");
203         }
204
205         if (!RouteUtil.contain(RouteUtil.statusRangeMatches, status)) {
206             throw new ExtendedNotSupportedException(
207                     "save IuiRouteInfo Status FAIL:status is wrong,value range:("
208                             + RouteUtil.show(RouteUtil.statusRangeMatches) + ")");
209         }
210
211         IuiRouteInfo new_iuiRouteInfo = getIuiRouteInstance(serviceName);
212
213         String serviceInfokey =
214                 RouteUtil.getPrefixedKey("", RouteUtil.IUIROUTE, serviceName,
215                         RouteUtil.ROUTE_PATH_INFO);
216         Map<String, String> serviceInfoMap = new HashMap<String, String>();
217         serviceInfoMap.put("status", status);
218
219
220         Jedis jedis = null;
221         try {
222             jedis = JedisUtil.borrowJedisInstance();
223             if (jedis == null) {
224                 throw new ExtendedInternalServerErrorException(
225                         "fetch from jedis pool failed,null object!");
226             }
227             jedis.hmset(serviceInfokey, serviceInfoMap);
228             new_iuiRouteInfo.setStatus(status);
229
230         } catch (Exception e) {
231             LOGGER.error("update IuiRoute status throw exception", e);
232             throw new ExtendedInternalServerErrorException(
233                     "update IuiRouteInfo status throw exception" + e.getMessage());
234
235         } finally {
236             JedisUtil.returnJedisInstance(jedis);
237         }
238
239         return new_iuiRouteInfo;
240     }
241
242     public synchronized IuiRouteInfo saveIuiRouteInstance(IuiRouteInfo iuiRouteInfo) {
243
244         if (StringUtils.isBlank(iuiRouteInfo.getServiceName())
245                 || iuiRouteInfo.getServers().length == 0) {
246             throw new ExtendedNotSupportedException(
247                     "save iuiRouteInfo FAIL: Some required fields are empty");
248         }
249
250         if (StringUtils.isNotBlank(iuiRouteInfo.getUrl())){
251             if (!RegExpTestUtil.urlRegExpTest(iuiRouteInfo.getUrl())) {
252                 throw new ExtendedNotSupportedException(
253                         "save iuiRouteInfo FAIL:url is not a valid format(url must be begin with /)");
254     
255             }
256         }
257
258         if (!RouteUtil.contain(RouteUtil.visualRangeRange, iuiRouteInfo.getVisualRange())) {
259             throw new ExtendedNotSupportedException(
260                     "save iuiRouteInfo FAIL:VisualRange is wrong,value range:("
261                             + RouteUtil.show(RouteUtil.visualRangeMatches) + ")");
262         }
263
264         if (!RouteUtil.contain(RouteUtil.controlRangeMatches, iuiRouteInfo.getControl())) {
265             throw new ExtendedNotSupportedException(
266                     "save iuiRouteInfo FAIL:control is wrong,value range:("
267                             + RouteUtil.show(RouteUtil.controlRangeMatches) + ")");
268         }
269
270         if (!RouteUtil.contain(RouteUtil.statusRangeMatches, iuiRouteInfo.getStatus())) {
271             throw new ExtendedNotSupportedException(
272                     "save iuiRouteInfo FAIL:status is wrong,value range:("
273                             + RouteUtil.show(RouteUtil.statusRangeMatches) + ")");
274         }
275
276         if (!RouteUtil.contain(RouteUtil.useOwnUpstreamRangeMatches, iuiRouteInfo.getUseOwnUpstream())) {
277             throw new ExtendedNotSupportedException(
278                     "save apiRouteInfo FAIL:useOwnUpstream is wrong,value range:("
279                             + RouteUtil.show(RouteUtil.useOwnUpstreamRangeMatches) + ")");
280         }
281
282         RouteServer[] serverList = iuiRouteInfo.getServers();
283         for (int i = 0; i < serverList.length; i++) {
284             RouteServer server = serverList[i];
285             if (!RegExpTestUtil.ipRegExpTest(server.getIp())) {
286                 throw new ExtendedNotSupportedException("save iuiRouteInfo FAIL:IP("
287                         + server.getIp() + ")is not a valid ip address");
288             }
289
290             if (!RegExpTestUtil.portRegExpTest(server.getPort())) {
291                 throw new ExtendedNotSupportedException("save iuiRouteInfo FAIL:Port("
292                         + server.getPort() + ")is not a valid Port address");
293             }
294         }
295
296
297         String serviceInfokey =
298                 RouteUtil.getPrefixedKey("", RouteUtil.IUIROUTE, iuiRouteInfo.getServiceName().trim(),
299                         RouteUtil.ROUTE_PATH_INFO);
300         Map<String, String> serviceInfoMap = new HashMap<String, String>();
301         serviceInfoMap.put("url", "/".equals(iuiRouteInfo.getUrl().trim()) ? "" : iuiRouteInfo
302                 .getUrl().trim());
303         serviceInfoMap.put("control", iuiRouteInfo.getControl());
304         serviceInfoMap.put("status", iuiRouteInfo.getStatus());
305         serviceInfoMap.put("visualRange", iuiRouteInfo.getVisualRange());
306         serviceInfoMap.put("useOwnUpstream", iuiRouteInfo.getUseOwnUpstream());
307
308
309         String serviceLBkey =
310                 RouteUtil.getPrefixedKey("", RouteUtil.IUIROUTE, iuiRouteInfo.getServiceName(),
311                         RouteUtil.ROUTE_PATH_LOADBALANCE);
312
313
314         Jedis jedis = null;
315         try {
316             jedis = JedisUtil.borrowJedisInstance();
317             if (jedis == null) {
318                 throw new ExtendedInternalServerErrorException(
319                         "fetch from jedis pool failed,null object!");
320             }
321             jedis.hmset(serviceInfokey, serviceInfoMap);
322
323             for (int i = 0; i < serverList.length; i++) {
324                 Map<String, String> servermap = new HashMap<String, String>();
325                 RouteServer server = serverList[i];
326
327                 servermap.put("ip", server.getIp());
328                 servermap.put("port", server.getPort());
329                 servermap.put("weight", Integer.toString(server.getWeight()));
330
331                 jedis.hmset(serviceLBkey + ":server" + (i + 1), servermap);
332             }
333
334
335         } catch (Exception e) {
336             LOGGER.error("call redis throw exception", e);
337             throw new ExtendedInternalServerErrorException("call redis throw exception:"
338                     + e.getMessage());
339         } finally {
340             JedisUtil.returnJedisInstance(jedis);;
341         }
342
343         return iuiRouteInfo;
344     }
345
346
347
348     public synchronized void deleteIuiRoute(String serviceName, String delKey) {
349
350         if (StringUtils.isBlank(serviceName)) {
351             throw new ExtendedNotSupportedException("serviceName  can't be empty");
352         }
353
354         Jedis jedis = null;
355         try {
356             jedis = JedisUtil.borrowJedisInstance();
357             if (jedis == null) {
358                 throw new ExtendedInternalServerErrorException(
359                         "fetch from jedis pool failed,null object!");
360             }
361
362             String routekey = RouteUtil.getPrefixedKey("", RouteUtil.IUIROUTE, serviceName, delKey);
363             Set<String> infoSet = jedis.keys(routekey);
364
365             if (infoSet.isEmpty()) {
366               LOGGER.warn("delete IuiRoute FAIL:serviceName-"
367                         + serviceName + " not fond ");
368             }
369             else{
370
371               String[] paths = new String[infoSet.size()];
372               infoSet.toArray(paths);
373               jedis.del(paths);
374             }
375
376
377         } catch (ExtendedNotFoundException e) {
378             throw e;
379         } catch (Exception e) {
380             LOGGER.error("delete IuiRoute throw exception", e);
381             throw new ExtendedInternalServerErrorException("delete IuiRoute throw exception:"
382                     + e.getMessage());
383         } finally {
384             JedisUtil.returnJedisInstance(jedis);
385         }
386
387
388     }
389
390
391
392 }