Authored by qinchao

Merge branch 'master' of http://git.yoho.cn/ops/monitor-service into dev_gml

@@ -242,8 +242,7 @@ public class CloudToolController { @@ -242,8 +242,7 @@ public class CloudToolController {
242 @RequestMapping("/updateMobjectInfo") 242 @RequestMapping("/updateMobjectInfo")
243 @ResponseBody 243 @ResponseBody
244 public BaseResponse updateMobjectInfo(@RequestBody AutoScalingInfoReq infoReq){ 244 public BaseResponse updateMobjectInfo(@RequestBody AutoScalingInfoReq infoReq){
245 - cloudToolService.updateMobjectInfo(infoReq);  
246 - return new BaseResponse(); 245 + return cloudToolService.updateMobjectInfo(infoReq);
247 } 246 }
248 247
249 /** 248 /**
@@ -316,11 +316,134 @@ public class CloudToolServiceImpl implements CloudToolService { @@ -316,11 +316,134 @@ public class CloudToolServiceImpl implements CloudToolService {
316 return updateMobject4Nginx(infoReq); 316 return updateMobject4Nginx(infoReq);
317 }else if ("PCH5-memcache".equalsIgnoreCase(infoReq.getScalingGroupName())||"java-gateway-memcache".equalsIgnoreCase(infoReq.getScalingGroupName())){ 317 }else if ("PCH5-memcache".equalsIgnoreCase(infoReq.getScalingGroupName())||"java-gateway-memcache".equalsIgnoreCase(infoReq.getScalingGroupName())){
318 return updateMemcacheInfoForMobject(infoReq); 318 return updateMemcacheInfoForMobject(infoReq);
  319 + }else if("ELASTICSEARCH".equalsIgnoreCase(infoReq.getScalingGroupName())){
  320 + //暂时不做
  321 + }else if("PCH5-NODE".equalsIgnoreCase(infoReq.getScalingGroupName())||"PCH5-AutoScaling".equalsIgnoreCase(infoReq.getScalingGroupName())){
  322 + //暂时不做
  323 + }else{
  324 + ////// 普通java项目
  325 + return updateMobject4JavaApp(infoReq);
  326 + }
  327 + }
  328 + return res;
  329 + }
  330 +
  331 + /// java app的监控配置,java_nginx 既包括172 ,又包括10,所以更新的时候,如果要删除需要只删除当前云
  332 + private BaseResponse updateMobject4JavaApp(AutoScalingInfoReq infoReq){
  333 + BaseResponse res = new BaseResponse();
  334 + String environment="";
  335 + if(1==infoReq.getCloudType()){
  336 + environment="aws";
  337 + }else if(2==infoReq.getCloudType()){
  338 + environment="qcloud";
  339 + }
  340 + String mobjectPaths=infoReq.getMobjectPaths();
  341 + String[] mobjectPaths_array=mobjectPaths.split(",");
  342 + String typeNames=mobjectPaths_array[mobjectPaths_array.length-1];//////////有可能是多个,比如activity-bigdata
  343 + StringBuilder sb=new StringBuilder();
  344 +
  345 + String[] allIps=infoReq.getNewInstanceIps().split(",");
  346 + List<String> allIpsList=new ArrayList<String>();
  347 + for(String ip:allIps){
  348 + if(StringUtils.isNotBlank(ip)){
  349 + allIpsList.add(ip);
  350 + }
  351 + }
  352 +
  353 + for(String typeName:typeNames.split("-")){
  354 + mobjectPaths_array[mobjectPaths_array.length-1]=typeName;
  355 + TypeInfo typeInfo = getTypeByMobjectPathArray(mobjectPaths_array);
  356 + if(typeInfo!=null){
  357 + List<MObjectInfo> objectInfoList = mObjectInfoMapper.getTypeMosInfo(typeInfo.getTypeId());
  358 + List<String> existsHostIps=new ArrayList<String>();
  359 + if(objectInfoList!=null&&objectInfoList.size()>0){
  360 + for(MObjectInfo mob:objectInfoList){
  361 + //处理移除的机器,但是要保留另外一个云的机器信息
  362 + if(!allIpsList.contains(mob.getMoHostIp())){
  363 + if(environment.equals("aws")&&mob.getMoHostIp().startsWith("172.")){
  364 + mObjectInfoMapper.deleteMoInfo(mob.getMoId());
  365 + sb.append("删除"+typeName+"监控对象:"+mob.getMoHostIp()+"\n");
  366 + }
  367 + if(environment.equals("qcloud")&&mob.getMoHostIp().startsWith("10.")){
  368 + mObjectInfoMapper.deleteMoInfo(mob.getMoId());
  369 + sb.append("删除"+typeName+"监控对象:"+mob.getMoHostIp()+"\n");
  370 + }
  371 + }else{
  372 + existsHostIps.add(mob.getMoHostIp());
  373 + }
  374 + }
  375 + }
  376 + //处理新增的机器
  377 + for(String ip:allIps){
  378 + if(StringUtils.isNotBlank(ip)&&!existsHostIps.contains(ip)){
  379 + MObjectInfo mob=new MObjectInfo();
  380 + mob.setMoName(buildMoName(typeName,environment));
  381 + mob.setMoHostIp(ip);
  382 + mob.setMoTags(getMobjectTagsForJavaApp(typeName));
  383 + mob.setMoTypeId(typeInfo.getTypeId());
  384 + mObjectInfoMapper.insertMoInfo(mob);
  385 + sb.append("添加"+typeName+"监控对象:"+mob.getMoHostIp()+"\n");
  386 + }
  387 + }
319 } 388 }
  389 +
320 } 390 }
  391 + res.setData(sb.toString());
321 return res; 392 return res;
322 } 393 }
323 394
  395 + // 获取java app的标签 :端口号
  396 + private String getMobjectTagsForJavaApp(String typeName){
  397 + String tag="";
  398 + switch (typeName){
  399 + case "gateway":
  400 + tag="8080";
  401 + break;
  402 + case "order":
  403 + tag="8084";
  404 + break;
  405 + case "promotion":
  406 + tag="8085";
  407 + break;
  408 + case "product":
  409 + tag="8083";
  410 + break;
  411 + case "message":
  412 + tag="8086";
  413 + break;
  414 + case "sns":
  415 + tag="8082";
  416 + break;
  417 + case "users":
  418 + tag="8081";
  419 + break;
  420 + case "resources":
  421 + tag="8087";
  422 + break;
  423 + case "activity":
  424 + tag="8090";
  425 + break;
  426 + case "union":
  427 + tag="";
  428 + break;
  429 + case "brower":
  430 + tag="8092";
  431 + break;
  432 + case "social":
  433 + tag="8095";
  434 + break;
  435 + case "uic":
  436 + tag="8096";
  437 + break;
  438 + case "bigdata":
  439 + tag="";
  440 + break;
  441 + case "yoho!now":
  442 + tag="";
  443 + break;
  444 + }
  445 + return tag;
  446 + }
324 /// nginx的监控配置,java_nginx 既包括172 ,又包括10,所以更新的时候,如果要删除需要只删除当前云 447 /// nginx的监控配置,java_nginx 既包括172 ,又包括10,所以更新的时候,如果要删除需要只删除当前云
325 private BaseResponse updateMobject4Nginx(AutoScalingInfoReq infoReq){ 448 private BaseResponse updateMobject4Nginx(AutoScalingInfoReq infoReq){
326 BaseResponse res = new BaseResponse(); 449 BaseResponse res = new BaseResponse();
@@ -343,18 +466,27 @@ public class CloudToolServiceImpl implements CloudToolService { @@ -343,18 +466,27 @@ public class CloudToolServiceImpl implements CloudToolService {
343 466
344 StringBuilder sb=new StringBuilder(); 467 StringBuilder sb=new StringBuilder();
345 List<MObjectInfo> objectInfoList = mObjectInfoMapper.getTypeMosInfo(typeInfo.getTypeId()); 468 List<MObjectInfo> objectInfoList = mObjectInfoMapper.getTypeMosInfo(typeInfo.getTypeId());
  469 +
  470 + String[] allIps=infoReq.getNewInstanceIps().split(",");
  471 + List<String> allIpsList=new ArrayList<String>();
  472 + for(String ip:allIps){
  473 + if(StringUtils.isNotBlank(ip)){
  474 + allIpsList.add(ip);
  475 + }
  476 + }
  477 +
346 List<String> existsHostIps=new ArrayList<String>(); 478 List<String> existsHostIps=new ArrayList<String>();
347 if(objectInfoList!=null&&objectInfoList.size()>0){ 479 if(objectInfoList!=null&&objectInfoList.size()>0){
348 for(MObjectInfo mob:objectInfoList){ 480 for(MObjectInfo mob:objectInfoList){
349 //处理移除的机器,但是要保留另外一个云的机器信息 481 //处理移除的机器,但是要保留另外一个云的机器信息
350 - if(infoReq.getNewInstanceIps().indexOf(mob.getMoHostIp())<0){ 482 + if(!allIpsList.contains(mob.getMoHostIp())){
351 if(environment.equals("aws")&&mob.getMoHostIp().startsWith("172.")){ 483 if(environment.equals("aws")&&mob.getMoHostIp().startsWith("172.")){
352 mObjectInfoMapper.deleteMoInfo(mob.getMoId()); 484 mObjectInfoMapper.deleteMoInfo(mob.getMoId());
353 - sb.append("删除"+typeName+"监控对象:"+mob.getMoId()+"\n"); 485 + sb.append("删除"+typeName+"监控对象:"+mob.getMoHostIp()+"\n");
354 } 486 }
355 if(environment.equals("qcloud")&&mob.getMoHostIp().startsWith("10.")){ 487 if(environment.equals("qcloud")&&mob.getMoHostIp().startsWith("10.")){
356 mObjectInfoMapper.deleteMoInfo(mob.getMoId()); 488 mObjectInfoMapper.deleteMoInfo(mob.getMoId());
357 - sb.append("删除"+typeName+"监控对象:"+mob.getMoId()+"\n"); 489 + sb.append("删除"+typeName+"监控对象:"+mob.getMoHostIp()+"\n");
358 } 490 }
359 }else{ 491 }else{
360 existsHostIps.add(mob.getMoHostIp()); 492 existsHostIps.add(mob.getMoHostIp());
@@ -362,7 +494,6 @@ public class CloudToolServiceImpl implements CloudToolService { @@ -362,7 +494,6 @@ public class CloudToolServiceImpl implements CloudToolService {
362 } 494 }
363 } 495 }
364 //处理新增的机器 496 //处理新增的机器
365 - String[] allIps=infoReq.getNewInstanceIps().split(",");  
366 for(String ip:allIps){ 497 for(String ip:allIps){
367 if(StringUtils.isNotBlank(ip)&&!existsHostIps.contains(ip)){ 498 if(StringUtils.isNotBlank(ip)&&!existsHostIps.contains(ip)){
368 MObjectInfo mob=new MObjectInfo(); 499 MObjectInfo mob=new MObjectInfo();
@@ -370,7 +501,7 @@ public class CloudToolServiceImpl implements CloudToolService { @@ -370,7 +501,7 @@ public class CloudToolServiceImpl implements CloudToolService {
370 mob.setMoHostIp(ip); 501 mob.setMoHostIp(ip);
371 mob.setMoTypeId(typeInfo.getTypeId()); 502 mob.setMoTypeId(typeInfo.getTypeId());
372 mObjectInfoMapper.insertMoInfo(mob); 503 mObjectInfoMapper.insertMoInfo(mob);
373 - sb.append("添加"+typeName+"监控对象:"+mob.getMoId()+"\n"); 504 + sb.append("添加"+typeName+"监控对象:"+mob.getMoHostIp()+"\n");
374 } 505 }
375 } 506 }
376 res.setData(sb.toString()); 507 res.setData(sb.toString());
@@ -400,13 +531,22 @@ public class CloudToolServiceImpl implements CloudToolService { @@ -400,13 +531,22 @@ public class CloudToolServiceImpl implements CloudToolService {
400 531
401 StringBuilder sb=new StringBuilder(); 532 StringBuilder sb=new StringBuilder();
402 List<MObjectInfo> objectInfoList = mObjectInfoMapper.getTypeMosInfo(typeInfo.getTypeId()); 533 List<MObjectInfo> objectInfoList = mObjectInfoMapper.getTypeMosInfo(typeInfo.getTypeId());
  534 +
  535 + String[] allIps=infoReq.getNewInstanceIps().split(",");
  536 + List<String> allIpsList=new ArrayList<String>();
  537 + for(String ip:allIps){
  538 + if(StringUtils.isNotBlank(ip)){
  539 + allIpsList.add(ip);
  540 + }
  541 + }
  542 +
403 List<String> existsHostIps=new ArrayList<String>(); 543 List<String> existsHostIps=new ArrayList<String>();
404 if(objectInfoList!=null&&objectInfoList.size()>0){ 544 if(objectInfoList!=null&&objectInfoList.size()>0){
405 for(MObjectInfo mob:objectInfoList){ 545 for(MObjectInfo mob:objectInfoList){
406 //处理移除的机器 546 //处理移除的机器
407 - if(infoReq.getNewInstanceIps().indexOf(mob.getMoHostIp())<0){ 547 + if(!allIpsList.contains(mob.getMoHostIp())){
408 mObjectInfoMapper.deleteMoInfo(mob.getMoId()); 548 mObjectInfoMapper.deleteMoInfo(mob.getMoId());
409 - sb.append("删除"+typeName+"监控对象:"+mob.getMoId()+"\n"); 549 + sb.append("删除"+typeName+"监控对象:"+mob.getMoHostIp()+"\n");
410 }else{ 550 }else{
411 existsHostIps.add(mob.getMoHostIp()); 551 existsHostIps.add(mob.getMoHostIp());
412 } 552 }
@@ -417,7 +557,7 @@ public class CloudToolServiceImpl implements CloudToolService { @@ -417,7 +557,7 @@ public class CloudToolServiceImpl implements CloudToolService {
417 if(typeName.indexOf("java")>0){ 557 if(typeName.indexOf("java")>0){
418 port="port:21211"; 558 port="port:21211";
419 } 559 }
420 - String[] allIps=infoReq.getNewInstanceIps().split(","); 560 +
421 for(String ip:allIps){ 561 for(String ip:allIps){
422 if(StringUtils.isNotBlank(ip)&&!existsHostIps.contains(ip)){ 562 if(StringUtils.isNotBlank(ip)&&!existsHostIps.contains(ip)){
423 MObjectInfo mob=new MObjectInfo(); 563 MObjectInfo mob=new MObjectInfo();
@@ -426,7 +566,7 @@ public class CloudToolServiceImpl implements CloudToolService { @@ -426,7 +566,7 @@ public class CloudToolServiceImpl implements CloudToolService {
426 mob.setMoHostIp(ip); 566 mob.setMoHostIp(ip);
427 mob.setMoTypeId(typeInfo.getTypeId()); 567 mob.setMoTypeId(typeInfo.getTypeId());
428 mObjectInfoMapper.insertMoInfo(mob); 568 mObjectInfoMapper.insertMoInfo(mob);
429 - sb.append("添加"+typeName+"监控对象:"+mob.getMoId()+"\n"); 569 + sb.append("添加"+typeName+"监控对象:"+mob.getMoHostIp()+"\n");
430 } 570 }
431 } 571 }
432 res.setData(sb.toString()); 572 res.setData(sb.toString());
@@ -38,6 +38,12 @@ @@ -38,6 +38,12 @@
38 38
39 <!--项目内部依赖--> 39 <!--项目内部依赖-->
40 <dependency> 40 <dependency>
  41 + <groupId>org.bouncycastle</groupId>
  42 + <artifactId>bcprov-jdk16</artifactId>
  43 + <version>1.46</version>
  44 + </dependency>
  45 +
  46 + <dependency>
41 <groupId>org.codehaus.jackson</groupId> 47 <groupId>org.codehaus.jackson</groupId>
42 <artifactId>jackson-mapper-asl</artifactId> 48 <artifactId>jackson-mapper-asl</artifactId>
43 </dependency> 49 </dependency>
@@ -6,6 +6,7 @@ import com.monitor.cmdb.service.IHostInfoService; @@ -6,6 +6,7 @@ import com.monitor.cmdb.service.IHostInfoService;
6 import com.monitor.model.request.HostInfoReq; 6 import com.monitor.model.request.HostInfoReq;
7 import com.monitor.model.response.BaseResponse; 7 import com.monitor.model.response.BaseResponse;
8 import com.monitor.model.response.PageResponse; 8 import com.monitor.model.response.PageResponse;
  9 +import com.yoho.ops.cmdb.models.CmdbApiReq;
9 import org.slf4j.Logger; 10 import org.slf4j.Logger;
10 import org.slf4j.LoggerFactory; 11 import org.slf4j.LoggerFactory;
11 import org.springframework.beans.factory.annotation.Autowired; 12 import org.springframework.beans.factory.annotation.Autowired;
@@ -16,9 +17,7 @@ import org.springframework.web.bind.annotation.RequestMapping; @@ -16,9 +17,7 @@ import org.springframework.web.bind.annotation.RequestMapping;
16 import org.springframework.web.bind.annotation.RequestParam; 17 import org.springframework.web.bind.annotation.RequestParam;
17 import org.springframework.web.bind.annotation.ResponseBody; 18 import org.springframework.web.bind.annotation.ResponseBody;
18 19
19 -  
20 import java.util.HashSet; 20 import java.util.HashSet;
21 -  
22 import java.util.List; 21 import java.util.List;
23 import java.util.Set; 22 import java.util.Set;
24 23
@@ -36,6 +35,31 @@ public class HostInfoCtrl { @@ -36,6 +35,31 @@ public class HostInfoCtrl {
36 @Autowired 35 @Autowired
37 IHostInfoService hostInfoService; 36 IHostInfoService hostInfoService;
38 37
  38 + /**
  39 + * 根据提供的tags标签查询host。返回json串
  40 + * encodeTags 加密串需要解密之后再用
  41 + * @return
  42 + */
  43 + @RequestMapping("/getHostInfoJson")
  44 + @ResponseBody
  45 + public String getHostInfoJson(@RequestBody CmdbApiReq apiReq) {
  46 + log.debug("cmdbapi param {}", apiReq);
  47 + return hostInfoService.getHostInfoJson(apiReq.getSourceIp(), apiReq.getContent());
  48 + }
  49 +
  50 +
  51 + /**
  52 + * 根据提供的tags标签查询host。返回json串
  53 + * encodeTags 加密串需要解密之后再用
  54 + * @return
  55 + */
  56 + @RequestMapping("/getHostInfoJsonWithAuth")
  57 + @ResponseBody
  58 + public String getHostInfoJsonWithAuth(@RequestBody CmdbApiReq apiReq) {
  59 + log.debug("cmdbapi param {}", apiReq);
  60 + return hostInfoService.getHostInfoJsonWithAuth(apiReq.getSignature(),apiReq.getAppid(),apiReq.getTimestamp(),apiReq.getLol(),apiReq.getContent());
  61 + }
  62 +
39 @RequestMapping("/getHostInfos") 63 @RequestMapping("/getHostInfos")
40 @ResponseBody 64 @ResponseBody
41 public BaseResponse<PageResponse<HostInfo>> getHostInfos(@RequestBody HostInfoReq req) throws Exception { 65 public BaseResponse<PageResponse<HostInfo>> getHostInfos(@RequestBody HostInfoReq req) throws Exception {
@@ -11,6 +11,9 @@ import java.util.List; @@ -11,6 +11,9 @@ import java.util.List;
11 * Created by yoho on 2016/6/14. 11 * Created by yoho on 2016/6/14.
12 */ 12 */
13 public interface IHostInfoService { 13 public interface IHostInfoService {
  14 + String getHostInfoJson(String sourceIp ,String content);
  15 + String getHostInfoJsonWithAuth(String signature ,String appid ,String timestamp ,String lol,String content);
  16 +
14 PageResponse<HostInfo> getHostInfos(HostInfoReq req); 17 PageResponse<HostInfo> getHostInfos(HostInfoReq req);
15 18
16 BaseResponse<Integer> saveHostInfo(HostInfo req); 19 BaseResponse<Integer> saveHostInfo(HostInfo req);
1 package com.monitor.cmdb.service.impl; 1 package com.monitor.cmdb.service.impl;
2 2
  3 +import com.alibaba.fastjson.JSON;
  4 +import com.alibaba.fastjson.JSONArray;
  5 +import com.alibaba.fastjson.JSONObject;
3 import com.model.HostInfo; 6 import com.model.HostInfo;
4 import com.model.MObjectInfo; 7 import com.model.MObjectInfo;
5 import com.monitor.cmdb.service.IHostInfoService; 8 import com.monitor.cmdb.service.IHostInfoService;
6 import com.monitor.cmdb.service.IMObjectInfoService; 9 import com.monitor.cmdb.service.IMObjectInfoService;
  10 +import com.monitor.cmdb.util.AESTool;
  11 +import com.monitor.cmdb.util.SignatureUtil;
7 import com.monitor.model.domain.PageBean; 12 import com.monitor.model.domain.PageBean;
8 import com.monitor.model.request.HostInfoReq; 13 import com.monitor.model.request.HostInfoReq;
9 -import com.monitor.model.response.PageResponse;  
10 import com.monitor.model.response.BaseResponse; 14 import com.monitor.model.response.BaseResponse;
  15 +import com.monitor.model.response.PageResponse;
11 import com.monitor.mysql.mapper.HostInfoMapper; 16 import com.monitor.mysql.mapper.HostInfoMapper;
12 import org.apache.commons.lang.StringUtils; 17 import org.apache.commons.lang.StringUtils;
13 import org.slf4j.Logger; 18 import org.slf4j.Logger;
@@ -16,6 +21,7 @@ import org.springframework.beans.factory.annotation.Autowired; @@ -16,6 +21,7 @@ import org.springframework.beans.factory.annotation.Autowired;
16 import org.springframework.stereotype.Service; 21 import org.springframework.stereotype.Service;
17 import org.springframework.util.CollectionUtils; 22 import org.springframework.util.CollectionUtils;
18 23
  24 +import java.util.ArrayList;
19 import java.util.List; 25 import java.util.List;
20 26
21 /** 27 /**
@@ -33,6 +39,99 @@ public class HostInfoServiceImpl implements IHostInfoService { @@ -33,6 +39,99 @@ public class HostInfoServiceImpl implements IHostInfoService {
33 IMObjectInfoService mobjectInfoService; 39 IMObjectInfoService mobjectInfoService;
34 40
35 @Override 41 @Override
  42 + public String getHostInfoJson(String sourceIp ,String content){
  43 + logger.debug("begin getHostInfoJson");
  44 + String backJson="";
  45 + if(StringUtils.isNotBlank(content)&&sourceIp.startsWith("127")){
  46 + JSONObject jo=JSON.parseObject(content);
  47 + List<Integer> cloudTypeList=new ArrayList<Integer>();
  48 + List<String> tagsList=new ArrayList<String>();
  49 + if(jo!=null){
  50 + if(jo.containsKey("cloudType")){
  51 + String cloudTypeStr=jo.getString("cloudType");
  52 + if(StringUtils.isNotBlank(cloudTypeStr)){
  53 + for(String str:cloudTypeStr.split(",")){
  54 + if(StringUtils.isNotBlank(str)){
  55 + cloudTypeList.add(Integer.parseInt(str));
  56 + }
  57 + }
  58 + }
  59 + }
  60 + if(jo.containsKey("tags")){
  61 + JSONArray ja=jo.getJSONArray("tags");
  62 + for(int i=0;i<ja.size();i++){
  63 + String tag=ja.getString(i);
  64 + if(StringUtils.isNotBlank(tag)){
  65 + tagsList.add(tag);
  66 + }
  67 + }
  68 + }
  69 + }
  70 + //执行查询,至少要有一个tag
  71 + List<HostInfo> hostInfos=new ArrayList<HostInfo>();
  72 + if(tagsList.size()>0){
  73 + hostInfos=hostInfoMapper.selectHostInfosByTagListAndCloudTypeList(tagsList,cloudTypeList);
  74 + }
  75 + backJson=JSON.toJSONString(hostInfos);
  76 + }else{
  77 + backJson="bad request param ! please check content:"+content+" sourceIP "+sourceIp;
  78 + }
  79 + return backJson;
  80 + }
  81 +
  82 + @Override
  83 + public String getHostInfoJsonWithAuth(String signature ,String appid ,String timestamp ,String lol,String content){
  84 + String backJson="";
  85 + long millis = Long.valueOf(timestamp);
  86 + if (SignatureUtil.isValid(signature, appid, lol, millis)) {
  87 + try{
  88 + String key=AESTool.findKeyById(appid);
  89 + content= AESTool.decrypt(content,key);//{"cloudType":[1,2],"tags":["xxx","YYYz"]}
  90 + logger.debug("conterafterdecode: " + content);
  91 + if(StringUtils.isNotBlank(content)){
  92 + JSONObject jo=JSON.parseObject(content);
  93 + List<Integer> cloudTypeList=new ArrayList<Integer>();
  94 + List<String> tagsList=new ArrayList<String>();
  95 + if(jo!=null){
  96 + if(jo.containsKey("cloudType")){
  97 + String cloudTypeStr=jo.getString("cloudType");
  98 + if(StringUtils.isNotBlank(cloudTypeStr)){
  99 + for(String str:cloudTypeStr.split(",")){
  100 + if(StringUtils.isNotBlank(str)){
  101 + cloudTypeList.add(Integer.parseInt(str));
  102 + }
  103 + }
  104 + }
  105 + }
  106 + if(jo.containsKey("tags")){
  107 + JSONArray ja=jo.getJSONArray("tags");
  108 + for(int i=0;i<ja.size();i++){
  109 + String tag=ja.getString(i);
  110 + if(StringUtils.isNotBlank(tag)){
  111 + tagsList.add(tag);
  112 + }
  113 + }
  114 + }
  115 + }
  116 + //执行查询,至少要有一个tag
  117 + List<HostInfo> hostInfos=new ArrayList<HostInfo>();
  118 + if(tagsList.size()>0){
  119 + hostInfos=hostInfoMapper.selectHostInfosByTagListAndCloudTypeList(tagsList,cloudTypeList);
  120 + }
  121 + backJson=AESTool.encrypt(JSON.toJSONString(hostInfos),key);
  122 + }else{
  123 + backJson="bad request cause by param is null";
  124 + }
  125 + }catch (Exception e){
  126 + backJson="error when decrypt!";
  127 + }
  128 + }else{
  129 + backJson="InValid Signature!";
  130 + }
  131 + return backJson;
  132 + }
  133 +
  134 + @Override
36 public PageResponse<HostInfo> getHostInfos(HostInfoReq req) { 135 public PageResponse<HostInfo> getHostInfos(HostInfoReq req) {
37 logger.info("getHostInfos with param is {}", req); 136 logger.info("getHostInfos with param is {}", req);
38 // 组装分页对象 137 // 组装分页对象
  1 +package com.monitor.cmdb.util;
  2 +
  3 +import org.apache.commons.lang.StringUtils;
  4 +import org.bouncycastle.crypto.CipherParameters;
  5 +import org.bouncycastle.crypto.engines.AESFastEngine;
  6 +import org.bouncycastle.crypto.modes.CBCBlockCipher;
  7 +import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
  8 +import org.bouncycastle.crypto.params.KeyParameter;
  9 +import org.bouncycastle.crypto.params.ParametersWithIV;
  10 +import org.bouncycastle.util.encoders.Hex;
  11 +import org.slf4j.Logger;
  12 +import org.slf4j.LoggerFactory;
  13 +
  14 +/**
  15 + * AES encryption and decryption tool.
  16 + *
  17 + * @author ben
  18 + * @creation 2014年3月20日
  19 + */
  20 +public class AESTool {
  21 + private static Logger logger = LoggerFactory.getLogger(AESTool.class);
  22 +
  23 + private static byte[] initVector = { 0x32, 0x37, 0x36, 0x35, 0x34, 0x33, 0x32, 0x31,
  24 + 0x38, 0x27, 0x36, 0x35, 0x33, 0x23, 0x32, 0x31 };
  25 +
  26 + public static final String SECRECTID="yohoopscmdb001";
  27 + public static final String SECRECTKEY="yoho9646123456789YOHO964601234~!";
  28 + /**
  29 + * @param appid
  30 + * @return
  31 + */
  32 + public static String findKeyById(String appid) {
  33 + String key = "";
  34 + switch (appid){
  35 + case SECRECTID:
  36 + key = SECRECTKEY;
  37 + break;
  38 + }
  39 + return key;
  40 + }
  41 +
  42 + /**
  43 + * Encrypt the content with a given key using aes algorithm.
  44 + *
  45 + * @param content
  46 + * @param key
  47 + * must contain exactly 32 characters
  48 + * @return
  49 + * @throws Exception
  50 + */
  51 + public static String encrypt(String content, String key) throws Exception {
  52 + if (key == null) {
  53 + throw new IllegalArgumentException("Key cannot be null!");
  54 + }
  55 + String encrypted = null;
  56 + byte[] keyBytes = key.getBytes();
  57 + if (keyBytes.length != 32 && keyBytes.length != 24
  58 + && keyBytes.length != 16) {
  59 + throw new IllegalArgumentException(
  60 + "Key length must be 128/192/256 bits!");
  61 + }
  62 + byte[] encryptedBytes = null;
  63 + encryptedBytes = encrypt(content.getBytes(), keyBytes, initVector);
  64 + encrypted = new String(Hex.encode(encryptedBytes));
  65 + return encrypted;
  66 + }
  67 +
  68 + /**
  69 + * Decrypt the content with a given key using aes algorithm.
  70 + *
  71 + * @param content
  72 + * @param key
  73 + * must contain exactly 32 characters
  74 + * @return
  75 + * @throws Exception
  76 + */
  77 + public static String decrypt(String content, String key) throws Exception {
  78 + if (key == null) {
  79 + throw new IllegalArgumentException("Key cannot be null!");
  80 + }
  81 + String decrypted = null;
  82 + byte[] encryptedContent = Hex.decode(content);
  83 + byte[] keyBytes = key.getBytes();
  84 + byte[] decryptedBytes = null;
  85 + if (keyBytes.length != 32 && keyBytes.length != 24
  86 + && keyBytes.length != 16) {
  87 + throw new IllegalArgumentException(
  88 + "Key length must be 128/192/256 bits!");
  89 + }
  90 + decryptedBytes = decrypt(encryptedContent, keyBytes, initVector);
  91 + decrypted = new String(decryptedBytes);
  92 + return decrypted;
  93 + }
  94 +
  95 + /**
  96 + * Encrypt data.
  97 + *
  98 + * @param plain
  99 + * @param key
  100 + * @param iv
  101 + * @return
  102 + * @throws Exception
  103 + */
  104 + public static byte[] encrypt(byte[] plain, byte[] key, byte[] iv) throws Exception {
  105 + PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(
  106 + new CBCBlockCipher(new AESFastEngine()));
  107 + CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key),
  108 + iv);
  109 + aes.init(true, ivAndKey);
  110 + return cipherData(aes, plain);
  111 + }
  112 +
  113 + /**
  114 + * Decrypt data.
  115 + *
  116 + * @param cipher
  117 + * @param key
  118 + * @param iv
  119 + * @return
  120 + * @throws Exception
  121 + */
  122 + public static byte[] decrypt(byte[] cipher, byte[] key, byte[] iv)
  123 + throws Exception {
  124 + PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(
  125 + new CBCBlockCipher(new AESFastEngine()));
  126 + CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key),
  127 + iv);
  128 + aes.init(false, ivAndKey);
  129 + return cipherData(aes, cipher);
  130 + }
  131 +
  132 + /**
  133 + * Encrypt or decrypt data.
  134 + *
  135 + * @param cipher
  136 + * @param data
  137 + * @return
  138 + * @throws Exception
  139 + */
  140 + private static byte[] cipherData(PaddedBufferedBlockCipher cipher, byte[] data)
  141 + throws Exception {
  142 + int minSize = cipher.getOutputSize(data.length);
  143 + byte[] outBuf = new byte[minSize];
  144 + int length1 = cipher.processBytes(data, 0, data.length, outBuf, 0);
  145 + int length2 = cipher.doFinal(outBuf, length1);
  146 + int actualLength = length1 + length2;
  147 + byte[] result = new byte[actualLength];
  148 + System.arraycopy(outBuf, 0, result, 0, result.length);
  149 + return result;
  150 + }
  151 +
  152 + public static void main(String[] args) throws Exception {
  153 + AESTool aesTool = new AESTool();
  154 + String appid = "canairport001";
  155 + String key = aesTool.findKeyById(appid);
  156 + String xml = "<root><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name></root>";
  157 + String encrypted = aesTool.encrypt(xml, key);
  158 + System.out.println("encrypted: \n" + encrypted);
  159 + System.out.println("encrypted length: \n" + encrypted.length());
  160 + String decrypted = aesTool.decrypt(encrypted, key);
  161 + System.out.println("decrypted: \n" + decrypted);
  162 + System.out.println("decrypted length: \n" + decrypted.length());
  163 + boolean isSuccessful = StringUtils.equals(decrypted, xml);
  164 + System.out.println(isSuccessful);
  165 + }
  166 +}
  1 +package com.monitor.cmdb.util;
  2 +
  3 +import com.alibaba.fastjson.JSON;
  4 +import com.monitor.common.util.HttpClientUtil;
  5 +import org.springframework.web.bind.annotation.RequestMapping;
  6 +import org.springframework.web.bind.annotation.ResponseBody;
  7 +
  8 +import java.util.Arrays;
  9 +import java.util.HashMap;
  10 +import java.util.Map;
  11 +
  12 +/**
  13 + * Created by craig.qin on 2017/10/31.
  14 + */
  15 +public class CmdbApiPostDemo {
  16 +
  17 + /**
  18 + * 根据提供的tags标签查询host。返回json串
  19 + * encodeTags 加密串需要解密之后再用
  20 + * @return
  21 + */
  22 + //@RequestMapping("/test")
  23 + //@ResponseBody
  24 + public void testCmdbApi1() {
  25 + String url="http://127.0.0.1:8080/cmdb/api";
  26 + Map<String ,Object> contentList=new HashMap<String,Object>();
  27 + contentList.put("cloudType","1,2");
  28 + contentList.put("tags", Arrays.asList(new String[]{"java"}));
  29 + String content = JSON.toJSONString(contentList);
  30 + String result = HttpClientUtil.doPost(url, content, null);
  31 + System.out.println("返回的结果:"+result);
  32 + }
  33 + /**
  34 + * 根据提供的tags标签查询host。返回json串
  35 + * encodeTags 加密串需要解密之后再用
  36 + * @return
  37 + */
  38 + //@RequestMapping("/testCmdbApi2")
  39 + //@ResponseBody
  40 + public void testCmdbApi2() {
  41 + try{
  42 + String appid = AESTool.SECRECTID;
  43 + String key = AESTool.findKeyById(appid);
  44 + Map<String ,Object> contentList=new HashMap<String,Object>();
  45 + contentList.put("cloudType","1,2");
  46 + contentList.put("tags",Arrays.asList(new String[]{"java"}));
  47 + String content = JSON.toJSONString(contentList);
  48 + content = AESTool.encrypt(content, key);
  49 + System.out.println("加密之后的内容:"+content);
  50 +
  51 + String token = SignatureUtil.findTokenById(appid);
  52 + String lol = SignatureUtil.digest(content, "MD5");
  53 + long millis = System.currentTimeMillis();
  54 + String signature = SignatureUtil.generateSignature(appid, token, lol,
  55 + millis);
  56 +
  57 + Map<String, String> paraMap = new HashMap<String, String>();
  58 + paraMap.put("s", signature);
  59 + paraMap.put("a", appid);
  60 + paraMap.put("t", String.valueOf(millis));
  61 + paraMap.put("l", lol);
  62 + String url="http://127.0.0.1:8080/cmdb/api2";
  63 + url=SignatureUtil.buildUri(url, paraMap);
  64 +
  65 + System.out.println("新url:"+url);
  66 +
  67 + String result = HttpClientUtil.doPost(url, content,null);
  68 + System.out.println("返回的密文:"+result);
  69 + System.out.println("解密:"+AESTool.decrypt(result,key));
  70 + }catch (Exception e){
  71 + //System.out.println("exception is happen",e);
  72 + }
  73 +
  74 + }
  75 +
  76 +}
  1 +package com.monitor.cmdb.util;
  2 +
  3 +import org.apache.commons.lang.StringUtils;
  4 +import org.slf4j.Logger;
  5 +import org.slf4j.LoggerFactory;
  6 +
  7 +import java.security.MessageDigest;
  8 +import java.security.NoSuchAlgorithmException;
  9 +import java.util.*;
  10 +
  11 +/**
  12 + * Created by craig.qin on 2017/10/31.
  13 + */
  14 +public class SignatureUtil {
  15 + private static Logger log = LoggerFactory.getLogger(SignatureUtil.class);
  16 +
  17 + private static final char[] hexArray = "0123456789ABCDEF".toCharArray();
  18 +
  19 + private static String encryptionAlgorithm = "SHA-1";
  20 +
  21 + /**
  22 + * 根据传入的uri和参数map拼接成实际uri
  23 + *
  24 + * @param uri
  25 + * @param paraMap
  26 + * @return
  27 + */
  28 + public static String buildUri(String uri, Map<String, String> paraMap) {
  29 + StringBuilder sb = new StringBuilder();
  30 + uri = StringUtils.trim(uri);
  31 + uri = StringUtils.removeEnd(uri, "/");
  32 + uri = StringUtils.removeEnd(uri, "?");
  33 + sb.append(uri);
  34 + if (paraMap != null && !paraMap.isEmpty()) {
  35 + sb.append("?");
  36 + Iterator<Map.Entry<String, String>> iterator = paraMap.entrySet()
  37 + .iterator();
  38 + while (iterator.hasNext()) {
  39 + Map.Entry<String, String> pair = iterator.next();
  40 + try {
  41 + String keyString = pair.getKey();
  42 + String valueString = pair.getValue();
  43 + sb.append(keyString);
  44 + sb.append("=");
  45 + sb.append(valueString);
  46 + sb.append("&");
  47 + } catch (Exception e) {
  48 + log.error("error", e);
  49 + }
  50 + }
  51 + }
  52 + return StringUtils.removeEnd(sb.toString(), "&");
  53 + }
  54 +
  55 + public static String bytesToHexString(byte[] bytes) {
  56 + char[] hexChars = new char[bytes.length * 2];
  57 + for (int j = 0; j < bytes.length; j++) {
  58 + int v = bytes[j] & 0xFF;
  59 + hexChars[j * 2] = hexArray[v >>> 4];
  60 + hexChars[j * 2 + 1] = hexArray[v & 0x0F];
  61 + }
  62 + return new String(hexChars);
  63 + }
  64 +
  65 + /* public static byte[] hexStringToBytes(String s) {
  66 + int len = s.length();
  67 + byte[] data = new byte[len / 2];
  68 + for (int i = 0; i < len; i += 2) {
  69 + data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character
  70 + .digit(s.charAt(i + 1), 16));
  71 + }
  72 + return data;
  73 + }*/
  74 +
  75 + /**
  76 + * 使用指定算法生成消息摘要,默认是md5
  77 + *
  78 + * @param strSrc
  79 + * , a string will be encrypted; <br/>
  80 + * @param encName
  81 + * , the algorithm name will be used, dafault to "MD5"; <br/>
  82 + * @return
  83 + */
  84 + public static String digest(String strSrc, String encName) {
  85 + MessageDigest md = null;
  86 + String strDes = null;
  87 + byte[] bt = strSrc.getBytes();
  88 + try {
  89 + if (encName == null || encName.equals("")) {
  90 + encName = "MD5";
  91 + }
  92 + md = MessageDigest.getInstance(encName);
  93 + md.update(bt);
  94 + strDes = bytesToHexString(md.digest()); // to HexString
  95 + } catch (NoSuchAlgorithmException e) {
  96 + log.error("Invalid algorithm: " + encName);
  97 + return null;
  98 + }
  99 + return strDes;
  100 + }
  101 +
  102 + /**
  103 + * 根据appid、token、lol以及时间戳来生成签名
  104 + *
  105 + * @param appid
  106 + * @param token
  107 + * @param lol
  108 + * @param millis
  109 + * @return
  110 + */
  111 + public static String generateSignature(String appid, String token, String lol,
  112 + long millis) {
  113 + String timestamp = String.valueOf(millis);
  114 + String signature = null;
  115 + if (StringUtils.isNotBlank(token) && StringUtils.isNotBlank(timestamp)
  116 + && StringUtils.isNotBlank(appid)) {
  117 + List<String> srcList = new ArrayList<String>();
  118 + srcList.add(timestamp);
  119 + srcList.add(appid);
  120 + srcList.add(token);
  121 + srcList.add(lol);
  122 + // 按照字典序逆序拼接参数
  123 + Collections.sort(srcList);
  124 + Collections.reverse(srcList);
  125 + StringBuilder sb = new StringBuilder();
  126 + for (int i = 0; i < srcList.size(); i++) {
  127 + sb.append(srcList.get(i));
  128 + }
  129 + signature = digest(sb.toString(), encryptionAlgorithm);
  130 + srcList.clear();
  131 + }
  132 + return signature;
  133 + }
  134 +
  135 + /**
  136 + * 验证签名: <br/>
  137 + * 1.根据appid获取该渠道的token;<br/>
  138 + * 2.根据appid、token、lol以及时间戳计算一次签名;<br/>
  139 + * 3.比较传过来的签名以及计算出的签名是否一致;
  140 + * @param signature
  141 + * @param appid
  142 + * @param lol
  143 + * @param millis
  144 + * @return
  145 + */
  146 + public static boolean isValid(String signature, String appid, String lol,
  147 + long millis) {
  148 + String token = findTokenById(appid);
  149 + String calculatedSignature = generateSignature(appid, token, lol,
  150 + millis);
  151 + log.info("calculated signature: \n" + calculatedSignature);
  152 + if (StringUtils.equals(calculatedSignature, signature)) {
  153 + return true;
  154 + } else {
  155 + return false;
  156 + }
  157 + }
  158 +
  159 + /**
  160 + *
  161 + * @param appid
  162 + * @return
  163 + */
  164 + public static String findTokenById(String appid) {
  165 + String token = "";
  166 + switch (appid){
  167 + case AESTool.SECRECTID:
  168 + token = "#@!1234567890!@#";
  169 + break;
  170 + }
  171 + return token;
  172 + }
  173 +
  174 + public static void main(String[] args) {
  175 + SignatureUtil generator = new SignatureUtil();
  176 + String xmlString = "<root><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name></root>";
  177 + System.out.println(xmlString.getBytes().length);
  178 + String digest = generator.digest(xmlString, "MD5");
  179 + System.out.println(digest);
  180 + System.out.println(digest.getBytes().length);
  181 + String appid = "canairport001";
  182 + String token = generator.findTokenById(appid);
  183 + long millis = System.currentTimeMillis();
  184 + String signature = generator.generateSignature(appid, token, digest,
  185 + millis);
  186 + System.out.println(signature);
  187 + boolean isValid = generator.isValid(signature, appid, digest, millis);
  188 + System.out.println(isValid);
  189 + }
  190 +}
  191 +
  1 +package com.yoho.ops.cmdb.models;
  2 +
  3 +import lombok.Data;
  4 +
  5 +/**
  6 + * Created by craig.qin on 2017/10/31.
  7 + */
  8 +@Data
  9 +public class CmdbApiReq {
  10 + //来源ip
  11 + private String sourceIp;
  12 + //生成的签名
  13 + private String signature ;
  14 + //分配的应用id或者secrectid
  15 + private String appid ;
  16 + //生成前面时的时间戳
  17 + private String timestamp ;
  18 + //签名摘要
  19 + private String lol;
  20 + //加密后的内容
  21 + private String content;
  22 +}
@@ -90,8 +90,8 @@ public interface StaticVar { @@ -90,8 +90,8 @@ public interface StaticVar {
90 90
91 String PLATFORM_SERVICE = "platform.addSort"; 91 String PLATFORM_SERVICE = "platform.addSort";
92 92
93 - String RESOURCES_SERVICE = "resources.getCategory";  
94 - 93 + //String RESOURCES_SERVICE = "resources.getCategory";
  94 + String RESOURCES_SERVICE ="resources.queryProductBanner";
95 String SNS_SERVICE = "sns.getList"; 95 String SNS_SERVICE = "sns.getList";
96 96
97 String USERS_SERVICE = "users.bind"; 97 String USERS_SERVICE = "users.bind";
@@ -98,7 +98,7 @@ public class QcloudBandwidthTask { @@ -98,7 +98,7 @@ public class QcloudBandwidthTask {
98 } 98 }
99 bandwidthMapper.insert(intraffic,outtraffic); 99 bandwidthMapper.insert(intraffic,outtraffic);
100 logger.info("QcloudBandwidthTask over "); 100 logger.info("QcloudBandwidthTask over ");
101 - if (intraffic > 200000 || outtraffic > 200000){ 101 + if (intraffic > 100 || outtraffic > 100){
102 alarmMsgService.sendSms("bandwidth", "专线带宽使用过多,请查看" , snsMobileConfig.getBaseMobile()); 102 alarmMsgService.sendSms("bandwidth", "专线带宽使用过多,请查看" , snsMobileConfig.getBaseMobile());
103 } 103 }
104 } catch (Exception e) { 104 } catch (Exception e) {
@@ -27,6 +27,8 @@ public interface HostInfoMapper { @@ -27,6 +27,8 @@ public interface HostInfoMapper {
27 27
28 List<HostInfo> selectHostInfosByTagList(@Param("tagsList") List<String> tagList); 28 List<HostInfo> selectHostInfosByTagList(@Param("tagsList") List<String> tagList);
29 29
  30 + List<HostInfo> selectHostInfosByTagListAndCloudTypeList(@Param("tagsList") List<String> tagList,@Param("cloudTypeList") List<Integer> cloudTypeList );
  31 +
30 List<HostInfo> selectHostInfosByTagAndCloudType(@Param("tag") String tag,@Param("cloudType") int cloudType); 32 List<HostInfo> selectHostInfosByTagAndCloudType(@Param("tag") String tag,@Param("cloudType") int cloudType);
31 33
32 HostInfo selectByHostIp(@Param("hostIp") String hostIp); 34 HostInfo selectByHostIp(@Param("hostIp") String hostIp);
@@ -202,6 +202,27 @@ @@ -202,6 +202,27 @@
202 </if> 202 </if>
203 </select> 203 </select>
204 204
  205 + <select id="selectHostInfosByTagListAndCloudTypeList" resultMap="BaseResultMap">
  206 + select
  207 + <include refid="Base_Column_List" />
  208 + from host_info
  209 + where 1=1
  210 + <if test="tagsList != null &amp;&amp; tagsList.size > 0" >
  211 + and
  212 + <foreach open="(" close=")" item="item" index="index" collection="tagsList" separator="and">
  213 + instr(tags, #{item}) &gt; 0
  214 + </foreach>
  215 + </if>
  216 +
  217 + <if test="cloudTypeList != null &amp;&amp; cloudTypeList.size > 0" >
  218 + and
  219 + <foreach open="(" close=")" item="item" index="index" collection="cloudTypeList" separator="or">
  220 + cloud_type = #{item}
  221 + </foreach>
  222 + </if>
  223 +
  224 + </select>
  225 +
205 <select id="selectHostInfosByTagAndCloudType" resultMap="BaseResultMap" > 226 <select id="selectHostInfosByTagAndCloudType" resultMap="BaseResultMap" >
206 select 227 select
207 <include refid="Base_Column_List" /> 228 <include refid="Base_Column_List" />