SqlTask.java 19.0 KB
Newer Older
L
ligang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.escheduler.server.worker.task.sql;

import cn.escheduler.alert.utils.MailUtils;
20
import cn.escheduler.api.enums.Status;
L
ligang 已提交
21 22 23 24 25 26 27 28
import cn.escheduler.common.Constants;
import cn.escheduler.common.enums.DbType;
import cn.escheduler.common.enums.ShowType;
import cn.escheduler.common.enums.TaskTimeoutStrategy;
import cn.escheduler.common.enums.UdfType;
import cn.escheduler.common.job.db.*;
import cn.escheduler.common.process.Property;
import cn.escheduler.common.task.AbstractParameters;
29
import cn.escheduler.common.task.sql.SqlBinds;
L
ligang 已提交
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
import cn.escheduler.common.task.sql.SqlParameters;
import cn.escheduler.common.task.sql.SqlType;
import cn.escheduler.common.utils.CollectionUtils;
import cn.escheduler.common.utils.ParameterUtils;
import cn.escheduler.dao.AlertDao;
import cn.escheduler.dao.DaoFactory;
import cn.escheduler.dao.ProcessDao;
import cn.escheduler.dao.model.*;
import cn.escheduler.server.utils.ParamUtils;
import cn.escheduler.server.utils.UDFUtils;
import cn.escheduler.server.worker.task.AbstractTask;
import cn.escheduler.server.worker.task.TaskProps;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.EnumUtils;
import org.slf4j.Logger;

import java.sql.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
53
import java.util.stream.Collectors;
L
ligang 已提交
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125

/**
 *  sql task
 */
public class SqlTask extends AbstractTask {

    /**
     *  sql parameters
     */
    private SqlParameters sqlParameters;

    /**
     *  process database access
     */
    private ProcessDao processDao;

    /**
     *  alert dao
     */
    private AlertDao alertDao;


    public SqlTask(TaskProps props, Logger logger) {
        super(props, logger);

        logger.info("sql task params {}", taskProps.getTaskParams());
        this.sqlParameters = JSONObject.parseObject(props.getTaskParams(), SqlParameters.class);

        if (!sqlParameters.checkParameters()) {
            throw new RuntimeException("sql task params is not valid");
        }
        this.processDao = DaoFactory.getDaoInstance(ProcessDao.class);
        this.alertDao = DaoFactory.getDaoInstance(AlertDao.class);
    }

