OuterIntfCtrl.java 9.3 KB
package com.ui.ctrl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Sets;
import com.ui.http.HttpRestClient;
import com.ui.model.BaseResponse;
import com.ui.model.MonitAlarmInfo;
import com.ui.model.WebHooksReleaseBO;
import com.ui.model.alarm.CommonAlarmData;
import com.ui.model.alarm.CommonData;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

/**
 * 
 * @author yoho
 * 对外提供接口
 *
 */
@Controller
@RequestMapping("/outer")
public class OuterIntfCtrl {

	Logger log = LoggerFactory.getLogger(OuterIntfCtrl.class);
	
	@Autowired
    private HttpRestClient httpClient;

	/**
	 * 对外接口,通用指标上报
	 */
	@RequestMapping("/commonAlarmDataUpLoad")
	@ResponseBody
	public void commonAlarmDataUpLoad(@RequestBody CommonData<CommonAlarmData> data){
		httpClient.defaultPost("/commonAlarmData/upLoadData",data,BaseResponse.class);
		//System.out.println(baseResponse);
	}


	/**
	 * 对外接口,提供报警
	 * @param info
	 * @return
	 */
	@RequestMapping("/recvMonitAlarm")
	@ResponseBody
	public BaseResponse recvMonitAlarm(@RequestBody MonitAlarmInfo info){
		BaseResponse response=httpClient.defaultPost("/recvMonitAlarm",info,BaseResponse.class);
		return response;
	}

	@RequestMapping("/maliciousIpAlarm")
	@ResponseBody
	public void maliciousIpAlarm(String info) {
		httpClient.defaultGet("/maliciousIpAlarm?info="+info,BaseResponse.class);
	}

	/**
	 * 对外接口,提供报警
	 * @param info   短信内容
	 * @param mobiles  手机号码,多个号码以逗号分隔
	 * 举例
	 *                 http://www.yohops.com/outer/recvMonitAlarmInfo?info=短信内容&mobiles=15699999,18988888
	 */
	@RequestMapping("/recvMonitAlarmInfo")
	@ResponseBody
	public BaseResponse recvMonitAlarmInfo(String info,String mobiles,String type){
		Map<String,String> map=new HashMap<>();
		if(info==null){
			info="";
		}
		map.put("info",info);
		if(mobiles==null){
			mobiles="";
		}
		map.put("mobiles",mobiles);
		if(type==null){
			type="";
		}
		map.put("type",type);
		BaseResponse response=httpClient.defaultGet("/recvMonitAlarmInfo",BaseResponse.class,map);
		return response;
	}

	/**
	 * 捕获的恶意ip写入运维系统的redis
	 * 自动封杀和告警提示
	 * @return
	 */
	@RequestMapping("/writeMipsObjToOpsReids")
	@ResponseBody
	public void writeMipsObjToOpsReids(@RequestBody String ipsObjs) {
		httpClient.defaultPostJson("/maliciousIp/writeMipsObjToOpsReids",ipsObjs,String.class);
	}

	/**
	 * 捕获的恶意ip写入运维系统的mysql
	 * 大数据算法
	 * @return
	 */
	@RequestMapping("/writeMipsInfoToOpsDb")
	@ResponseBody
	public void writeMipsInfoToOpsDb(@RequestBody String ipsObjs) {
		httpClient.defaultPostJson("/maliciousIp/writeMipsInfoToOpsDb",ipsObjs,String.class);
	}

	@RequestMapping("/getHostIpByTags")
	@ResponseBody
	public String getHostIpByTags(String tags) {
		List<String> ips= httpClient.defaultPost("/hostInfo/getHostIpByTags?tags="+tags,null,List.class);
		return JSON.toJSONString(ips);
	}

	/**********************************************************************
	 * dock项目
	 *********************************************************************/
	/**
	 * 发布工单_jenkins:更新镜像的状态
	 */
	@RequestMapping("/updateJenkinsStatus")
	@ResponseBody
	public BaseResponse updateJenkinsStatus(String ticketID,String jobID,String status) {
		Map<String,String> map=new HashMap<>();
		map.put("ticketID",ticketID);
		map.put("jobID",jobID);
		map.put("status",status);
		return httpClient.defaultGet("/dockerProject/updateJenkinsStatus",BaseResponse.class,map);
	}

	/**
	 * docker自动发布的回调
	 */
	@RequestMapping("/gitWebHook")
	@ResponseBody
	public BaseResponse gitWebHook(@RequestBody com.alibaba.fastjson.JSONObject jsonObject) throws Exception {
		log.info("gitWebHookAppCollectLog get the webhook from git begin --{}", jsonObject.toJSONString());
		WebHooksReleaseBO bo=releaseWebHooksNoCommits(jsonObject);
		return httpClient.defaultPost("/dockerProject/gitWebHook",bo,BaseResponse.class);
	}

