Authored by qinchao

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

... ... @@ -242,8 +242,7 @@ public class CloudToolController {
@RequestMapping("/updateMobjectInfo")
@ResponseBody
public BaseResponse updateMobjectInfo(@RequestBody AutoScalingInfoReq infoReq){
cloudToolService.updateMobjectInfo(infoReq);
return new BaseResponse();
return cloudToolService.updateMobjectInfo(infoReq);
}
/**
... ...
... ... @@ -316,11 +316,134 @@ public class CloudToolServiceImpl implements CloudToolService {
return updateMobject4Nginx(infoReq);
}else if ("PCH5-memcache".equalsIgnoreCase(infoReq.getScalingGroupName())||"java-gateway-memcache".equalsIgnoreCase(infoReq.getScalingGroupName())){
return updateMemcacheInfoForMobject(infoReq);
}else if("ELASTICSEARCH".equalsIgnoreCase(infoReq.getScalingGroupName())){
//暂时不做
}else if("PCH5-NODE".equalsIgnoreCase(infoReq.getScalingGroupName())||"PCH5-AutoScaling".equalsIgnoreCase(infoReq.getScalingGroupName())){
//暂时不做
}else{
////// 普通java项目
return updateMobject4JavaApp(infoReq);
}
}
return res;
}
/// java app的监控配置,java_nginx 既包括172 ,又包括10,所以更新的时候,如果要删除需要只删除当前云
private BaseResponse updateMobject4JavaApp(AutoScalingInfoReq infoReq){
BaseResponse res = new BaseResponse();
String environment="";
if(1==infoReq.getCloudType()){
environment="aws";
}else if(2==infoReq.getCloudType()){
environment="qcloud";
}
String mobjectPaths=infoReq.getMobjectPaths();
String[] mobjectPaths_array=mobjectPaths.split(",");
String typeNames=mobjectPaths_array[mobjectPaths_array.length-1];//////////有可能是多个,比如activity-bigdata
StringBuilder sb=new StringBuilder();
String[] allIps=infoReq.getNewInstanceIps().split(",");
List<String> allIpsList=new ArrayList<String>();
for(String ip:allIps){
if(StringUtils.isNotBlank(ip)){
allIpsList.add(ip);
}
}
for(String typeName:typeNames.split("-")){
mobjectPaths_array[mobjectPaths_array.length-1]=typeName;
TypeInfo typeInfo = getTypeByMobjectPathArray(mobjectPaths_array);
if(typeInfo!=null){
List<MObjectInfo> objectInfoList = mObjectInfoMapper.getTypeMosInfo(typeInfo.getTypeId());
List<String> existsHostIps=new ArrayList<String>();
if(objectInfoList!=null&&objectInfoList.size()>0){
for(MObjectInfo mob:objectInfoList){
//处理移除的机器,但是要保留另外一个云的机器信息
if(!allIpsList.contains(mob.getMoHostIp())){
if(environment.equals("aws")&&mob.getMoHostIp().startsWith("172.")){
mObjectInfoMapper.deleteMoInfo(mob.getMoId());
sb.append("删除"+typeName+"监控对象:"+mob.getMoHostIp()+"\n");
}
if(environment.equals("qcloud")&&mob.getMoHostIp().startsWith("10.")){
mObjectInfoMapper.deleteMoInfo(mob.getMoId());
sb.append("删除"+typeName+"监控对象:"+mob.getMoHostIp()+"\n");
}
}else{
existsHostIps.add(mob.getMoHostIp());
}
}
}
//处理新增的机器
for(String ip:allIps){
if(StringUtils.isNotBlank(ip)&&!existsHostIps.contains(ip)){
MObjectInfo mob=new MObjectInfo();
mob.setMoName(buildMoName(typeName,environment));
mob.setMoHostIp(ip);
mob.setMoTags(getMobjectTagsForJavaApp(typeName));
mob.setMoTypeId(typeInfo.getTypeId());
mObjectInfoMapper.insertMoInfo(mob);
sb.append("添加"+typeName+"监控对象:"+mob.getMoHostIp()+"\n");
}
}
}
}
res.setData(sb.toString());
return res;
}
// 获取java app的标签 :端口号
private String getMobjectTagsForJavaApp(String typeName){
String tag="";
switch (typeName){
case "gateway":
tag="8080";
break;
case "order":
tag="8084";
break;
case "promotion":
tag="8085";
break;
case "product":
tag="8083";
break;
case "message":
tag="8086";
break;
case "sns":
tag="8082";
break;
case "users":
tag="8081";
break;
case "resources":
tag="8087";
break;
case "activity":
tag="8090";
break;
case "union":
tag="";
break;
case "brower":
tag="8092";
break;
case "social":
tag="8095";
break;
case "uic":
tag="8096";
break;
case "bigdata":
tag="";
break;
case "yoho!now":
tag="";
break;
}
return tag;
}
/// nginx的监控配置,java_nginx 既包括172 ,又包括10,所以更新的时候,如果要删除需要只删除当前云
private BaseResponse updateMobject4Nginx(AutoScalingInfoReq infoReq){
BaseResponse res = new BaseResponse();
... ... @@ -343,18 +466,27 @@ public class CloudToolServiceImpl implements CloudToolService {
StringBuilder sb=new StringBuilder();
List<MObjectInfo> objectInfoList = mObjectInfoMapper.getTypeMosInfo(typeInfo.getTypeId());
String[] allIps=infoReq.getNewInstanceIps().split(",");
List<String> allIpsList=new ArrayList<String>();
for(String ip:allIps){
if(StringUtils.isNotBlank(ip)){
allIpsList.add(ip);
}
}
List<String> existsHostIps=new ArrayList<String>();
if(objectInfoList!=null&&objectInfoList.size()>0){
for(MObjectInfo mob:objectInfoList){
//处理移除的机器,但是要保留另外一个云的机器信息
if(infoReq.getNewInstanceIps().indexOf(mob.getMoHostIp())<0){
if(!allIpsList.contains(mob.getMoHostIp())){
if(environment.equals("aws")&&mob.getMoHostIp().startsWith("172.")){
mObjectInfoMapper.deleteMoInfo(mob.getMoId());
sb.append("删除"+typeName+"监控对象:"+mob.getMoId()+"\n");
sb.append("删除"+typeName+"监控对象:"+mob.getMoHostIp()+"\n");
}
if(environment.equals("qcloud")&&mob.getMoHostIp().startsWith("10.")){
mObjectInfoMapper.deleteMoInfo(mob.getMoId());
sb.append("删除"+typeName+"监控对象:"+mob.getMoId()+"\n");
sb.append("删除"+typeName+"监控对象:"+mob.getMoHostIp()+"\n");
}
}else{
existsHostIps.add(mob.getMoHostIp());
... ... @@ -362,7 +494,6 @@ public class CloudToolServiceImpl implements CloudToolService {
}
}
//处理新增的机器
String[] allIps=infoReq.getNewInstanceIps().split(",");
for(String ip:allIps){
if(StringUtils.isNotBlank(ip)&&!existsHostIps.contains(ip)){
MObjectInfo mob=new MObjectInfo();
... ... @@ -370,7 +501,7 @@ public class CloudToolServiceImpl implements CloudToolService {
mob.setMoHostIp(ip);
mob.setMoTypeId(typeInfo.getTypeId());
mObjectInfoMapper.insertMoInfo(mob);
sb.append("添加"+typeName+"监控对象:"+mob.getMoId()+"\n");
sb.append("添加"+typeName+"监控对象:"+mob.getMoHostIp()+"\n");
}
}
res.setData(sb.toString());
... ... @@ -400,13 +531,22 @@ public class CloudToolServiceImpl implements CloudToolService {
StringBuilder sb=new StringBuilder();
List<MObjectInfo> objectInfoList = mObjectInfoMapper.getTypeMosInfo(typeInfo.getTypeId());
String[] allIps=infoReq.getNewInstanceIps().split(",");
List<String> allIpsList=new ArrayList<String>();
for(String ip:allIps){
if(StringUtils.isNotBlank(ip)){
allIpsList.add(ip);
}
}
List<String> existsHostIps=new ArrayList<String>();
if(objectInfoList!=null&&objectInfoList.size()>0){
for(MObjectInfo mob:objectInfoList){
//处理移除的机器
if(infoReq.getNewInstanceIps().indexOf(mob.getMoHostIp())<0){
if(!allIpsList.contains(mob.getMoHostIp())){
mObjectInfoMapper.deleteMoInfo(mob.getMoId());
sb.append("删除"+typeName+"监控对象:"+mob.getMoId()+"\n");
sb.append("删除"+typeName+"监控对象:"+mob.getMoHostIp()+"\n");
}else{
existsHostIps.add(mob.getMoHostIp());
}
... ... @@ -417,7 +557,7 @@ public class CloudToolServiceImpl implements CloudToolService {
if(typeName.indexOf("java")>0){
port="port:21211";
}
String[] allIps=infoReq.getNewInstanceIps().split(",");
for(String ip:allIps){
if(StringUtils.isNotBlank(ip)&&!existsHostIps.contains(ip)){
MObjectInfo mob=new MObjectInfo();
... ... @@ -426,7 +566,7 @@ public class CloudToolServiceImpl implements CloudToolService {
mob.setMoHostIp(ip);
mob.setMoTypeId(typeInfo.getTypeId());
mObjectInfoMapper.insertMoInfo(mob);
sb.append("添加"+typeName+"监控对象:"+mob.getMoId()+"\n");
sb.append("添加"+typeName+"监控对象:"+mob.getMoHostIp()+"\n");
}
}
res.setData(sb.toString());
... ...
... ... @@ -38,6 +38,12 @@
<!--项目内部依赖-->
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk16</artifactId>
<version>1.46</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
</dependency>
... ...
... ... @@ -6,6 +6,7 @@ import com.monitor.cmdb.service.IHostInfoService;
import com.monitor.model.request.HostInfoReq;
import com.monitor.model.response.BaseResponse;
import com.monitor.model.response.PageResponse;
import com.yoho.ops.cmdb.models.CmdbApiReq;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
... ... @@ -16,9 +17,7 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
... ... @@ -36,6 +35,31 @@ public class HostInfoCtrl {
@Autowired
IHostInfoService hostInfoService;
/**
* 根据提供的tags标签查询host。返回json串
* encodeTags 加密串需要解密之后再用
* @return
*/
@RequestMapping("/getHostInfoJson")
@ResponseBody
public String getHostInfoJson(@RequestBody CmdbApiReq apiReq) {
log.debug("cmdbapi param {}", apiReq);
return hostInfoService.getHostInfoJson(apiReq.getSourceIp(), apiReq.getContent());
}
/**
* 根据提供的tags标签查询host。返回json串
* encodeTags 加密串需要解密之后再用
* @return
*/
@RequestMapping("/getHostInfoJsonWithAuth")
@ResponseBody
public String getHostInfoJsonWithAuth(@RequestBody CmdbApiReq apiReq) {
log.debug("cmdbapi param {}", apiReq);
return hostInfoService.getHostInfoJsonWithAuth(apiReq.getSignature(),apiReq.getAppid(),apiReq.getTimestamp(),apiReq.getLol(),apiReq.getContent());
}
@RequestMapping("/getHostInfos")
@ResponseBody
public BaseResponse<PageResponse<HostInfo>> getHostInfos(@RequestBody HostInfoReq req) throws Exception {
... ...
... ... @@ -11,6 +11,9 @@ import java.util.List;
* Created by yoho on 2016/6/14.
*/
public interface IHostInfoService {
String getHostInfoJson(String sourceIp ,String content);
String getHostInfoJsonWithAuth(String signature ,String appid ,String timestamp ,String lol,String content);
PageResponse<HostInfo> getHostInfos(HostInfoReq req);
BaseResponse<Integer> saveHostInfo(HostInfo req);
... ...
package com.monitor.cmdb.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.model.HostInfo;
import com.model.MObjectInfo;
import com.monitor.cmdb.service.IHostInfoService;
import com.monitor.cmdb.service.IMObjectInfoService;
import com.monitor.cmdb.util.AESTool;
import com.monitor.cmdb.util.SignatureUtil;
import com.monitor.model.domain.PageBean;
import com.monitor.model.request.HostInfoReq;
import com.monitor.model.response.PageResponse;
import com.monitor.model.response.BaseResponse;
import com.monitor.model.response.PageResponse;
import com.monitor.mysql.mapper.HostInfoMapper;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
... ... @@ -16,6 +21,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.List;
/**
... ... @@ -33,6 +39,99 @@ public class HostInfoServiceImpl implements IHostInfoService {
IMObjectInfoService mobjectInfoService;
@Override
public String getHostInfoJson(String sourceIp ,String content){
logger.debug("begin getHostInfoJson");
String backJson="";
if(StringUtils.isNotBlank(content)&&sourceIp.startsWith("127")){
JSONObject jo=JSON.parseObject(content);
List<Integer> cloudTypeList=new ArrayList<Integer>();
List<String> tagsList=new ArrayList<String>();
if(jo!=null){
if(jo.containsKey("cloudType")){
String cloudTypeStr=jo.getString("cloudType");
if(StringUtils.isNotBlank(cloudTypeStr)){
for(String str:cloudTypeStr.split(",")){
if(StringUtils.isNotBlank(str)){
cloudTypeList.add(Integer.parseInt(str));
}
}
}
}
if(jo.containsKey("tags")){
JSONArray ja=jo.getJSONArray("tags");
for(int i=0;i<ja.size();i++){
String tag=ja.getString(i);
if(StringUtils.isNotBlank(tag)){
tagsList.add(tag);
}
}
}
}
//执行查询,至少要有一个tag
List<HostInfo> hostInfos=new ArrayList<HostInfo>();
if(tagsList.size()>0){
hostInfos=hostInfoMapper.selectHostInfosByTagListAndCloudTypeList(tagsList,cloudTypeList);
}
backJson=JSON.toJSONString(hostInfos);
}else{
backJson="bad request param ! please check content:"+content+" sourceIP "+sourceIp;
}
return backJson;
}
@Override
public String getHostInfoJsonWithAuth(String signature ,String appid ,String timestamp ,String lol,String content){
String backJson="";
long millis = Long.valueOf(timestamp);
if (SignatureUtil.isValid(signature, appid, lol, millis)) {
try{
String key=AESTool.findKeyById(appid);
content= AESTool.decrypt(content,key);//{"cloudType":[1,2],"tags":["xxx","YYYz"]}
logger.debug("conterafterdecode: " + content);
if(StringUtils.isNotBlank(content)){
JSONObject jo=JSON.parseObject(content);
List<Integer> cloudTypeList=new ArrayList<Integer>();
List<String> tagsList=new ArrayList<String>();
if(jo!=null){
if(jo.containsKey("cloudType")){
String cloudTypeStr=jo.getString("cloudType");
if(StringUtils.isNotBlank(cloudTypeStr)){
for(String str:cloudTypeStr.split(",")){
if(StringUtils.isNotBlank(str)){
cloudTypeList.add(Integer.parseInt(str));
}
}
}
}
if(jo.containsKey("tags")){
JSONArray ja=jo.getJSONArray("tags");
for(int i=0;i<ja.size();i++){
String tag=ja.getString(i);
if(StringUtils.isNotBlank(tag)){
tagsList.add(tag);
}
}
}
}
//执行查询,至少要有一个tag
List<HostInfo> hostInfos=new ArrayList<HostInfo>();
if(tagsList.size()>0){
hostInfos=hostInfoMapper.selectHostInfosByTagListAndCloudTypeList(tagsList,cloudTypeList);
}
backJson=AESTool.encrypt(JSON.toJSONString(hostInfos),key);
}else{
backJson="bad request cause by param is null";
}
}catch (Exception e){
backJson="error when decrypt!";
}
}else{
backJson="InValid Signature!";
}
return backJson;
}
@Override
public PageResponse<HostInfo> getHostInfos(HostInfoReq req) {
logger.info("getHostInfos with param is {}", req);
// 组装分页对象
... ...
package com.monitor.cmdb.util;
import org.apache.commons.lang.StringUtils;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.engines.AESFastEngine;
import org.bouncycastle.crypto.modes.CBCBlockCipher;
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;
import org.bouncycastle.util.encoders.Hex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* AES encryption and decryption tool.
*
* @author ben
* @creation 2014年3月20日
*/
public class AESTool {
private static Logger logger = LoggerFactory.getLogger(AESTool.class);
private static byte[] initVector = { 0x32, 0x37, 0x36, 0x35, 0x34, 0x33, 0x32, 0x31,
0x38, 0x27, 0x36, 0x35, 0x33, 0x23, 0x32, 0x31 };
public static final String SECRECTID="yohoopscmdb001";
public static final String SECRECTKEY="yoho9646123456789YOHO964601234~!";
/**
* @param appid
* @return
*/
public static String findKeyById(String appid) {
String key = "";
switch (appid){
case SECRECTID:
key = SECRECTKEY;
break;
}
return key;
}
/**
* Encrypt the content with a given key using aes algorithm.
*
* @param content
* @param key
* must contain exactly 32 characters
* @return
* @throws Exception
*/
public static String encrypt(String content, String key) throws Exception {
if (key == null) {
throw new IllegalArgumentException("Key cannot be null!");
}
String encrypted = null;
byte[] keyBytes = key.getBytes();
if (keyBytes.length != 32 && keyBytes.length != 24
&& keyBytes.length != 16) {
throw new IllegalArgumentException(
"Key length must be 128/192/256 bits!");
}
byte[] encryptedBytes = null;
encryptedBytes = encrypt(content.getBytes(), keyBytes, initVector);
encrypted = new String(Hex.encode(encryptedBytes));
return encrypted;
}
/**
* Decrypt the content with a given key using aes algorithm.
*
* @param content
* @param key
* must contain exactly 32 characters
* @return
* @throws Exception
*/
public static String decrypt(String content, String key) throws Exception {
if (key == null) {
throw new IllegalArgumentException("Key cannot be null!");
}
String decrypted = null;
byte[] encryptedContent = Hex.decode(content);
byte[] keyBytes = key.getBytes();
byte[] decryptedBytes = null;
if (keyBytes.length != 32 && keyBytes.length != 24
&& keyBytes.length != 16) {
throw new IllegalArgumentException(
"Key length must be 128/192/256 bits!");
}
decryptedBytes = decrypt(encryptedContent, keyBytes, initVector);
decrypted = new String(decryptedBytes);
return decrypted;
}
/**
* Encrypt data.
*
* @param plain
* @param key
* @param iv
* @return
* @throws Exception
*/
public static byte[] encrypt(byte[] plain, byte[] key, byte[] iv) throws Exception {
PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(
new CBCBlockCipher(new AESFastEngine()));
CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key),
iv);
aes.init(true, ivAndKey);
return cipherData(aes, plain);
}
/**
* Decrypt data.
*
* @param cipher
* @param key
* @param iv
* @return
* @throws Exception
*/
public static byte[] decrypt(byte[] cipher, byte[] key, byte[] iv)
throws Exception {
PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(
new CBCBlockCipher(new AESFastEngine()));
CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key),
iv);
aes.init(false, ivAndKey);
return cipherData(aes, cipher);
}
/**
* Encrypt or decrypt data.
*
* @param cipher
* @param data
* @return
* @throws Exception
*/
private static byte[] cipherData(PaddedBufferedBlockCipher cipher, byte[] data)
throws Exception {
int minSize = cipher.getOutputSize(data.length);
byte[] outBuf = new byte[minSize];
int length1 = cipher.processBytes(data, 0, data.length, outBuf, 0);
int length2 = cipher.doFinal(outBuf, length1);
int actualLength = length1 + length2;
byte[] result = new byte[actualLength];
System.arraycopy(outBuf, 0, result, 0, result.length);
return result;
}
public static void main(String[] args) throws Exception {
AESTool aesTool = new AESTool();
String appid = "canairport001";
String key = aesTool.findKeyById(appid);
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>";
String encrypted = aesTool.encrypt(xml, key);
System.out.println("encrypted: \n" + encrypted);
System.out.println("encrypted length: \n" + encrypted.length());
String decrypted = aesTool.decrypt(encrypted, key);
System.out.println("decrypted: \n" + decrypted);
System.out.println("decrypted length: \n" + decrypted.length());
boolean isSuccessful = StringUtils.equals(decrypted, xml);
System.out.println(isSuccessful);
}
}
\ No newline at end of file
... ...
package com.monitor.cmdb.util;
import com.alibaba.fastjson.JSON;
import com.monitor.common.util.HttpClientUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Created by craig.qin on 2017/10/31.
*/
public class CmdbApiPostDemo {
/**
* 根据提供的tags标签查询host。返回json串
* encodeTags 加密串需要解密之后再用
* @return
*/
//@RequestMapping("/test")
//@ResponseBody
public void testCmdbApi1() {
String url="http://127.0.0.1:8080/cmdb/api";
Map<String ,Object> contentList=new HashMap<String,Object>();
contentList.put("cloudType","1,2");
contentList.put("tags", Arrays.asList(new String[]{"java"}));
String content = JSON.toJSONString(contentList);
String result = HttpClientUtil.doPost(url, content, null);
System.out.println("返回的结果:"+result);
}
/**
* 根据提供的tags标签查询host。返回json串
* encodeTags 加密串需要解密之后再用
* @return
*/
//@RequestMapping("/testCmdbApi2")
//@ResponseBody
public void testCmdbApi2() {
try{
String appid = AESTool.SECRECTID;
String key = AESTool.findKeyById(appid);
Map<String ,Object> contentList=new HashMap<String,Object>();
contentList.put("cloudType","1,2");
contentList.put("tags",Arrays.asList(new String[]{"java"}));
String content = JSON.toJSONString(contentList);
content = AESTool.encrypt(content, key);
System.out.println("加密之后的内容:"+content);
String token = SignatureUtil.findTokenById(appid);
String lol = SignatureUtil.digest(content, "MD5");
long millis = System.currentTimeMillis();
String signature = SignatureUtil.generateSignature(appid, token, lol,
millis);
Map<String, String> paraMap = new HashMap<String, String>();
paraMap.put("s", signature);
paraMap.put("a", appid);
paraMap.put("t", String.valueOf(millis));
paraMap.put("l", lol);
String url="http://127.0.0.1:8080/cmdb/api2";
url=SignatureUtil.buildUri(url, paraMap);
System.out.println("新url:"+url);
String result = HttpClientUtil.doPost(url, content,null);
System.out.println("返回的密文:"+result);
System.out.println("解密:"+AESTool.decrypt(result,key));
}catch (Exception e){
//System.out.println("exception is happen",e);
}
}
}
... ...
package com.monitor.cmdb.util;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
/**
* Created by craig.qin on 2017/10/31.
*/
public class SignatureUtil {
private static Logger log = LoggerFactory.getLogger(SignatureUtil.class);
private static final char[] hexArray = "0123456789ABCDEF".toCharArray();
private static String encryptionAlgorithm = "SHA-1";
/**
* 根据传入的uri和参数map拼接成实际uri
*
* @param uri
* @param paraMap
* @return
*/
public static String buildUri(String uri, Map<String, String> paraMap) {
StringBuilder sb = new StringBuilder();
uri = StringUtils.trim(uri);
uri = StringUtils.removeEnd(uri, "/");
uri = StringUtils.removeEnd(uri, "?");
sb.append(uri);
if (paraMap != null && !paraMap.isEmpty()) {
sb.append("?");
Iterator<Map.Entry<String, String>> iterator = paraMap.entrySet()
.iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> pair = iterator.next();
try {
String keyString = pair.getKey();
String valueString = pair.getValue();
sb.append(keyString);
sb.append("=");
sb.append(valueString);
sb.append("&");
} catch (Exception e) {
log.error("error", e);
}
}
}
return StringUtils.removeEnd(sb.toString(), "&");
}
public static String bytesToHexString(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
/* public static byte[] hexStringToBytes(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character
.digit(s.charAt(i + 1), 16));
}
return data;
}*/
/**
* 使用指定算法生成消息摘要,默认是md5
*
* @param strSrc
* , a string will be encrypted; <br/>
* @param encName
* , the algorithm name will be used, dafault to "MD5"; <br/>
* @return
*/
public static String digest(String strSrc, String encName) {
MessageDigest md = null;
String strDes = null;
byte[] bt = strSrc.getBytes();
try {
if (encName == null || encName.equals("")) {
encName = "MD5";
}
md = MessageDigest.getInstance(encName);
md.update(bt);
strDes = bytesToHexString(md.digest()); // to HexString
} catch (NoSuchAlgorithmException e) {
log.error("Invalid algorithm: " + encName);
return null;
}
return strDes;
}
/**
* 根据appid、token、lol以及时间戳来生成签名
*
* @param appid
* @param token
* @param lol
* @param millis
* @return
*/
public static String generateSignature(String appid, String token, String lol,
long millis) {
String timestamp = String.valueOf(millis);
String signature = null;
if (StringUtils.isNotBlank(token) && StringUtils.isNotBlank(timestamp)
&& StringUtils.isNotBlank(appid)) {
List<String> srcList = new ArrayList<String>();
srcList.add(timestamp);
srcList.add(appid);
srcList.add(token);
srcList.add(lol);
// 按照字典序逆序拼接参数
Collections.sort(srcList);
Collections.reverse(srcList);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < srcList.size(); i++) {
sb.append(srcList.get(i));
}
signature = digest(sb.toString(), encryptionAlgorithm);
srcList.clear();
}
return signature;
}
/**
* 验证签名: <br/>
* 1.根据appid获取该渠道的token;<br/>
* 2.根据appid、token、lol以及时间戳计算一次签名;<br/>
* 3.比较传过来的签名以及计算出的签名是否一致;
* @param signature
* @param appid
* @param lol
* @param millis
* @return
*/
public static boolean isValid(String signature, String appid, String lol,
long millis) {
String token = findTokenById(appid);
String calculatedSignature = generateSignature(appid, token, lol,
millis);
log.info("calculated signature: \n" + calculatedSignature);
if (StringUtils.equals(calculatedSignature, signature)) {
return true;
} else {
return false;
}
}
/**
*
* @param appid
* @return
*/
public static String findTokenById(String appid) {
String token = "";
switch (appid){
case AESTool.SECRECTID:
token = "#@!1234567890!@#";
break;
}
return token;
}
public static void main(String[] args) {
SignatureUtil generator = new SignatureUtil();
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>";
System.out.println(xmlString.getBytes().length);
String digest = generator.digest(xmlString, "MD5");
System.out.println(digest);
System.out.println(digest.getBytes().length);
String appid = "canairport001";
String token = generator.findTokenById(appid);
long millis = System.currentTimeMillis();
String signature = generator.generateSignature(appid, token, digest,
millis);
System.out.println(signature);
boolean isValid = generator.isValid(signature, appid, digest, millis);
System.out.println(isValid);
}
}
... ...
package com.yoho.ops.cmdb.models;
import lombok.Data;
/**
* Created by craig.qin on 2017/10/31.
*/
@Data
public class CmdbApiReq {
//来源ip
private String sourceIp;
//生成的签名
private String signature ;
//分配的应用id或者secrectid
private String appid ;
//生成前面时的时间戳
private String timestamp ;
//签名摘要
private String lol;
//加密后的内容
private String content;
}
... ...
... ... @@ -90,8 +90,8 @@ public interface StaticVar {
String PLATFORM_SERVICE = "platform.addSort";
String RESOURCES_SERVICE = "resources.getCategory";
//String RESOURCES_SERVICE = "resources.getCategory";
String RESOURCES_SERVICE ="resources.queryProductBanner";
String SNS_SERVICE = "sns.getList";
String USERS_SERVICE = "users.bind";
... ...
... ... @@ -98,7 +98,7 @@ public class QcloudBandwidthTask {
}
bandwidthMapper.insert(intraffic,outtraffic);
logger.info("QcloudBandwidthTask over ");
if (intraffic > 200000 || outtraffic > 200000){
if (intraffic > 100 || outtraffic > 100){
alarmMsgService.sendSms("bandwidth", "专线带宽使用过多,请查看" , snsMobileConfig.getBaseMobile());
}
} catch (Exception e) {
... ...
... ... @@ -27,6 +27,8 @@ public interface HostInfoMapper {
List<HostInfo> selectHostInfosByTagList(@Param("tagsList") List<String> tagList);
List<HostInfo> selectHostInfosByTagListAndCloudTypeList(@Param("tagsList") List<String> tagList,@Param("cloudTypeList") List<Integer> cloudTypeList );
List<HostInfo> selectHostInfosByTagAndCloudType(@Param("tag") String tag,@Param("cloudType") int cloudType);
HostInfo selectByHostIp(@Param("hostIp") String hostIp);
... ...
... ... @@ -202,6 +202,27 @@
</if>
</select>
<select id="selectHostInfosByTagListAndCloudTypeList" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from host_info
where 1=1
<if test="tagsList != null &amp;&amp; tagsList.size > 0" >
and
<foreach open="(" close=")" item="item" index="index" collection="tagsList" separator="and">
instr(tags, #{item}) &gt; 0
</foreach>
</if>
<if test="cloudTypeList != null &amp;&amp; cloudTypeList.size > 0" >
and
<foreach open="(" close=")" item="item" index="index" collection="cloudTypeList" separator="or">
cloud_type = #{item}
</foreach>
</if>
</select>
<select id="selectHostInfosByTagAndCloudType" resultMap="BaseResultMap" >
select
<include refid="Base_Column_List" />
... ...