    @Override
    public void handle() throws Exception {
        // set the name of the current thread
        String threadLoggerInfoName = String.format("TaskLogInfo-%s", taskProps.getTaskAppId());
        Thread.currentThread().setName(threadLoggerInfoName);
        logger.info(sqlParameters.toString());
        logger.info("sql type : {}, datasource : {}, sql : {} , localParams : {},udfs : {},showType : {},connParams : {}",
                sqlParameters.getType(), sqlParameters.getDatasource(), sqlParameters.getSql(),
                sqlParameters.getLocalParams(), sqlParameters.getUdfs(), sqlParameters.getShowType(), sqlParameters.getConnParams());

        // determine whether there is a data source
        if (sqlParameters.getDatasource() == 0){
            logger.error("datasource is null");
            exitStatusCode = -1;
        }else {
            List<String> createFuncs = null;
            DataSource dataSource = processDao.findDataSourceById(sqlParameters.getDatasource());
            logger.info("datasource name : {} , type : {} , desc : {}  , user_id : {} , parameter : {}",
                    dataSource.getName(),dataSource.getType(),dataSource.getNote(),
                    dataSource.getUserId(),dataSource.getConnectionParams());

            if (dataSource != null){
                Connection con = null;
                try {
                    BaseDataSource baseDataSource = null;
                    if (DbType.MYSQL.name().equals(dataSource.getType().name())){
                        baseDataSource = JSONObject.parseObject(dataSource.getConnectionParams(),MySQLDataSource.class);
                        Class.forName(Constants.JDBC_MYSQL_CLASS_NAME);
                    }else if (DbType.POSTGRESQL.name().equals(dataSource.getType().name())){
                        baseDataSource = JSONObject.parseObject(dataSource.getConnectionParams(),PostgreDataSource.class);
                        Class.forName(Constants.JDBC_POSTGRESQL_CLASS_NAME);
                    }else if (DbType.HIVE.name().equals(dataSource.getType().name())){
                        baseDataSource = JSONObject.parseObject(dataSource.getConnectionParams(),HiveDataSource.class);
                        Class.forName(Constants.JDBC_HIVE_CLASS_NAME);
                    }else if (DbType.SPARK.name().equals(dataSource.getType().name())){
                        baseDataSource = JSONObject.parseObject(dataSource.getConnectionParams(),SparkDataSource.class);
                        Class.forName(Constants.JDBC_SPARK_CLASS_NAME);
B
Baoqi 已提交
126 127 128
                    }else if (DbType.CLICKHOUSE.name().equals(dataSource.getType().name())){
                        baseDataSource = JSONObject.parseObject(dataSource.getConnectionParams(),ClickHouseDataSource.class);
                        Class.forName(Constants.JDBC_CLICKHOUSE_CLASS_NAME);
B
Baoqi 已提交
129 130 131
                    }else if (DbType.ORACLE.name().equals(dataSource.getType().name())){
                        baseDataSource = JSONObject.parseObject(dataSource.getConnectionParams(),OracleDataSource.class);
                        Class.forName(Constants.JDBC_ORACLE_CLASS_NAME);
B
Baoqi 已提交
132 133 134
                    }else if (DbType.SQLSERVER.name().equals(dataSource.getType().name())){
                        baseDataSource = JSONObject.parseObject(dataSource.getConnectionParams(),SQLServerDataSource.class);
                        Class.forName(Constants.JDBC_SQLSERVER_CLASS_NAME);
L
ligang 已提交
135 136 137 138
                    }


                    // ready to execute SQL and parameter entity Map
139 140 141 142 143 144 145 146 147
                    SqlBinds mainSqlBinds = getSqlAndSqlParamsMap(sqlParameters.getSql());
                    List<SqlBinds> preStatementSqlBinds = Optional.ofNullable(sqlParameters.getPreStatements()).orElse(new ArrayList<>())
                            .stream()
                            .map(this::getSqlAndSqlParamsMap)
                            .collect(Collectors.toList());
                    List<SqlBinds> postStatementSqlBinds = Optional.ofNullable(sqlParameters.getPostStatements()).orElse(new ArrayList<>())
                            .stream()
                            .map(this::getSqlAndSqlParamsMap)
                            .collect(Collectors.toList());
L
ligang 已提交
148 149 150 151 152 153 154

                    if(EnumUtils.isValidEnum(UdfType.class, sqlParameters.getType()) && StringUtils.isNotEmpty(sqlParameters.getUdfs())){
                        List<UdfFunc> udfFuncList = processDao.queryUdfFunListByids(sqlParameters.getUdfs());
                        createFuncs = UDFUtils.createFuncs(udfFuncList, taskProps.getTenantCode(), logger);
                    }

                    // execute sql task
155
                    con = executeFuncAndSql(baseDataSource, mainSqlBinds, preStatementSqlBinds, postStatementSqlBinds, createFuncs);
L
ligang 已提交
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173

                } finally {
                    if (con != null) {
                        try {
                            con.close();
                        } catch (SQLException e) {
                            throw e;
                        }
                    }
                }
            }
        }
    }

    /**
     *  ready to execute SQL and parameter entity Map
     * @return
     */
174 175 176
    private SqlBinds getSqlAndSqlParamsMap(String sql) {
        Map<Integer,Property> sqlParamsMap =  new HashMap<>();
        StringBuilder sqlBuilder = new StringBuilder();
L
ligang 已提交
177 178 179 180 181 182 183 184 185 186 187 188 189

        // find process instance by task id
        ProcessInstance processInstance = processDao.findProcessInstanceByTaskId(taskProps.getTaskInstId());

        Map<String, Property> paramsMap = ParamUtils.convert(taskProps.getUserDefParamsMap(),
                taskProps.getDefinedParams(),
                sqlParameters.getLocalParametersMap(),
                processInstance.getCmdTypeIfComplement(),
                processInstance.getScheduleTime());

        // spell SQL according to the final user-defined variable
        if(paramsMap == null){
            sqlBuilder.append(sql);
190
            return new SqlBinds(sqlBuilder.toString(), sqlParamsMap);
L
ligang 已提交
191 192
        }

193 194 195 196 197 198
        if (StringUtils.isNotEmpty(sqlParameters.getTitle())){
            String title = ParameterUtils.convertParameterPlaceholders(sqlParameters.getTitle(), ParamUtils.convert(paramsMap));
            logger.info(title);
            sqlParameters.setTitle(title);
        }

L
ligang 已提交
199 200 201 202 203 204 205 206 207 208
        // special characters need to be escaped, ${} needs to be escaped
        String rgex = "'?\\$\\{(.*?)\\}'?";
        setSqlParamsMap(sql,rgex,sqlParamsMap,paramsMap);

        // replace the ${} of the SQL statement with the Placeholder
        String formatSql = sql.replaceAll(rgex,"?");
        sqlBuilder.append(formatSql);

        // print repalce sql
        printReplacedSql(sql,formatSql,rgex,sqlParamsMap);
209
        return new SqlBinds(sqlBuilder.toString(), sqlParamsMap);
L
ligang 已提交
210 211 212 213 214 215 216 217 218 219
    }

