Search in sources :

Example 6 with IPPortPair

use of beans.request.IPPortPair in project MSEC by Tencent.

the class CarryOutReleasePlan method exec.

public JsonRPCResponseBase exec(ReleasePlan request) {
    Logger logger = Logger.getLogger(CarryOutReleasePlan.class);
    JsonRPCResponseBase resp = new JsonRPCResponseBase();
    plan_id = request.getPlan_id();
    flsn = request.getFirst_level_service_name();
    slsn = request.getSecond_level_service_name();
    logger.info(String.format("carry out plan begin\n [%s.%s][%s]\n", flsn, slsn, plan_id));
    if (flsn == null || flsn.length() < 1 || slsn == null || slsn.length() < 1 || plan_id == null || plan_id.length() < 1) {
        resp.setStatus(100);
        resp.setMessage("service name/plan id invalid!");
        return resp;
    }
    String result = checkIdentity();
    if (!result.equals("success")) {
        resp.setStatus(99);
        resp.setMessage(result);
        return resp;
    }
    DBUtil util = new DBUtil();
    if (util.getConnection() == null) {
        resp.setStatus(100);
        resp.setMessage("db connect failed!");
        return resp;
    }
    try {
        String sql = "select dest_ip_list, memo,release_type from t_release_plan where plan_id=?";
        ArrayList<Object> params = new ArrayList<Object>();
        params.add(request.getPlan_id());
        Map<String, Object> res = util.findSimpleResult(sql, params);
        if (res.get("dest_ip_list") == null) {
            resp.setStatus(100);
            resp.setMessage("query dest ip list failed.");
            return resp;
        }
        String dest_ip_list = (String) (res.get("dest_ip_list"));
        release_memo = (String) (res.get("memo"));
        release_type = (String) (res.get("release_type"));
        release_memo = plan_id.substring(4, 12) + release_memo;
        ObjectMapper objectMapper = new ObjectMapper();
        IPPortPair[] ips = objectMapper.readValue(dest_ip_list, IPPortPair[].class);
        logger.info("destination IP number;" + ips.length);
        //每一个目标ip执行耗时估计30s,
        long gap = ips.length * 60;
        long lastCarryoutTime = getLastCarryoutTime(util);
        checkTime(util, gap, lastCarryoutTime);
        logger.info("check last carry out time OK");
        //对每个IP下发安装包
        String tarFile = PackReleaseFile.getPackedFile(request.getPlan_id());
        logger.info("release package path:" + tarFile);
        getHttpResponse().setContentType("text/html");
        getHttpResponse().setCharacterEncoding("UTF-8");
        ServletOutputStream out = getHttpResponse().getOutputStream();
        safeWrite("<html>", out);
        safeWrite("<head>", out);
        safeWrite("<title>release result</title>", out);
        safeWrite("</head>", out);
        safeWrite("<body>", out);
        //这个标签用于原样输出
        safeWrite("<pre>", out);
        updatePlanStatus(util, "carrying out");
        String dev_lang = getDevLang(util, flsn, slsn);
        doRelease(tarFile, ips, out, lastCarryoutTime == 0, dev_lang, util);
        safeWrite("</pre>", out);
        safeWrite("</body>", out);
        safeWrite("</html>", out);
        //update plan status
        updatePlanStatus(util, "carry out successfully");
        try {
            out.close();
        } catch (Exception e) {
        }
        return null;
    } catch (Exception e) {
        resp.setStatus(100);
        resp.setMessage(e.getMessage());
        e.printStackTrace();
        try {
            updatePlanStatus(util, "failed to carry out");
        } catch (Exception e1) {
        }
        return resp;
    } finally {
        util.releaseConn();
    }
}
Also used : ServletOutputStream(javax.servlet.ServletOutputStream) ArrayList(java.util.ArrayList) Logger(org.apache.log4j.Logger) IPPortPair(beans.request.IPPortPair) ObjectMapper(org.codehaus.jackson.map.ObjectMapper)

Example 7 with IPPortPair

use of beans.request.IPPortPair in project MSEC by Tencent.

the class DelSecondLevelServiceIPInfo method exec.

