Browse Source

1.日志增加tenant
2.修复服务监控无法显示问题。

airhead 7 years ago
parent
commit
97ef8c9e81

+ 4 - 14
hos-broker/src/main/java/com/yihu/hos/broker/models/LogOffset.java

@ -14,11 +14,9 @@ import java.util.Date;
public class LogOffset {
    @Id
    private String id;
    @Indexed
    private String tenant;
    @Indexed
    @Indexed(unique = true)
    private String name;    //需要采集的目标
    private Date offset;
    private long offset;
    private Date createTime;
    public String getId() {
@ -29,14 +27,6 @@ public class LogOffset {
        this.id = id;
    }
    public String getTenant() {
        return tenant;
    }
    public void setTenant(String tenant) {
        this.tenant = tenant;
    }
    public String getName() {
        return name;
    }
@ -45,11 +35,11 @@ public class LogOffset {
        this.name = name;
    }
    public Date getOffset() {
    public long getOffset() {
        return offset;
    }
    public void setOffset(Date offset) {
    public void setOffset(long offset) {
        this.offset = offset;
    }

+ 18 - 8
hos-broker/src/main/java/com/yihu/hos/broker/services/ServiceMonitorService.java

@ -7,6 +7,7 @@ import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.UpdateOptions;
import com.yihu.hos.broker.common.constants.MonitorConstant;
import com.yihu.hos.broker.models.LogOffset;
import com.yihu.hos.core.datatype.DateUtil;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
@ -44,10 +45,13 @@ public class ServiceMonitorService {
            Date begin = new Date();
            Date end = new Date();
            if (offset != null) {
                begin = offset.getOffset();
                long lngOffset = offset.getOffset();
                begin = DateUtil.toDateFromTime(lngOffset);
            }
            DateFormat df = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss z", Locale.ENGLISH);
            begin = DateUtil.formatCharDateYMDHMS("2017-06-12 00:00:00");
            end = DateUtil.formatCharDateYMDHMS("2017-06-20 00:00:00");
            String beginTime = df.format(begin);
            String endTime = df.format(end);
@ -55,7 +59,11 @@ public class ServiceMonitorService {
            AggregateIterable<Document> documents = aggregate(database, beginTime, endTime);
            outPut(database, documents);
            offset.setOffset(end);
            if (offset == null) {
                offset = new LogOffset();
                offset.setName(MonitorConstant.SERVICE);
            }
            offset.setOffset(end.getTime());
            mongoOperations.save(offset);
        } catch (Exception e) {
            e.printStackTrace();
@ -65,13 +73,13 @@ public class ServiceMonitorService {
    private void mapReduce(MongoDatabase database, String beginTime, String endTime) {
        Document document = new Document("mapReduce", MonitorConstant.BUSINESS);
        String mapFunc = "function(){emit(this.breadcrumbId, {fireTime:this.fireTime, createTime:this.createTime, routeId:this.routeId, bodyLength:this.bodyLength, tenant:this.tenant});}";
        String mapFunc = "function(){emit(this.breadcrumbId, {fireTime:this.fireTime, createTime:this.createTime, bodyLength:this.bodyLength, tenant:this.tenant, routeId:this.routeId});}";
        document = document.append("map", mapFunc);
        String reduceFunc = "function(key, values){" +
                "var len=values.length;" +
                "var delay=values[len-1].fireTime-values[0].fireTime;" +
                "if(len == 1){delay=values[0].createTime-values[0].fireTime;}" +
                "return {fireTime: values[0].fireTime, in:values[0].bodyLength, out:values[len-1].bodyLength, delay:delay, tenant:values[0].tenant}}";
                "return {fireTime: values[0].fireTime, in:values[0].bodyLength, out:values[len-1].bodyLength, delay:delay, tenant:values[0].tenant, routeId:values[0].routeId}}";
        document = document.append("reduce", reduceFunc);
        String query = "{fireTime:{$gte:new Date(\"" + beginTime + "\"), $lt:new Date(\"" + endTime + "\")}}";
        document = document.append("query", Document.parse(query));
@ -95,10 +103,12 @@ public class ServiceMonitorService {
                "day:{\"$dayOfMonth\":\"$value.fireTime\"}," +
                "hour:{\"$hour\":\"$value.fireTime\"}," +
                "minute:{\"$minute\": \"$value.fireTime\"}" +
                "routId:\"$value.routeId\"" +
                "routeId:\"$value.routeId\"" +
                "tenant:\"$value.tenantId\"" +
                "}"));
        group.append("pv", Document.parse("{$sum:1}"));
        group.append("successful", Document.parse("{$sum:1}"));
        group.append("failure", Document.parse("{$sum:0}"));    //TODO:暂时为空
        group.append("delay", Document.parse("{$sum:\"$value.delay\"}"));
        group.append("avgDelay", Document.parse("{$avg:\"$value.delay\"}"));
        group.append("in", Document.parse("{$sum:\"$value.in\"}"));
@ -114,10 +124,10 @@ public class ServiceMonitorService {
        MongoCollection<Document> serviceMetrics = database.getCollection(MonitorConstant.SERVICE_METRICS);
        for (Document document : documents) {
            Document id = (Document) document.get("_id");
            String time = id.get("year").toString() + id.get("month").toString() + id.get("day").toString() +
                    id.get("hour").toString() + id.get("minute").toString();
            String time = String.format("%04d", (int) id.get("year")) + String.format("%02d", (int) id.get("month")) + String.format("%02d", (int) id.get("day")) +
                    String.format("%02d", (int) id.get("hour")) + String.format("%02d", (int) id.get("minute"));
            document.put("time", time);
            document.put("routId", id.get("routeId"));
            document.put("routeId", id.get("routeId"));
            document.put("tenant", id.get("tenant"));
            document.putIfAbsent("avgDelay", 0);

+ 4 - 0
hos-camel2/pom.xml

@ -76,6 +76,10 @@
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-quartz</artifactId>
        </dependency>
        <dependency>
            <groupId>net.sf.json-lib</groupId>

+ 7 - 0
hos-logger/src/main/java/com/yihu/hos/logger/configuration/LoggerConfiguration.java

@ -20,6 +20,9 @@ public class LoggerConfiguration {
    @Value("${logger.ehr}")
    private String ehrLogDir;
    @Value("${logger.tenant}")
    private String tenant;
    public String getBrokerURL() {
        return brokerURL;
    }
@ -35,4 +38,8 @@ public class LoggerConfiguration {
    public String getEhrLogDir() {
        return ehrLogDir;
    }
    public String getTenant() {
        return tenant;
    }
}

+ 13 - 0
hos-logger/src/main/java/com/yihu/hos/logger/model/HosLog.java

@ -32,6 +32,7 @@ public class HosLog {
    private String fireTimeSource;
    private Date updateTime;
    private Date createTime;
    private String tenant;
    public HosLog() {
        this.createTime = DateUtil.getSysDateTime();
@ -176,4 +177,16 @@ public class HosLog {
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
    public String getMessageId() {
        return messageId;
    }
    public String getTenant() {
        return tenant;
    }
    public void setTenant(String tenant) {
        this.tenant = tenant;
    }
}

+ 5 - 3
hos-logger/src/main/java/com/yihu/hos/logger/service/HosLogService.java

@ -1,8 +1,7 @@
package com.yihu.hos.logger.service;
import ch.qos.logback.classic.spi.ILoggingEvent;
import com.yihu.hos.core.log.Logger;
import com.yihu.hos.core.log.LoggerFactory;
import com.yihu.hos.logger.configuration.LoggerConfiguration;
import com.yihu.hos.logger.model.HosLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
@ -16,10 +15,12 @@ import java.util.Map;
 */
@Component("businessLogService")
public class HosLogService {
    private static final Logger logger = LoggerFactory.getLogger(HosLogService.class);
    @Autowired
    private MongoOperations mongoOperations;
    @Autowired
    private LoggerConfiguration loggerConfiguration;
    /**
     * camel.exchangeId The exchange id
     * camel.messageId The message id
@ -47,6 +48,7 @@ public class HosLogService {
        hosLog.setCamelContextId(mdcPropertyMap.get("camel.contextId"));
        hosLog.setBody(event.getMessage());
        hosLog.setBodyLength(event.getMessage().length());
        hosLog.setTenant(loggerConfiguration.getTenant());
        mongoOperations.save(hosLog);
    }

+ 1 - 0
hos-logger/src/main/resources/application.yml

@ -30,4 +30,5 @@ spring:
      gridFsDatabase: dfs
logger:
  tenant: jkzl
  ehr: e:/file

+ 23 - 14
src/main/java/com/yihu/hos/monitor/controller/ServiceMonitorController.java

@ -1,10 +1,15 @@
package com.yihu.hos.monitor.controller;
import com.yihu.hos.common.constants.ContextAttributes;
import com.yihu.hos.monitor.service.ServiceMonitorService;
import com.yihu.hos.system.service.FlowManager;
import com.yihu.hos.tenant.model.TenantSession;
import com.yihu.hos.web.framework.model.Result;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@ -24,8 +29,9 @@ import javax.servlet.http.HttpSession;
@Controller("ServiceMonitorController")
@RequestMapping("/monitor/service")
public class ServiceMonitorController {
    private static Logger logger = LoggerFactory.getLogger(ServiceMonitorController.class);
    @Resource(name = ServiceMonitorService.BEAN_ID)
    @Autowired
    private ServiceMonitorService monitorService;
    @Resource(name = FlowManager.BEAN_ID)
@ -52,8 +58,10 @@ public class ServiceMonitorController {
            @RequestParam(value = "endTime") String endTime) {
        try {
            HttpSession session = request.getSession();
            return monitorService.metrics(session,id, beginTime, endTime);
            TenantSession tenantSession = (TenantSession) session.getAttribute(ContextAttributes.TENANT_SESSION);
            return monitorService.serviceMetrics(tenantSession.getTenant(), id, beginTime, endTime);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return Result.error("获取服务指标失败");
        }
    }
@ -65,6 +73,7 @@ public class ServiceMonitorController {
        try {
            return monitorService.getServiceTreeList();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取服务树列表失败");
        }
    }
@ -76,12 +85,12 @@ public class ServiceMonitorController {
    public Result serviceStatus(
            HttpServletRequest request,
            @ApiParam(name = "routeCode", value = "流程Code", required = true)
            @RequestParam(value = "routeCode") Integer routeCode ) {
            @RequestParam(value = "routeCode") Integer routeCode) {
        try {
            boolean succ = flowManager.serviceOpenOrPause(routeCode,0);
            if (succ){
            boolean succ = flowManager.serviceOpenOrPause(routeCode, 0);
            if (succ) {
                return Result.success("获取服务状态成功");
            }else {
            } else {
                return Result.error("获取服务状态失败");
            }
        } catch (Exception e) {
@ -96,12 +105,12 @@ public class ServiceMonitorController {
    public Result startService(
            HttpServletRequest request,
            @ApiParam(name = "flowId", value = "流程ID", required = true)
            @RequestParam(value = "flowId") Integer flowId ) {
            @RequestParam(value = "flowId") Integer flowId) {
        try {
            boolean succ = flowManager.serviceOpenOrPause(flowId,1);
            if (succ){
            boolean succ = flowManager.serviceOpenOrPause(flowId, 1);
            if (succ) {
                return Result.success("开启服务成功");
            }else {
            } else {
                return Result.error("开启服务失败");
            }
        } catch (Exception e) {
@ -115,12 +124,12 @@ public class ServiceMonitorController {
    public Result stopService(
            HttpServletRequest request,
            @ApiParam(name = "flowId", value = "流程ID", required = true)
            @RequestParam(value = "flowId") Integer flowId ) {
            @RequestParam(value = "flowId") Integer flowId) {
        try {
            boolean succ = flowManager.serviceOpenOrPause(flowId,0);
            if (succ){
            boolean succ = flowManager.serviceOpenOrPause(flowId, 0);
            if (succ) {
                return Result.success("暂停服务成功");
            }else {
            } else {
                return Result.error("暂停服务失败");
            }
        } catch (Exception e) {

+ 1 - 1
src/main/java/com/yihu/hos/monitor/dao/ServiceMonitorDao.java

@ -36,7 +36,7 @@ public class ServiceMonitorDao extends SQLGeneralDAO {
    }
    public List<SystemServiceFlow> getFlowsByType(String type) throws Exception {
        return (List<SystemServiceFlow>) super.hibernateTemplate.find("from SystemServiceFlow s where s.type=?",type);
        return (List<SystemServiceFlow>) super.hibernateTemplate.find("from SystemServiceFlow s where s.fileType=?",type);
    }
}

+ 19 - 104
src/main/java/com/yihu/hos/monitor/service/ServiceMonitorService.java

@ -1,116 +1,62 @@
package com.yihu.hos.monitor.service;
import com.mongodb.*;
import com.yihu.hos.common.constants.ContextAttributes;
import com.yihu.hos.core.datatype.CollectionUtil;
import com.yihu.hos.monitor.dao.ServiceMonitorDao;
import com.yihu.hos.system.model.SystemServiceEndpoint;
import com.yihu.hos.system.model.SystemServiceFlow;
import com.yihu.hos.system.model.SystemServiceFlowConfig;
import com.yihu.hos.tenant.model.TenantSession;
import com.yihu.hos.web.framework.constant.ServiceFlowConstant;
import com.yihu.hos.web.framework.model.Result;
import com.yihu.hos.web.framework.model.TreeView;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * Created by chenweida on 2016/1/27.
 */
@Service("ServiceMonitorService")
@Service
public class ServiceMonitorService {
    public static final String BEAN_ID = "ServiceMonitorService";
    public static final String dbName = "log";
    public static final String tableName = "service";
    public static final String serviceFlow = "serviceFlow";
    public static final String tableName = "serviceMetrics";
    public static final String configuration = "configuration";
    @Autowired
    private MongoOperations mongoOperations;
    @Autowired
    private Mongo mongo;
    private MongoClient mongoClient;
    @Autowired
    private ServiceMonitorDao serviceMonitorDao;
//    @Resource(name = FlowManager.BEAN_ID)
//    private FlowManager flowManager;
    public Result metrics(HttpSession session, String id, String beginTime, String endTime) throws Exception {
        String name;
        String code;
        String description;
        TenantSession tenantSession = (TenantSession) session.getAttribute(ContextAttributes.TENANT_SESSION);
        if (id.contains("flow")) {
            Integer flowId = Integer.parseInt(id.replace("flow", ""));
            SystemServiceFlow systemServiceFlow = serviceMonitorDao.getFlowById(flowId);
            name = systemServiceFlow.getName();
            code = systemServiceFlow.getCode();
            description = systemServiceFlow.getDescription();
        } else {
            String endpointId = id.replace("endpoint", "");
            SystemServiceEndpoint systemServiceEndpoint = serviceMonitorDao.getEndpointById(endpointId);
            name = systemServiceEndpoint.getName();
            code = systemServiceEndpoint.getCode();
            description = systemServiceEndpoint.getDescription();
        }
        JSONObject serviceInfo = new JSONObject();
        serviceInfo.put("name", name);
        serviceInfo.put("description", description);
        mongoOperations = new MongoTemplate(mongo, dbName);
    public Result serviceMetrics(String tenant, String routeId, String beginTime, String endTime) throws Exception {
        MongoTemplate mongoOperations = new MongoTemplate(mongoClient, dbName);
        DBCollection metrics = mongoOperations.getCollection(tableName);
        BasicDBObject queryObject = new BasicDBObject().append(QueryOperators.AND,
                new BasicDBObject[]{
                        new BasicDBObject().append("create_time",
                                new BasicDBObject().append(QueryOperators.GTE, beginTime)),
                        new BasicDBObject().append("create_time",
                                new BasicDBObject().append(QueryOperators.LT, endTime)),
                        new BasicDBObject("name", code),
                        new BasicDBObject("tenant", tenantSession.getTenant())});
                        new BasicDBObject().append("time", new BasicDBObject().append(QueryOperators.GTE, beginTime)),
                        new BasicDBObject().append("time", new BasicDBObject().append(QueryOperators.LT, endTime))
//                        new BasicDBObject().append("time", new BasicDBObject().append(QueryOperators.GTE, "201706120000")),
//                        new BasicDBObject().append("time", new BasicDBObject().append(QueryOperators.LT, "201706200000"))
                        , new BasicDBObject("routeId", routeId)
                        , new BasicDBObject("tenant", tenant)
                });
        JSONObject result = new JSONObject();
        DBCursor cursor = metrics.find(queryObject);
        JSONArray bandwidth = new JSONArray();
        JSONArray qps = new JSONArray();
        JSONArray usage = new JSONArray();
        JSONArray delay = new JSONArray();
        JSONArray data = new JSONArray();
        while (cursor.hasNext()) {
            DBObject dbObject = cursor.next();
            dbObject.removeField("_id");
            String type = dbObject.get("type").toString();
            switch (type) {
                case "bandwidth":
                    bandwidth.put(dbObject);
                    break;
                case "qps":
                    qps.put(dbObject);
                    break;
                case "usage":
                    usage.put(dbObject);
                    break;
                case "delay":
                    delay.put(dbObject);
                    break;
            }
            data.put(dbObject);
        }
        result.put("bandwidth", bandwidth);
        result.put("qps", qps);
        result.put("usage", usage);
        result.put("delay", delay);
        result.put("serviceInfo", serviceInfo);
        result.put("data", data);
        return Result.success(result.toString());
    }
@ -118,25 +64,6 @@ public class ServiceMonitorService {
        List<TreeView> treeList = new ArrayList<>();
        List<SystemServiceFlow> flowList = serviceMonitorDao.getFlowsByType(ServiceFlowConstant.CLASS);
        List<SystemServiceFlowConfig> flowEndpointList = serviceMonitorDao.getAllFlowEndpoints();
        List<SystemServiceEndpoint> endpointList = serviceMonitorDao.getAllEndpoints();
        Map<Integer, List<String>> flowEndpointMap = new HashMap<>();
        Map<String, SystemServiceEndpoint> endpointMap = new HashMap<>();
        for (SystemServiceFlowConfig systemServiceFlowConfig : flowEndpointList) {
            List<String> endpointIdList;
            if (flowEndpointMap.containsKey(systemServiceFlowConfig.getFlowId())) {
                endpointIdList = flowEndpointMap.get(systemServiceFlowConfig.getFlowId());
            } else {
                endpointIdList = new ArrayList<>();
            }
            endpointIdList.add(systemServiceFlowConfig.getEndpointId());
            flowEndpointMap.put(systemServiceFlowConfig.getFlowId(), endpointIdList);
        }
        for (SystemServiceEndpoint endpoint : endpointList) {
            endpointMap.put(endpoint.getId(), endpoint);
        }
        for (SystemServiceFlow flow : flowList) {
            TreeView rootTree = new TreeView();
@ -145,21 +72,9 @@ public class ServiceMonitorService {
            rootTree.setPid("-1");
            rootTree.setText(flow.getName());
            treeList.add(rootTree);
            List<String> endpointIdList = flowEndpointMap.get(flow.getId());
            if (!CollectionUtil.isEmpty(endpointIdList)) {
                for (String endpointId : endpointIdList) {
                    SystemServiceEndpoint endpoint = endpointMap.get(endpointId);
                    TreeView childTree = new TreeView();
                    childTree.setIschecked(false);
                    childTree.setId("endpoint" + endpoint.getId());
                    childTree.setPid("flow" + flow.getId());
                    childTree.setText(endpoint.getName());
                    treeList.add(childTree);
                }
            }
        }
        JSONArray jsonArray = new JSONArray(treeList);
        JSONArray jsonArray = new JSONArray(treeList);
        return Result.success(jsonArray.toString());
    }

+ 1 - 2
src/main/webapp/WEB-INF/ehr/commons/jsp/commonFoot.jsp

@ -7,8 +7,7 @@
<script src="${staticRoot}/lib/ligerui/custom/ligerOverwrite.js"></script>
<script src="${staticRoot}/lib/ligerui/plugins/customTree.js"></script>
<script src="${staticRoot}/lib/bootstrap/js/bootstrap.min.js"></script>
<script src="${staticRoot}/lib/module/dateExt.js"></script>
<script src="${staticRoot}/lib/module/util.js"></script>
<script src="${staticRoot}/lib/plugin/formEx/attrscan.js"></script>
<script src="${staticRoot}/lib/plugin/formEx/readonly.js"></script>

+ 81 - 21
src/main/webapp/WEB-INF/ehr/jsp/monitor/service/sEnvManage.jsp

@ -4,27 +4,84 @@
<link rel="stylesheet" href="${contextRoot}/develop/lib/plugin/switchery/switchery.css">
<style>
    .c-item{float:left;height: 30px;line-height: 30px;width: 150px;background: #fff;color:#000;text-align: center;font-size: 12px;border:1px solid #dcdcdc;}
    .c-bor-r{border-right: 0;}
    .c-item.active{background: #16B3EE;color:#fff}
    .ml50{margin-left: 50px;}
    .mt20{margin-top: 20px;}
    .mb20{margin-bottom: 20px;}
    .f-dis-inline{display: inline-block;}
    .f-fs12{font-size: 12px;}
    .f-fs14{font-size: 14px;}
    .c-fwb{font-weight: bold;}
    .div-item{width:50%;float: left;}
    .c-item{font-size: 12px;display: inline-block;width: 100px;}
    .c-content{font-size: 16px;display: inline-block;width: 100px;font-weight: bold;}
    .div-right-item{font-size: 12px;width: 150px;}
    .c-item {
        float: left;
        height: 30px;
        line-height: 30px;
        width: 150px;
        background: #fff;
        color: #000;
        text-align: center;
        font-size: 12px;
        border: 1px solid #dcdcdc;
    }
    .c-bor-r {
        border-right: 0;
    }
    .c-item.active {
        background: #16B3EE;
        color: #fff
    }
    .ml50 {
        margin-left: 50px;
    }
    .mt20 {
        margin-top: 20px;
    }
    .mb20 {
        margin-bottom: 20px;
    }
    .f-dis-inline {
        display: inline-block;
    }
    .f-fs12 {
        font-size: 12px;
    }
    .f-fs14 {
        font-size: 14px;
    }
    .c-fwb {
        font-weight: bold;
    }
    .div-item {
        width: 50%;
        float: left;
    }
    .c-item {
        font-size: 12px;
        display: inline-block;
        width: 100px;
    }
    .c-content {
        font-size: 16px;
        display: inline-block;
        width: 100px;
        font-weight: bold;
    }
    .div-right-item {
        font-size: 12px;
        width: 150px;
    }
</style>
<!-- ####### 页面部分 ####### -->
<div id="div_wrapper">
    <!--左边 区域-->
    <div position="left"  style="margin-left:10px;margin-top:10px;border-right: thin solid rgb(162, 162, 162);">
    <div position="left" style="margin-left:10px;margin-top:10px;border-right: thin solid rgb(162, 162, 162);">
        <ul id="div_wrapper_left_ul_servicetree" class="m-snav"></ul>
    </div>
    <div position="center" style="margin-left:10px;margin-top:10px;margin-right:10px;">
@ -34,9 +91,10 @@
            <div class="m-form-group">
                <div class="col-sm-3" style="text-align: center;padding-top:10px;">
                    <div style="width:255px">
                        <input type="checkbox" class="js-switch" id="jobStatusSwitch" checked />
                        <input type="checkbox" class="js-switch" id="jobStatusSwitch" checked/>
                    </div>
                    <div style="float: left;width:235px;border-left:1px solid #e1e1e1;;line-height: 32px;" id="jobStatus">
                    <div style="float: left;width:235px;border-left:1px solid #e1e1e1;;line-height: 32px;"
                         id="jobStatus">
                        -
                    </div>
                    <div style="clear: both;padding-top:20px;">任务调度</div>
@ -52,11 +110,11 @@
            <div class="m-form-group" style="margin-left: 100px;">
                <label style="width: 100px;">开始时间:</label>
                <div class="m-form-control">
                    <input id="repeatStartTime" type="text" />
                    <input id="repeatStartTime" type="text"/>
                </div>
                <label style="width: 100px;">结束时间:</label>
                <div class="m-form-control">
                    <input id="repeatEndTime" type="text" />
                    <input id="repeatEndTime" type="text"/>
                </div>
                <div class="m-form-control">
                    <div id="btnSearch" class="l-button">
@ -67,11 +125,13 @@
            <%-- echarts 数据--%>
            <div id="main1" style="width: 500px;margin-left:130px;height:250px;border: solid deepskyblue 1px;"></div>
            <%-- echarts 数据--%>
            <div id="main2" style="width: 500px;margin:-250px 0px 20px 680px;height:250px;border: solid deepskyblue 1px;"></div>
            <div id="main2"
                 style="width: 500px;margin:-250px 0px 20px 680px;height:250px;border: solid deepskyblue 1px;"></div>
            <%-- echarts 数据--%>
            <div id="main3" style="width: 500px;margin-left:130px;height:250px;border: solid deepskyblue 1px;"></div>
            <%-- echarts 数据--%>
            <div id="main4" style="width: 500px;margin:-250px 0px 20px 680px;height:250px;border: solid deepskyblue 1px;"></div>
            <div id="main4"
                 style="width: 500px;margin:-250px 0px 20px 680px;height:250px;border: solid deepskyblue 1px;"></div>
        </div>
    </div>
</div>

+ 163 - 166
src/main/webapp/WEB-INF/ehr/jsp/monitor/service/sEnvManageJs.jsp

@ -25,59 +25,57 @@
            width: 240,
            showTime: true
        });
        $("#repeatStartTime").ligerDateEditor("setValue",prevDate());
        $("#repeatEndTime").ligerDateEditor("setValue",nowDate());
        $("#repeatStartTime").ligerDateEditor("setValue", prevDate());
        $("#repeatEndTime").ligerDateEditor("setValue", nowDate());
        /*初始化时间控件-end*/
        //搜索按钮事件
        $(".m-form-control").on("click","#btnSearch",function(){
        $(".m-form-control").on("click", "#btnSearch", function () {
            var beginTime = $("#repeatStartTime").ligerDateEditor("getValue");
            var endTime = $("#repeatEndTime").ligerDateEditor("getValue");
            if(beginTime=="" && $endTime=="")
            {
            if (beginTime == "" && $endTime == "") {
                $.ligerDialog.error("请选择起始结束时间!");
                return false;
            }
            if(beginTime > endTime)
            {
            if (beginTime > endTime) {
                $.ligerDialog.error("开始时间不能大于结束时间!");
                return false;
            }
            var id = $("#selectId").val();
            //获取服务器监控数据
            getServiceInfo(id,beginTime,endTime);
            getServiceInfo(id, beginTime, endTime);
        });
        //初始化树
        getServiceTree();
    });
    function initSwitcher(){
    function initSwitcher() {
        var me = this;
        //开关控件
        var changeCheckbox = document.querySelector('#jobStatusSwitch');
        var switchery = new Switchery(changeCheckbox, { disabled: true,size: 'large' });
        changeCheckbox.onchange = function() {
        var switchery = new Switchery(changeCheckbox, {disabled: true, size: 'large'});
        changeCheckbox.onchange = function () {
            //debugger
            var a = me.switchery;
            var jobId = $("#selJob").ligerComboBox("getValue");
            if(!changeCheckbox.checked)
            {
                me.valid(jobId,"0");
            if (!changeCheckbox.checked) {
                me.valid(jobId, "0");
            }
            else{
                me.valid(jobId,"1");
            else {
                me.valid(jobId, "1");
            }
        };
    }
    function getServiceTree(){
    function getServiceTree() {
        var serviceTree = $("#div_wrapper_left_ul_servicetree");
        //初始化树
        $.ajax({
            type: "GET",
            dataType: "json",
            url: "${contextRoot}/monitor/service/trees",
            success: function (msg) {
                if (msg.successFlg) {
@ -109,128 +107,134 @@
        });
    }
    function getServiceInfo(id, beginTime, endTime){
    function getServiceInfo(id, beginTime, endTime) {
        beginTime = new Date(beginTime).format("yyyyMMddhhmm");
        endTime = new Date(endTime).format("yyyyMMddhhmm");
        debugger
        $.ajax({
            type: "GET",
            url : "${contextRoot}/monitor/service/metrics",
            dataType : "json",
            data:{id:id,beginTime:beginTime, endTime:endTime},
            cache:false,
            success :function(re){
                if(re.successFlg) {
            url: "${contextRoot}/monitor/service/metrics",
            dataType: "json",
            data: {id: id, beginTime: beginTime, endTime: endTime},
            cache: false,
            success: function (re) {
                if (re.successFlg) {
                    //TODO 设置图表
                    var message = JSON.parse(re.message);
                    var serviceInfo = message.serviceInfo;
                    $("#serviceName").text(serviceInfo.name);
                    $("#serviceDescription").text(serviceInfo.description);
//                    var serviceInfo = message.serviceInfo;
//                    $("#serviceName").text(serviceInfo.name);
//                    $("#serviceDescription").text(serviceInfo.description);
                    service.bandwidth(message.bandwidth);
                    service.qps(message.qps);
                    service.delay(message.delay);
                    service.usage(message.usage);
                    service.bandwidth(message.data);
                    service.qps(message.data);
                    service.delay(message.data);
                    service.usage(message.data);
                    service.setJobStatus();
                } else {
                    $.ligerDialog.error(re.message);
                }
            },
            error :function(data){
                $.ligerDialog.error("Status:"+data.status +"(" +data.statusText+")");
            error: function (data) {
                $.ligerDialog.error("Status:" + data.status + "(" + data.statusText + ")");
            }
        });
    }
    var service = {
        switchery:null,
        bandwidth:function(data){
        switchery: null,
        bandwidth: function (data) {
            // 基于准备好的dom,初始化echarts实例
            var myChart = echarts.init(document.getElementById('main1'));
             if(data!=null && data.length>0)
             {
                 var x = [];
                 var y = [];
                 for(var i=0;i<data.length;i++)
                 {
                     var createTime = data[i].createTime.substring(11,16);
                     x.push(createTime);
                     y.push(data[i].value);
                 }
                 // 指定图表的配置项和数据
                 var option = {
                     title: {
                         text: ' 带宽',
                         left: 'center'
                     },
                     tooltip: {
                         trigger: 'axis'
                     },
                     dataZoom : {
                         show : true,
                         start : 50,
                         end : 100
                     },
                     legend: {
                         left: 'left',
                         data: ['带宽']
                     },
                     xAxis: {
                         type: 'category',
                         name: '时间',
                         splitLine: {show: false},
                         data: x
                     },
                     grid: {
                         left: '3%',
                         right: '4%',
                         bottom: '3%',
                         containLabel: true
                     },
                     yAxis: {
                         type: 'log',
                     },
                     series: [
                         {
                             name: '带宽',
                             type: 'line',
                             data: y
                         },
                     ]
                 };
             myChart.setOption(option);
             //设置图例下方的信息
             } else{
                 myChart.clear();
             }
            if (data != null && data.length > 0) {
                var x = [];
                var inPut = [];
                var outPut = [];
                for (var i = 0; i < data.length; i++) {
                    var createTime = data[i].time.substring(8, 12);
                    x.push(createTime);
                    inPut.push(data[i].in);
                    outPut.push(data[i].out);
                }
                // 指定图表的配置项和数据
                var option = {
                    title: {
                        text: ' 带宽',
                        left: 'center'
                    },
                    tooltip: {
                        trigger: 'axis'
                    },
                    dataZoom: {
                        show: true,
                        start: 50,
                        end: 100
                    },
                    legend: {
                        left: 'left',
                        data: ['输入', "输出"]
                    },
                    xAxis: {
                        type: 'category',
                        name: '时间',
                        splitLine: {show: false},
                        data: x
                    },
                    grid: {
                        left: '3%',
                        right: '4%',
                        bottom: '3%',
                        containLabel: true
                    },
                    yAxis: {
                        type: 'log',
                    },
                    series: [
                        {
                            name: '输入',
                            type: 'line',
                            data: inPut
                        },
                        {
                            name: '输出',
                            type: 'line',
                            data: outPut
                        },
                    ]
                };
                myChart.setOption(option);
                //设置图例下方的信息
            } else {
                myChart.clear();
            }
        },
        qps:function(data){
        qps: function (data) {
            // 基于准备好的dom,初始化echarts实例
            var myChart = echarts.init(document.getElementById('main2'));
            if(data!=null && data.length>0)
            {
            if (data != null && data.length > 0) {
                var x = [];
                var y = [];
                for(var i=0;i<data.length;i++)
                {
                    var createTime = data[i].createTime.substring(11,16);
                for (var i = 0; i < data.length; i++) {
                    var createTime = data[i].time.substring(8, 12);
                    x.push(createTime);
                    y.push(data[i].value);
                    y.push(data[i].pv);
                }
                // 指定图表的配置项和数据
                var option = {
                    title: {
                        text: ' 吞吐量',
                        text: ' TPS',
                        left: 'center'
                    },
                    tooltip: {
                        trigger: 'axis'
                    },
                    dataZoom : {
                        show : true,
                        start : 50,
                        end : 100
                    dataZoom: {
                        show: true,
                        start: 50,
                        end: 100
                    },
                    legend: {
                        left: 'left',
                        data: ['吞吐量']
                        data: ['TPS']
                    },
                    xAxis: {
                        type: 'category',
@ -249,7 +253,7 @@
                    },
                    series: [
                        {
                            name: '吞吐量',
                            name: 'TPS',
                            type: 'line',
                            data: y
                        },
@ -257,22 +261,22 @@
                };
                myChart.setOption(option);
            }
            else{
            else {
                myChart.clear();
            }
        },
        delay:function(data){
        delay: function (data) {
            // 基于准备好的dom,初始化echarts实例
            var myChart = echarts.init(document.getElementById('main3'));
            if(data!=null && data.length>0)
            {
            if (data != null && data.length > 0) {
                var x = [];
                var y = [];
                for(var i=0;i<data.length;i++)
                {
                    var createTime = data[i].createTime.substring(11,16);
                var delay = [];
                var avgDelay = [];
                for (var i = 0; i < data.length; i++) {
                    var createTime = data[i].time.substring(8, 12);
                    x.push(createTime);
                    y.push(data[i].value);
                    delay.push(data[i].delay);
                    avgDelay.push(data[i].avgDelay);
                }
                // 指定图表的配置项和数据
                var option = {
@ -283,14 +287,14 @@
                    tooltip: {
                        trigger: 'axis'
                    },
                    dataZoom : {
                        show : true,
                        start : 50,
                        end : 100
                    dataZoom: {
                        show: true,
                        start: 50,
                        end: 100
                    },
                    legend: {
                        left: 'left',
                        data: ['延时']
                        data: ['延时', '平均延时']
                    },
                    xAxis: {
                        type: 'category',
@ -311,54 +315,59 @@
                        {
                            name: '延时',
                            type: 'line',
                            data: y
                            data: delay
                        },
                        {
                            name: '平均延时',
                            type: 'line',
                            data: avgDelay
                        }
                    ]
                };
                myChart.setOption(option);
            }
            else{
            else {
                myChart.clear();
            }
        },
        usage:function(data){
        usage: function (data) {
            // 基于准备好的dom,初始化echarts实例
            var myChart = echarts.init(document.getElementById('main4'));
            if(data!=null && data.length>0)
            {
            if (data != null && data.length > 0) {
                var x = [];
                var y1 = [];
                var y2 = [];
                var y3 = [];
                for(var i=0;i<data.length;i++)
                {
                    var createTime = data[i].createTime.substring(11,16);
                for (var i = 0; i < data.length; i++) {
                    var createTime = data[i].time.substring(8, 12);
                    x.push(createTime);
                    var count = JSON.parse(JSON.parse(data[i].value));
                    y1.push(count.totalCount);
                    y2.push(count.successCount);
                    y3.push(count.failureCount);
                    var count = data[i].pv;
                    var successful = data[i].successful;
                    y1.push(successful / count * 100);
                }
                // 指定图表的配置项和数据
                // 指定图表的配置项和数据
                var option = {
                    title: {
                        text: ' 使用率',
                        left: 'center'
                    },
                    tooltip: {
                        trigger: 'axis'
                        trigger: 'axis',
                        formatter: function (params) {
                            var index = params[0].dataIndex;
                            return params[0].seriesName + "<br/>" +
                                params[0].name + ' : ' + params[0].value + '% (' + data[index].successful + '/' + data[index].pv + ')';
                        }
                    },
                    dataZoom : {
                        show : true,
                        start : 50,
                        end : 100
                    dataZoom: {
                        show: true,
                        start: 50,
                        end: 100
                    },
                    legend: {
                        left: 'left',
                        data: ['总使用数', '成功数', '失败数']
                        data: ['使用率']
                    },
                        xAxis: {
                    xAxis: {
                        type: 'category',
                        name: '时间',
                        splitLine: {show: false},
@ -375,43 +384,31 @@
                    },
                    series: [
                        {
                            name: '总使用数',
                            name: '使用率',
                            type: 'line',
                            data: y1
                        },
                        {
                            name: '成功数',
                            type: 'line',
                            data: y2
                        },
                        {
                            name: '失败数',
                            type: 'line',
                            data: y3
                        }
                    ]
                };
                myChart.setOption(option);
            }
            else{
            else {
                myChart.clear();
            }
        },
        //任务状态
        setJobStatus:function(status)
        {
        setJobStatus: function (status) {
            var me = this;
            if(status=="1")
            {
                $('#jobStatusSwitch').attr("checked",true);
                me.switchery.element.checked=true;
            if (status == "1") {
                $('#jobStatusSwitch').attr("checked", true);
                me.switchery.element.checked = true;
                me.switchery.setPosition();
                $("#jobStatus").html('<span class="green job_run">正在运行中...</span>');
            }
            else{
            else {
                $('#jobStatusSwitch').removeAttr("checked");
                me.switchery.element.checked=false;
                me.switchery.element.checked = false;
                me.switchery.setPosition();
                $("#jobStatus").html('<span class="red job_stop">运行暂停</span>');
            }
@ -420,7 +417,7 @@
    /*当前时间*/
    function nowDate(){
    function nowDate() {
        var date = new Date();
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
@ -428,16 +425,16 @@
        var hour = date.getHours();
        var minute = date.getMinutes();
        var second = date.getSeconds();
        return year + '-' + month + '-' + day  + ' ' + hour + ':' + minute + ':' + second;
        return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
    }
    /*前一天时间*/
    function prevDate(){
    function prevDate() {
        var now = new Date();
        var date = new Date(now.getTime() -  24 * 3600 * 1000);
        var date = new Date(now.getTime() - 1 * 3600 * 1000);
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var day = date.getDate();
        return year + '-' + month + '-' + day  + ' 00:00:00';
        return year + '-' + month + '-' + day + ' 00:00:00';
    }
</script>

+ 26 - 0
src/main/webapp/develop/lib/module/dateExt.js

@ -0,0 +1,26 @@
/**
 * Created by l4qiang on 2017-06-20.
 */
// 对Date的扩展,将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符,
// 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
// 例子:
// (new Date()).format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
// (new Date()).format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
Date.prototype.format = function(fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}