    @Override
    public AbstractParameters getParameters() {
        return this.sqlParameters;
    }

    /**
     *  execute sql
     * @param baseDataSource
220 221 222 223
     * @param mainSqlBinds
     * @param preStatementsBinds
     * @param postStatementsBinds
     * @param createFuncs
L
ligang 已提交
224
     */
225 226 227 228 229
    public Connection executeFuncAndSql(BaseDataSource baseDataSource,
                                        SqlBinds mainSqlBinds,
                                        List<SqlBinds> preStatementsBinds,
                                        List<SqlBinds> postStatementsBinds,
                                        List<String> createFuncs){
L
ligang 已提交
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
        Connection connection = null;
        try {

            if (DbType.HIVE.name().equals(sqlParameters.getType())) {
                Properties paramProp = new Properties();
                paramProp.setProperty("user", baseDataSource.getUser());
                paramProp.setProperty("password", baseDataSource.getPassword());
                Map<String, String> connParamMap = CollectionUtils.stringToMap(sqlParameters.getConnParams(), Constants.SEMICOLON,"hiveconf:");
                if(connParamMap != null){
                    paramProp.putAll(connParamMap);
                }

                connection = DriverManager.getConnection(baseDataSource.getJdbcUrl(),paramProp);
            }else{
                connection = DriverManager.getConnection(baseDataSource.getJdbcUrl(),
                        baseDataSource.getUser(), baseDataSource.getPassword());
            }

            // create temp function
249 250 251 252 253 254
            if (CollectionUtils.isNotEmpty(createFuncs)) {
                try (Statement  funcStmt = connection.createStatement()) {
                    for (String createFunc : createFuncs) {
                        logger.info("hive create function sql: {}", createFunc);
                        funcStmt.execute(createFunc);
                    }
L
ligang 已提交
255 256 257
                }
            }

258 259 260 261
            for (SqlBinds sqlBind: preStatementsBinds) {
                try (PreparedStatement stmt = prepareStatementAndBind(connection, sqlBind)) {
                    int result = stmt.executeUpdate();
                    logger.info("pre statement execute result: " + result + ", for sql: "  + sqlBind.getSql());
L
ligang 已提交
262 263
                }
            }
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279

            try (PreparedStatement  stmt = prepareStatementAndBind(connection, mainSqlBinds)) {
                // decide whether to executeQuery or executeUpdate based on sqlType
                if (sqlParameters.getSqlType() == SqlType.QUERY.ordinal()) {
                    // query statements need to be convert to JsonArray and inserted into Alert to send
                    JSONArray array = new JSONArray();
                    ResultSet resultSet = stmt.executeQuery();
                    ResultSetMetaData md = resultSet.getMetaData();
                    int num = md.getColumnCount();

                    while (resultSet.next()) {
                        JSONObject mapOfColValues = new JSONObject(true);
                        for (int i = 1; i <= num; i++) {
                            mapOfColValues.put(md.getColumnName(i), resultSet.getObject(i));
                        }
                        array.add(mapOfColValues);
L
ligang 已提交
280 281
                    }

282
                    logger.info("execute sql : {}", JSONObject.toJSONString(array, SerializerFeature.WriteMapNullValue));
L
ligang 已提交
283

284 285 286 287 288
                    // send as an attachment
                    if (StringUtils.isEmpty(sqlParameters.getShowType())) {
                        logger.info("showType is empty,don't need send email");
                    } else {
                        if (array.size() > 0) {
L
ligang 已提交
289 290 291 292 293
                            if (StringUtils.isNotEmpty(sqlParameters.getTitle())) {
                                sendAttachment(sqlParameters.getTitle(), JSONObject.toJSONString(array, SerializerFeature.WriteMapNullValue));
                            }else{
                                sendAttachment(taskProps.getNodeName() + " query resultsets ", JSONObject.toJSONString(array, SerializerFeature.WriteMapNullValue));
                            }
294
                        }
L
ligang 已提交
295 296
                    }

297
                    exitStatusCode = 0;
L
ligang 已提交
298

299 300 301 302 303
                } else if (sqlParameters.getSqlType() == SqlType.NON_QUERY.ordinal()) {
                    // non query statement
                    int result = stmt.executeUpdate();
                    exitStatusCode = 0;
                }
L
ligang 已提交
304 305
            }

306 307 308 309 310 311
            for (SqlBinds sqlBind: postStatementsBinds) {
                try (PreparedStatement stmt = prepareStatementAndBind(connection, sqlBind)) {
                    int result = stmt.executeUpdate();
                    logger.info("post statement execute result: " + result + ", for sql: "  + sqlBind.getSql());
                }
            }
L
ligang 已提交
312 313
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
314
            throw new RuntimeException(e.getMessage());
L
ligang 已提交
315 316 317 318
        }
        return connection;
    }

319 320 321 322 323 324 325 326 327 328 329 330 331 332
    private PreparedStatement prepareStatementAndBind(Connection connection, SqlBinds sqlBinds) throws Exception {
        PreparedStatement  stmt = connection.prepareStatement(sqlBinds.getSql());
        if(taskProps.getTaskTimeoutStrategy() == TaskTimeoutStrategy.FAILED || taskProps.getTaskTimeoutStrategy() == TaskTimeoutStrategy.WARNFAILED){
            stmt.setQueryTimeout(taskProps.getTaskTimeout());
        }
        Map<Integer, Property> params = sqlBinds.getParamsMap();
        if(params != null){
            for(Integer key : params.keySet()){
                Property prop = params.get(key);
                ParameterUtils.setInParameter(key,stmt,prop.getType(),prop.getValue());
            }
        }
        return stmt;
    }
L
ligang 已提交
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351