public DelSecondLevelServiceIPInfoResponse exec(DelSecondLevelServiceIPInfoRequest request) {
    DelSecondLevelServiceIPInfoResponse response = new DelSecondLevelServiceIPInfoResponse();
    response.setMessage("unkown error.");
    response.setStatus(100);
    String result = checkIdentity();
    if (!result.equals("success")) {
        response.setStatus(99);
        response.setMessage(result);
        return response;
    }
    if (request.getIpToDel() == null || request.getIpToDel().length == 0) {
        response.setMessage("IP /port to be deleted should NOT be empty.");
        response.setStatus(100);
        return response;
    }
    DBUtil util = new DBUtil();
    if (util.getConnection() == null) {
        response.setMessage("DB connect failed.");
        response.setStatus(100);
        return response;
    }
    try {
        int total = 0;
        IPPortPair[] ipToDel = request.getIpToDel();
        for (int i = 0; i < ipToDel.length; i++) {
            String sql = "delete from t_second_level_service_ipinfo where ip=? and port=? and status='disabled'";
            List<Object> params = new ArrayList<Object>();
            params.add(ipToDel[i].getIp());
            params.add(ipToDel[i].getPort());
            try {
                int delNum = util.updateByPreparedStatement(sql, params);
                if (delNum > 0) {
                    total += delNum;
                    continue;
                } else {
                    response.setMessage("delete record number is " + delNum);
                    response.setDelNumber(delNum);
                    response.setStatus(100);
                    return response;
                }
            } catch (SQLException e) {
                response.setMessage("Delete record failed:" + e.toString());
                response.setStatus(100);
                e.printStackTrace();
                return response;
            }
        }
        response.setMessage("success");
        response.setDelNumber(total);
        response.setStatus(0);
        return response;
    } finally {
        util.releaseConn();
    }
}
Also used : DBUtil(ngse.org.DBUtil) IPPortPair(beans.request.IPPortPair) SQLException(java.sql.SQLException) ArrayList(java.util.ArrayList) DelSecondLevelServiceIPInfoResponse(beans.response.DelSecondLevelServiceIPInfoResponse)

Example 8 with IPPortPair

use of beans.request.IPPortPair in project MSEC by Tencent.

the class ChangeOddCapacity method exec.

public JsonRPCResponseBase exec(ChangeOddCapacityRequest request) {
    JsonRPCResponseBase response = new JsonRPCResponseBase();
    String result = checkIdentity();
    if (!result.equals("success")) {
        response.setStatus(99);
        response.setMessage(result);
        return response;
    }
    Logger logger = Logger.getLogger(ChangeOddCapacity.class);
    //把ip列表刷新到LB的服务器里并下发给各个客户端
    AccessZooKeeper azk = new AccessZooKeeper();
    DBUtil util = new DBUtil();
    if (util.getConnection() == null) {
        response.setStatus(100);
        response.setMessage("db connect failed");
        return response;
    }
    try {
        //step1:更新扩缩容的IP的状态
        if (//扩容
        request.getAction_type().equals("expand")) {
            updateIPStatus(request, true, util);
        } else // 缩容
        {
            updateIPStatus(request, false, util);
        }
        logger.info("update matchine's status OK, matchine Numbers:" + request.getIp_list().size());
        //step2: 获得该服务下所有enabled的IP,写入LB系统
        ArrayList<IPPortPair> ips = LoadBalance.getIPPortInfoByServiceName(request.getFirst_level_service_name(), request.getSecond_level_service_name(), util);
        if (ips == null) {
            response.setStatus(100);
            response.setMessage("get ip info from db failed");
            return response;
        }
        logger.info("get enabled IP, they will be write to LB server, number:" + ips.size());
        result = LoadBalance.writeOneServiceConfigInfo(azk, request.getFirst_level_service_name() + "/" + request.getSecond_level_service_name(), false, ips);
        if (result == null || !result.equals("success")) {
            response.setStatus(100);
            response.setMessage(result);
            return response;
        }
        logger.info("write into LB server successfully.");
        response.setStatus(0);
        response.setMessage("success");
        return response;
    } catch (Exception e) {
        e.printStackTrace();
        response.setStatus(100);
        response.setMessage(e.getMessage());
        return response;
    } finally {
        azk.disconnect();
        util.releaseConn();
    }
}
Also used : DBUtil(ngse.org.DBUtil) JsonRPCResponseBase(ngse.org.JsonRPCResponseBase) IPPortPair(beans.request.IPPortPair) Logger(org.apache.log4j.Logger) AccessZooKeeper(ngse.org.AccessZooKeeper)

Example 9 with IPPortPair

use of beans.request.IPPortPair in project MSEC by Tencent.

the class QueryBusinessLog method getBusiLogSrvIPPort.