	private WebHooksReleaseBO releaseWebHooksNoCommits(JSONObject jsonObject) {
		WebHooksReleaseBO webHooksReleaseBO = new WebHooksReleaseBO();
		String object_kind = jsonObject.getString("object_kind");
		String ref = jsonObject.getString("ref");
		String userName = jsonObject.getString("user_name");
		String userEmail = jsonObject.getString("user_email");
		Integer total_commits_count = jsonObject.getInteger("total_commits_count");
		String projectName = jsonObject.getJSONObject("project").getString("name");
		String projectNameSpace = jsonObject.getJSONObject("project").getString("namespace");
		String gitUrl = jsonObject.getJSONObject("project").getString("ssh_url");
		Set<String> list = Sets.newHashSet();
		JSONArray jsonArrays = jsonObject.getJSONArray("commits");
		Iterator<Object> it = jsonArrays.iterator();
		while (it.hasNext()) {
			JSONObject ob = (JSONObject) it.next();
			JSONArray jsonArrayAdded = ob.getJSONArray("added");
			JSONArray jsonArrayModified = ob.getJSONArray("modified");
			JSONArray jsonArrayRemoved = ob.getJSONArray("removed");
			addChange(jsonArrayAdded, list);
			addChange(jsonArrayModified, list);
			addChange(jsonArrayRemoved, list);
		}
		webHooksReleaseBO.setChangFileForDockerFile(list);
		webHooksReleaseBO.setObject_kind(object_kind);
		webHooksReleaseBO.setRef(ref);
		webHooksReleaseBO.setTotal_commits_count(total_commits_count);
		webHooksReleaseBO.setProjectName(projectName);
		webHooksReleaseBO.setProjectNameSpace(projectNameSpace);
		webHooksReleaseBO.setGitUrl(gitUrl);
		webHooksReleaseBO.setUser_name(userName);
		webHooksReleaseBO.setUser_email(userEmail);
		return webHooksReleaseBO;
	}

	private void addChange(JSONArray jsonArray, Set<String> list) {
		if (Objects.nonNull(jsonArray) && jsonArray.size() > NumberUtils.INTEGER_ZERO) {
			for (int i = 0; i < jsonArray.size(); i++) {
				String newAdd = jsonArray.get(i).toString();
				if (StringUtils.isNotBlank(newAdd)) {
					list.add(newAdd);
				}
			}
		}
	}


	/**
	 *
	 *   Grafana alert webhook. refer to:http://docs.grafana.org/alerting/notifications/
	 *
	 *   <pre>
	 *
	 *       {
	 "title": "My alert",
	 "ruleId": 1,
	 "ruleName": "Load peaking!",
	 "ruleUrl": "http://url.to.grafana/db/dashboard/my_dashboard?panelId=2",
	 "state": "alerting",
	 "imageUrl": "http://s3.image.url",
	 "message": "Load is peaking. Make sure the traffic is real and spin up more webfronts",
	 "evalMatches": [
	 {
	 "metric": "requests",
	 "tags": {},
	 "value": 122
	 }
	 ]
	 }
	 *   </pre>
	 *
	 * Created by chunhua.zhang on 2017/5/26.
	 */
	/**
	 * 接口:grafana报警提示
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/grafanaWebHook")
	@ResponseBody
	public BaseResponse  grafanaWebHook(HttpServletRequest request) {
		try {
			String jsonBody = IOUtils.toString(request.getInputStream(),"utf-8");
			log.info("receive grafana webhook message:{}", jsonBody);
			JSONObject alert = (JSONObject) JSON.parse(jsonBody);
			String title = "";
			String state = "";
			String imgUrl = "";
			String message = "";
			if(alert!=null){
				 title = alert.getString("title");
				 state = alert.getString("state");
				 imgUrl = alert.get("imageUrl")==null?"":alert.getString("imageUrl");
				 message = alert.get("message")==null?"":alert.getString("message");
			}

			Map<String, String> map=new HashMap<>();
			map.put("title",title);
			map.put("state",state);
			map.put("imgUrl",imgUrl);
			map.put("message",message);
			return httpClient.defaultGet("/grafanaAlert/sendDing",BaseResponse.class,map);
		} catch (IOException e) {
			e.printStackTrace();
		}

		return new BaseResponse(201);
	}

	/***
	 * DNS 更新接口
	 */
	@RequestMapping("/dnsJustForShell")
	@ResponseBody
	public String dnsJustForShell(String domain, String cloud, String type, String operate, String record, String value) {
		if (StringUtils.isBlank(domain) || StringUtils.isBlank(cloud) || StringUtils.isBlank(operate)) {
			return "param error";
		}
		Map<String, String> map=new HashMap<>();
		map.put("domain",domain);
		map.put("cloud",cloud);
		map.put("operate",operate);

		map.put("record",StringUtils.isBlank(record)?"":record);
		map.put("type",StringUtils.isBlank(type)?"":type);
		map.put("value",StringUtils.isBlank(value)?"":value);
		return httpClient.defaultGet("/internalDns/justForShell",String.class,map);
	}

	@RequestMapping("/dnsJustForShellUpdate")
	@ResponseBody
	public String dnsJustForShellUpdate( String cloud,  String record, String value) {
		String domain="yohoops.org";
		String operate="update";
		String type="";
		return this.dnsJustForShell(domain,cloud,type,operate,record,value);
	}

	@RequestMapping("/dnsJustForShellCommit")
	@ResponseBody
	public String dnsJustForShellCommit( String cloud) {
		String domain="yohoops.org";
		String operate="commit";
		return this.dnsJustForShell(domain,cloud,"",operate,"","");
	}


}