    /**
     *  send mail as an attachment
     * @param title
     * @param content
     */
    public void sendAttachment(String title,String content){

        //  process instance
        ProcessInstance instance = processDao.findProcessInstanceByTaskId(taskProps.getTaskInstId());

        // process define
        ProcessDefinition processDefine = processDao.findProcessDefineById(instance.getProcessDefinitionId());

        List<User> users = alertDao.queryUserByAlertGroupId(instance.getWarningGroupId());

        // receiving group list
        List<String> receviersList = new ArrayList<String>();
        for(User user:users){
352
            receviersList.add(user.getEmail().trim());
L
ligang 已提交
353 354
        }
        // custom receiver
L
ligang 已提交
355
        String receivers = sqlParameters.getReceivers();
L
ligang 已提交
356 357 358
        if (StringUtils.isNotEmpty(receivers)){
            String[] splits = receivers.split(Constants.COMMA);
            for (String receiver : splits){
359
                receviersList.add(receiver.trim());
L
ligang 已提交
360 361 362 363 364 365
            }
        }

        // copy list
        List<String> receviersCcList = new ArrayList<String>();
        // Custom Copier
L
ligang 已提交
366
        String receiversCc = sqlParameters.getReceiversCc();
L
ligang 已提交
367 368 369
        if (StringUtils.isNotEmpty(receiversCc)){
            String[] splits = receiversCc.split(Constants.COMMA);
            for (String receiverCc : splits){
370
                receviersCcList.add(receiverCc.trim());
L
ligang 已提交
371 372 373 374 375
            }
        }

        String showTypeName = sqlParameters.getShowType().replace(Constants.COMMA,"").trim();
        if(EnumUtils.isValidEnum(ShowType.class,showTypeName)){
376 377 378 379 380
            Map<String, Object> mailResult = MailUtils.sendMails(receviersList, receviersCcList, title, content, ShowType.valueOf(showTypeName));
            Status status = (Status) mailResult.get(cn.escheduler.api.utils.Constants.STATUS);
            if(status != Status.SUCCESS){
                throw new RuntimeException("send mail failed!");
            }
L
ligang 已提交
381 382
        }else{
            logger.error("showType: {} is not valid "  ,showTypeName);
383
            throw new RuntimeException(String.format("showType: %s is not valid ",showTypeName));
L
ligang 已提交
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
        }
    }

    /**
     *  regular expressions match the contents between two specified strings
     * @param content
     * @return
     */
    public void setSqlParamsMap(String content, String rgex, Map<Integer,Property> sqlParamsMap, Map<String,Property> paramsPropsMap){
        Pattern pattern = Pattern.compile(rgex);
        Matcher m = pattern.matcher(content);
        int index = 1;
        while (m.find()) {

            String paramName = m.group(1);
            Property prop =  paramsPropsMap.get(paramName);

            sqlParamsMap.put(index,prop);
            index ++;
        }
    }

    /**
     *  print replace sql
     * @param content
     * @param formatSql
     * @param rgex
     * @param sqlParamsMap
     */
    public void printReplacedSql(String content, String formatSql,String rgex, Map<Integer,Property> sqlParamsMap){
        //parameter print style
        logger.info("after replace sql , preparing : {}" , formatSql);
        StringBuffer logPrint = new StringBuffer("replaced sql , parameters:");
        for(int i=1;i<=sqlParamsMap.size();i++){
            logPrint.append(sqlParamsMap.get(i).getValue()+"("+sqlParamsMap.get(i).getType()+")");
        }
        logger.info(logPrint.toString());

        //direct print style
        Pattern pattern = Pattern.compile(rgex);
        Matcher m = pattern.matcher(content);
        int index = 1;
        StringBuffer sb = new StringBuffer("replaced sql , direct:");
        while (m.find()) {

            m.appendReplacement(sb, sqlParamsMap.get(index).getValue());

            index ++;
        }
        m.appendTail(sb);
        logger.info(sb.toString());
    }
}