public static ArrayList<IPPortPair> getBusiLogSrvIPPort() {
    DBUtil util = new DBUtil();
    try {
        if (util.getConnection() == null) {
            return null;
        }
        String sql = sql = "select ip,port from t_second_level_service_ipinfo where second_level_service_name='log' " + "and first_level_service_name='RESERVED' and status='enabled'";
        ArrayList<IPPortPair> list = util.findMoreRefResult(sql, null, IPPortPair.class);
        return list;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    } finally {
        util.releaseConn();
    }
}
Also used : DBUtil(ngse.org.DBUtil) IPPortPair(beans.request.IPPortPair)

Example 10 with IPPortPair

use of beans.request.IPPortPair in project MSEC by Tencent.

the class QueryBusinessLog method doQueryLog.

private String doQueryLog(BusinessLog request) {
    Logger logger = Logger.getLogger(QueryBusinessLog.class);
    String svcname = request.getService_name();
    //if (svcname == null || svcname.length() < 1) { return "svcname field invalid";}
    String dt;
    dt = request.getDt_begin();
    if (dt == null || dt.length() < 14) {
        return "time field invalid";
    }
    String begin_dt = dt.substring(0, 4) + "-" + dt.substring(4, 6) + "-" + dt.substring(6, 8);
    String begin_tm = dt.substring(9);
    dt = request.getDt_end();
    if (dt == null || dt.length() < 14) {
        return "time field invalid";
    }
    String end_dt = dt.substring(0, 4) + "-" + dt.substring(4, 6) + "-" + dt.substring(6, 8);
    String end_tm = dt.substring(9);
    String where = "";
    if (request.getRequest_id() != null && request.getRequest_id().length() > 0) {
        if (where.length() > 0) {
            where += " and ";
        }
        where += " ReqID='" + request.getRequest_id() + "'";
    }
    if (request.getLog_ip() != null && request.getLog_ip().length() > 0) {
        if (where.length() > 0) {
            where += " and ";
        }
        where += " LocalIP='" + request.getLog_ip() + "' ";
    }
    if (request.getMore_condition() != null && request.getMore_condition().length() > 0) {
        if (where.length() > 0) {
            where += " and ";
        }
        where += request.getMore_condition();
    }
    String sJson = String.format("{\"queryLogReq\":{\"appName\":\"%s\",  \"logLevel\":\"DEBUG\"," + "\"filterFieldList\": null,\"maxRetNum\":1000, \"startDate\":\"%s\"," + " \"endDate\":\"%s\", \"startTime\":\"%s\", \"endTime\":\"%s\", " + "\"whereCondition\":\"%s\"}}", svcname, begin_dt, end_dt, begin_tm, end_tm, where);
    logger.info("request to  log server:" + sJson);
    String lens = String.format("%10d", sJson.length());
    ArrayList<IPPortPair> ipPortPairs = getBusiLogSrvIPPort();
    if (ipPortPairs == null || ipPortPairs.size() < 1) {
        return "get log server ip failed";
    }
    log_srv_ip = ipPortPairs.get(0).getIp();
    log_srv_port = ipPortPairs.get(0).getPort();
    Socket socket = new Socket();
    try {
        socket.setSoTimeout(5000);
        socket.connect(new InetSocketAddress(log_srv_ip, log_srv_port), 3000);
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write(lens.getBytes());
        outputStream.write(sJson.getBytes());
        socket.shutdownOutput();
        //收应答包
        // length field 10bytes
        byte[] buf = new byte[1024 * 1024];
        int total_len = 0;
        while (total_len < 10) {
            int len = socket.getInputStream().read(buf, total_len, 10 - total_len);
            if (len <= 0) {
                return "receive json len failed.";
            }
            total_len += len;
        }
        int jsonLen = new Integer(new String(buf, 0, total_len).trim()).intValue();
        logger.info(String.format("response json string len:%d", jsonLen));
        if (jsonLen > buf.length) {
            return "response json is too long";
        }
        total_len = 0;
        while (total_len < jsonLen) {
            int len = socket.getInputStream().read(buf, total_len, jsonLen - total_len);
            if (len <= 0) {
                return "receive json string failed.";
            }
            total_len += len;
        }
        String jsonStr = new String(buf, 0, total_len);
        //String jsonStr = "{'queryLogRsp':{'ret':0, 'errmsg':'ok', 'records':[ ['b\"i{e:r}s\\'on', '1122[8]490', '36岁'],['babamama', '2202020302', '37岁']  ],heads:['name', 'uin', 'age']}}";
        logger.info("the length of log json string:" + jsonStr.length());
        // logger.info("log resp:"+jsonStr);
        JSONObject jsonObject = new JSONObject(jsonStr);
        jsonObject = jsonObject.getJSONObject("queryLogRsp");
        int status = jsonObject.getInt("ret");
        if (status != 0) {
            String message = jsonObject.getString("errmsg");
            return message;
        }
        ArrayList<String> columns = new ArrayList<String>();
        ArrayList<HashMap<String, String>> record_map_list = new ArrayList<HashMap<String, String>>();
        //返回的json字符串
        // {queryLogRsp:{ret:0, errmsg:'ok', records:[ ['fieldvalue1', 'fieldvalue2', 'fieldvalue3'], ...  ],heads:['ReqID', 'instime', ....]} }
        // 注意:引号要转义
        // 例如:{'queryLogRsp':{'ret':0, 'errmsg':'ok', 'records':[ ['b"i{e:r}s\'on', '1122[8]490', '36岁'],['babamama', '2202030202', '37岁']  ],heads:['name', 'uin', 'age']}}
        // json array里元素的顺序是否在序列化前后或者反序列化前后保持不变呢?
        JSONArray heads = jsonObject.getJSONArray("heads");
        StringBuffer logstr = new StringBuffer();
        for (int i = 0; i < heads.length(); i++) {
            columns.add(heads.getString(i));
            logstr.append(heads.getString(i));
            logstr.append(";");
        }
        logger.info("log head:" + logstr);
        JSONArray records = jsonObject.getJSONArray("records");
        for (int i = 0; i < records.length(); ++i) {
            JSONArray values = records.getJSONArray(i);
            if (values.length() != columns.size()) {
                return "data returned by log serv is invalid.";
            }
            HashMap<String, String> record_map = new HashMap<String, String>();
            for (int j = 0; j < values.length(); j++) {
                String value = values.getString(j);
                record_map.put(columns.get(j), value);
            }
            record_map_list.add(record_map);
        }
        logger.info("log record number:" + record_map_list.size());
        BusinessLogResult businessLogResult = new BusinessLogResult();
        businessLogResult.setColumn_names(columns);
        businessLogResult.setLog_records(record_map_list);
        this.getHttpRequest().getSession().setAttribute(BUSI_LOG_RESULT_IN_SESSION, businessLogResult);
        return "success";
    } catch (Exception e) {
        e.printStackTrace();
        logger.error(e.getMessage());
        return e.getMessage();
    } finally {
        if (socket != null) {
            try {
                socket.close();
            } catch (Exception e) {
            }
            ;
        }
    }
}
Also used : BusinessLogResult(beans.dbaccess.BusinessLogResult) HashMap(java.util.HashMap) InetSocketAddress(java.net.InetSocketAddress) OutputStream(java.io.OutputStream) ServletOutputStream(javax.servlet.ServletOutputStream) ArrayList(java.util.ArrayList) JSONArray(org.json.JSONArray) Logger(org.apache.log4j.Logger) IPPortPair(beans.request.IPPortPair) JSONObject(org.json.JSONObject) Socket(java.net.Socket)

Aggregations

IPPortPair (beans.request.IPPortPair)22 Logger (org.apache.log4j.Logger)18 ArrayList (java.util.ArrayList)12 DBUtil (ngse.org.DBUtil)12 AccessZooKeeper (ngse.org.AccessZooKeeper)7 JSONObject (org.json.JSONObject)7 OutputStream (java.io.OutputStream)5 InetSocketAddress (java.net.InetSocketAddress)5 Socket (java.net.Socket)5 ServletOutputStream (javax.servlet.ServletOutputStream)5 JsonRPCResponseBase (ngse.org.JsonRPCResponseBase)4 SecondLevelService (beans.dbaccess.SecondLevelService)3 ObjectMapper (org.codehaus.jackson.map.ObjectMapper)3 JSONArray (org.json.JSONArray)3 BusinessLogResult (beans.dbaccess.BusinessLogResult)2 OddSecondLevelService (beans.dbaccess.OddSecondLevelService)2 SQLException (java.sql.SQLException)2 CapacityBaseInfo (beans.dbaccess.CapacityBaseInfo)1 CapacityDetailInfo (beans.dbaccess.CapacityDetailInfo)1 BusiLogField (beans.request.BusiLogField)1