From b825b9c513fffc712aed5862709124b77be3dab8 Mon Sep 17 00:00:00 2001 From: ligang Date: Fri, 29 Mar 2019 13:37:35 +0800 Subject: [PATCH] Initial module escheduler-dao commit --- escheduler-dao/pom.xml | 153 ++ .../cn/escheduler/dao/AbstractBaseDao.java | 27 + .../main/java/cn/escheduler/dao/AlertDao.java | 137 ++ .../java/cn/escheduler/dao/DaoFactory.java | 63 + .../java/cn/escheduler/dao/ProcessDao.java | 1540 +++++++++++++++++ .../java/cn/escheduler/dao/ServerDao.java | 162 ++ .../java/cn/escheduler/dao/TaskRecordDao.java | 253 +++ .../dao/datasource/ConnectionFactory.java | 126 ++ .../dao/datasource/DatabaseConfiguration.java | 63 + .../dao/mapper/AlertGroupMapper.java | 149 ++ .../dao/mapper/AlertGroupMapperProvider.java | 194 +++ .../cn/escheduler/dao/mapper/AlertMapper.java | 107 ++ .../dao/mapper/AlertMapperProvider.java | 121 ++ .../escheduler/dao/mapper/CommandMapper.java | 106 ++ .../dao/mapper/CommandMapperProvider.java | 144 ++ .../dao/mapper/DataSourceMapper.java | 219 +++ .../dao/mapper/DataSourceMapperProvider.java | 231 +++ .../dao/mapper/DatasourceUserMapper.java | 55 + .../mapper/DatasourceUserMapperProvider.java | 69 + .../dao/mapper/MasterServerMapper.java | 81 + .../mapper/MasterServerMapperProvider.java | 99 ++ .../dao/mapper/ProcessDefinitionMapper.java | 248 +++ .../ProcessDefinitionMapperProvider.java | 292 ++++ .../dao/mapper/ProcessInstanceMapMapper.java | 103 ++ .../ProcessInstanceMapMapperProvider.java | 150 ++ .../dao/mapper/ProcessInstanceMapper.java | 614 +++++++ .../mapper/ProcessInstanceMapperProvider.java | 582 +++++++ .../escheduler/dao/mapper/ProjectMapper.java | 190 ++ .../dao/mapper/ProjectMapperProvider.java | 242 +++ .../dao/mapper/ProjectUserMapper.java | 83 + .../dao/mapper/ProjectUserMapperProvider.java | 117 ++ .../cn/escheduler/dao/mapper/QueueMapper.java | 88 + .../dao/mapper/QueueMapperProvider.java | 121 ++ .../escheduler/dao/mapper/ResourceMapper.java | 278 +++ .../dao/mapper/ResourceMapperProvider.java | 297 ++++ .../dao/mapper/ResourcesUserMapper.java | 54 + .../mapper/ResourcesUserMapperProvider.java | 77 + .../escheduler/dao/mapper/ScheduleMapper.java | 174 ++ .../dao/mapper/ScheduleMapperProvider.java | 181 ++ .../escheduler/dao/mapper/SessionMapper.java | 106 ++ .../dao/mapper/SessionMapperProvider.java | 136 ++ .../dao/mapper/TaskInstanceMapper.java | 307 ++++ .../mapper/TaskInstanceMapperProvider.java | 407 +++++ .../escheduler/dao/mapper/TenantMapper.java | 137 ++ .../dao/mapper/TenantMapperProvider.java | 182 ++ .../escheduler/dao/mapper/UDFUserMapper.java | 55 + .../dao/mapper/UDFUserMapperProvider.java | 76 + .../escheduler/dao/mapper/UdfFuncMapper.java | 273 +++ .../dao/mapper/UdfFuncMapperProvider.java | 253 +++ .../dao/mapper/UserAlertGroupMapper.java | 92 + .../mapper/UserAlertGroupMapperProvider.java | 97 ++ .../cn/escheduler/dao/mapper/UserMapper.java | 225 +++ .../dao/mapper/UserMapperProvider.java | 250 +++ .../dao/mapper/WorkerServerMapper.java | 74 + .../mapper/WorkerServerMapperProvider.java | 90 + .../java/cn/escheduler/dao/model/Alert.java | 228 +++ .../cn/escheduler/dao/model/AlertGroup.java | 115 ++ .../java/cn/escheduler/dao/model/Command.java | 250 +++ .../escheduler/dao/model/CycleDependency.java | 93 + .../cn/escheduler/dao/model/DataSource.java | 186 ++ .../escheduler/dao/model/DatasourceUser.java | 115 ++ .../dao/model/DefinitionGroupByUser.java | 62 + .../cn/escheduler/dao/model/Dependency.java | 62 + .../dao/model/ExecuteStatusCount.java | 53 + .../cn/escheduler/dao/model/MasterServer.java | 130 ++ .../cn/escheduler/dao/model/ProcessData.java | 85 + .../dao/model/ProcessDefinition.java | 345 ++++ .../escheduler/dao/model/ProcessInstance.java | 521 ++++++ .../dao/model/ProcessInstanceMap.java | 85 + .../java/cn/escheduler/dao/model/Project.java | 167 ++ .../cn/escheduler/dao/model/ProjectUser.java | 143 ++ .../java/cn/escheduler/dao/model/Queue.java | 69 + .../cn/escheduler/dao/model/Resource.java | 209 +++ .../escheduler/dao/model/ResourcesUser.java | 115 ++ .../cn/escheduler/dao/model/Schedule.java | 281 +++ .../java/cn/escheduler/dao/model/Session.java | 87 + .../cn/escheduler/dao/model/TaskInstance.java | 483 ++++++ .../cn/escheduler/dao/model/TaskRecord.java | 256 +++ .../java/cn/escheduler/dao/model/Tenant.java | 142 ++ .../java/cn/escheduler/dao/model/UDFUser.java | 115 ++ .../java/cn/escheduler/dao/model/UdfFunc.java | 225 +++ .../java/cn/escheduler/dao/model/User.java | 240 +++ .../escheduler/dao/model/UserAlertGroup.java | 129 ++ .../cn/escheduler/dao/model/WorkerServer.java | 127 ++ .../cn/escheduler/dao/utils/DagHelper.java | 213 +++ .../escheduler/dao/utils/PropertyUtils.java | 192 ++ .../dao/utils/cron/AbstractCycle.java | 169 ++ .../escheduler/dao/utils/cron/CronUtils.java | 207 +++ .../dao/utils/cron/CycleFactory.java | 211 +++ .../escheduler/dao/utils/cron/CycleLinks.java | 64 + .../main/resources/dao/data_source.properties | 53 + .../cn/escheduler/dao/ProcessDaoTest.java | 32 + .../cn/escheduler/dao/cron/CronUtilsTest.java | 181 ++ .../dao/mapper/AlertGroupMapperTest.java | 59 + .../dao/mapper/AlertMapperTest.java | 62 + .../dao/mapper/CommandMapperTest.java | 70 + .../dao/mapper/DataSourceMapperTest.java | 67 + .../dao/mapper/MasterServerMapperTest.java | 74 + .../mapper/ProcessDefinitionMapperTest.java | 76 + .../dao/mapper/TenantMapperTest.java | 60 + .../dao/mapper/UdfFuncMapperTest.java | 61 + .../dao/mapper/UserAlertGroupMapperTest.java | 58 + .../escheduler/dao/mapper/UserMapperTest.java | 63 + 103 files changed, 17840 insertions(+) create mode 100644 escheduler-dao/pom.xml create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/AbstractBaseDao.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/AlertDao.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/DaoFactory.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/ProcessDao.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/ServerDao.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/TaskRecordDao.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/datasource/ConnectionFactory.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/datasource/DatabaseConfiguration.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/mapper/AlertGroupMapper.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/mapper/AlertGroupMapperProvider.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/mapper/AlertMapper.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/mapper/AlertMapperProvider.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/mapper/CommandMapper.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/mapper/CommandMapperProvider.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/mapper/DataSourceMapper.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/mapper/DataSourceMapperProvider.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/mapper/DatasourceUserMapper.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/mapper/DatasourceUserMapperProvider.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/mapper/MasterServerMapper.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/mapper/MasterServerMapperProvider.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ProcessDefinitionMapper.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ProcessDefinitionMapperProvider.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ProcessInstanceMapMapper.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ProcessInstanceMapMapperProvider.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ProcessInstanceMapper.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ProcessInstanceMapperProvider.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ProjectMapper.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ProjectMapperProvider.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ProjectUserMapper.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ProjectUserMapperProvider.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/mapper/QueueMapper.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/mapper/QueueMapperProvider.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ResourceMapper.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ResourceMapperProvider.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ResourcesUserMapper.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ResourcesUserMapperProvider.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ScheduleMapper.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ScheduleMapperProvider.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/mapper/SessionMapper.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/mapper/SessionMapperProvider.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/mapper/TaskInstanceMapper.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/mapper/TaskInstanceMapperProvider.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/mapper/TenantMapper.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/mapper/TenantMapperProvider.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/mapper/UDFUserMapper.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/mapper/UDFUserMapperProvider.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/mapper/UdfFuncMapper.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/mapper/UdfFuncMapperProvider.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/mapper/UserAlertGroupMapper.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/mapper/UserAlertGroupMapperProvider.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/mapper/UserMapper.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/mapper/UserMapperProvider.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/mapper/WorkerServerMapper.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/mapper/WorkerServerMapperProvider.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/model/Alert.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/model/AlertGroup.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/model/Command.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/model/CycleDependency.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/model/DataSource.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/model/DatasourceUser.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/model/DefinitionGroupByUser.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/model/Dependency.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/model/ExecuteStatusCount.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/model/MasterServer.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/model/ProcessData.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/model/ProcessDefinition.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/model/ProcessInstance.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/model/ProcessInstanceMap.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/model/Project.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/model/ProjectUser.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/model/Queue.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/model/Resource.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/model/ResourcesUser.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/model/Schedule.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/model/Session.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/model/TaskInstance.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/model/TaskRecord.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/model/Tenant.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/model/UDFUser.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/model/UdfFunc.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/model/User.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/model/UserAlertGroup.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/model/WorkerServer.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/utils/DagHelper.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/utils/PropertyUtils.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/utils/cron/AbstractCycle.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/utils/cron/CronUtils.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/utils/cron/CycleFactory.java create mode 100644 escheduler-dao/src/main/java/cn/escheduler/dao/utils/cron/CycleLinks.java create mode 100644 escheduler-dao/src/main/resources/dao/data_source.properties create mode 100644 escheduler-dao/src/test/java/cn/escheduler/dao/ProcessDaoTest.java create mode 100644 escheduler-dao/src/test/java/cn/escheduler/dao/cron/CronUtilsTest.java create mode 100644 escheduler-dao/src/test/java/cn/escheduler/dao/mapper/AlertGroupMapperTest.java create mode 100644 escheduler-dao/src/test/java/cn/escheduler/dao/mapper/AlertMapperTest.java create mode 100644 escheduler-dao/src/test/java/cn/escheduler/dao/mapper/CommandMapperTest.java create mode 100644 escheduler-dao/src/test/java/cn/escheduler/dao/mapper/DataSourceMapperTest.java create mode 100644 escheduler-dao/src/test/java/cn/escheduler/dao/mapper/MasterServerMapperTest.java create mode 100644 escheduler-dao/src/test/java/cn/escheduler/dao/mapper/ProcessDefinitionMapperTest.java create mode 100644 escheduler-dao/src/test/java/cn/escheduler/dao/mapper/TenantMapperTest.java create mode 100644 escheduler-dao/src/test/java/cn/escheduler/dao/mapper/UdfFuncMapperTest.java create mode 100644 escheduler-dao/src/test/java/cn/escheduler/dao/mapper/UserAlertGroupMapperTest.java create mode 100644 escheduler-dao/src/test/java/cn/escheduler/dao/mapper/UserMapperTest.java diff --git a/escheduler-dao/pom.xml b/escheduler-dao/pom.xml new file mode 100644 index 0000000000..4d5d0f09dc --- /dev/null +++ b/escheduler-dao/pom.xml @@ -0,0 +1,153 @@ + + + 4.0.0 + + cn.analysys + escheduler + 1.0.0 + + escheduler-dao + escheduler-dao + http://maven.apache.org + + UTF-8 + + + + junit + junit + test + + + + org.mybatis.spring.boot + mybatis-spring-boot-autoconfigure + + + org.springframework.boot + spring-boot + + + + + org.mybatis.spring.boot + mybatis-spring-boot-starter + + + org.apache.tomcat + tomcat-jdbc + + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.ow2.asm + asm + + + org.springframework.boot + spring-boot + + + org.springframework.boot + spring-boot-autoconfigure + + + + + + mysql + mysql-connector-java + + + + com.alibaba + druid + + + + ch.qos.logback + logback-classic + + + com.fasterxml.jackson.core + jackson-annotations + + + com.fasterxml.jackson.core + jackson-databind + + + org.apache.httpcomponents + httpclient + + + commons-httpclient + commons-httpclient + + + org.apache.commons + commons-lang3 + + + commons-lang + commons-lang + + + + com.alibaba + fastjson + compile + + + + com.cronutils + cron-utils + + + + org.quartz-scheduler + quartz + + + + org.quartz-scheduler + quartz-jobs + + + commons-configuration + commons-configuration + + + cn.analysys + escheduler-common + + + org.springframework + spring-test + test + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + ${java.version} + ${java.version} + ${project.build.sourceEncoding} + + + + + diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/AbstractBaseDao.java b/escheduler-dao/src/main/java/cn/escheduler/dao/AbstractBaseDao.java new file mode 100644 index 0000000000..ce18b15528 --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/AbstractBaseDao.java @@ -0,0 +1,27 @@ +/* + * 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.dao; + +/** + * base dao + */ +public abstract class AbstractBaseDao { + + protected abstract void init(); + + +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/AlertDao.java b/escheduler-dao/src/main/java/cn/escheduler/dao/AlertDao.java new file mode 100644 index 0000000000..dcc87eee80 --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/AlertDao.java @@ -0,0 +1,137 @@ +/* + * 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.dao; + +import cn.escheduler.common.enums.AlertStatus; +import cn.escheduler.common.enums.AlertType; +import cn.escheduler.common.enums.ShowType; +import cn.escheduler.dao.datasource.ConnectionFactory; +import cn.escheduler.dao.mapper.AlertMapper; +import cn.escheduler.dao.mapper.UserAlertGroupMapper; +import cn.escheduler.dao.model.Alert; +import cn.escheduler.dao.model.User; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.util.Date; +import java.util.List; + +@Component +public class AlertDao extends AbstractBaseDao { + + private final Logger logger = LoggerFactory.getLogger(getClass()); + + @Autowired + private AlertMapper alertMapper; + + @Autowired + private UserAlertGroupMapper userAlertGroupMapper; + + @Override + protected void init() { + alertMapper = ConnectionFactory.getSqlSession().getMapper(AlertMapper.class); + userAlertGroupMapper = ConnectionFactory.getSqlSession().getMapper(UserAlertGroupMapper.class); + } + + /** + * insert alert + * @param alert + * @return + */ + public int addAlert(Alert alert){ + return alertMapper.insert(alert); + } + + /** + * update alert + * @param alertStatus + * @param log + * @param id + * @return + */ + public int updateAlert(AlertStatus alertStatus,String log,int id){ + return alertMapper.update(alertStatus, log, new Date(), id); + } + + /** + * query user list by alert group id + * @param alerGroupId + * @return + */ + public List queryUserByAlertGroupId(int alerGroupId){ + return userAlertGroupMapper.queryForUser(alerGroupId); + } + /** + * MasterServer or WorkerServer stoped + */ + public void sendServerStopedAlert(int alertgroupId,String host,String serverType){ + Alert alert = new Alert(); + String content = String.format("[{'type':'%s','host':'%s','event':'服务挂掉','警告级别':'严重'}]",serverType,host); + alert.setTitle("容错告警"); + alert.setShowType(ShowType.TABLE); + alert.setContent(content); + alert.setAlertType(AlertType.EMAIL); + alert.setAlertGroupId(alertgroupId); + alert.setCreateTime(new Date()); + alert.setUpdateTime(new Date()); + alertMapper.insert(alert); + } + + /** + * task timeout warn + */ + public void sendTaskTimeoutAlert(int alertgroupId,String receivers,String receiversCc,int taskId,String taskName){ + Alert alert = new Alert(); + String content = String.format("[{'id':'%d','name':'%s','event':'timeout','warnLevel':'middle'}]",taskId,taskName); + alert.setTitle("Task Timeout Warn"); + alert.setShowType(ShowType.TABLE); + alert.setContent(content); + alert.setAlertType(AlertType.EMAIL); + alert.setAlertGroupId(alertgroupId); + if (StringUtils.isNotEmpty(receivers)) { + alert.setReceivers(receivers); + } + if (StringUtils.isNotEmpty(receiversCc)) { + alert.setReceiversCc(receiversCc); + } + alert.setCreateTime(new Date()); + alert.setUpdateTime(new Date()); + alertMapper.insert(alert); + } + + /** + * list the alert information of waiting to be executed + * @return + */ + public List listWaitExecutionAlert(){ + return alertMapper.listAlertByStatus(AlertStatus.WAIT_EXECUTION); + } + + /** + * list user information by alert group id + * @param alergroupId + * @return + */ + public List listUserByAlertgroupId(int alergroupId){ + return userAlertGroupMapper.listUserByAlertgroupId(alergroupId); + } + + +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/DaoFactory.java b/escheduler-dao/src/main/java/cn/escheduler/dao/DaoFactory.java new file mode 100644 index 0000000000..0a523e3b8b --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/DaoFactory.java @@ -0,0 +1,63 @@ +/* + * 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.dao; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.lang.reflect.InvocationTargetException; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * dao factory + */ +public class DaoFactory { + + private static final Logger logger = LoggerFactory.getLogger(DaoFactory.class); + + private static Map daoMap = new ConcurrentHashMap<>(); + + private DaoFactory(){ + + } + + /** + * 获取 Dao 实例 + * + * @param clazz + * @return Dao实例 + */ + @SuppressWarnings("unchecked") + public static T getDaoInstance(Class clazz) { + String className = clazz.getName(); + synchronized (daoMap) { + if (!daoMap.containsKey(className)) { + try { + T t = clazz.getConstructor().newInstance(); + // 实例初始化 + t.init(); + daoMap.put(className, t); + } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { + logger.error(e.getMessage(), e); + } + } + } + + return (T) daoMap.get(className); + } +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/ProcessDao.java b/escheduler-dao/src/main/java/cn/escheduler/dao/ProcessDao.java new file mode 100644 index 0000000000..e01150e207 --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/ProcessDao.java @@ -0,0 +1,1540 @@ +/* + * 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.dao; + +import cn.escheduler.common.Constants; +import cn.escheduler.common.enums.*; +import cn.escheduler.common.model.DateInterval; +import cn.escheduler.common.model.TaskNode; +import cn.escheduler.common.queue.ITaskQueue; +import cn.escheduler.common.queue.TaskQueueFactory; +import cn.escheduler.common.task.subprocess.SubProcessParameters; +import cn.escheduler.common.utils.DateUtils; +import cn.escheduler.common.utils.JSONUtils; +import cn.escheduler.common.utils.ParameterUtils; +import cn.escheduler.dao.mapper.*; +import cn.escheduler.dao.model.*; +import cn.escheduler.dao.utils.cron.CronUtils; +import com.alibaba.fastjson.JSONObject; +import com.cronutils.model.Cron; +import org.apache.commons.lang3.ArrayUtils; +import org.apache.commons.lang3.StringUtils; +import org.quartz.CronExpression; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; + +import java.util.*; + +import static cn.escheduler.common.Constants.*; +import static cn.escheduler.dao.datasource.ConnectionFactory.getMapper; + +/** + * process relative dao that some mappers in this. + */ +@Component +public class ProcessDao extends AbstractBaseDao { + + private final Logger logger = LoggerFactory.getLogger(getClass()); + + private final int[] stateArray = new int[]{ExecutionStatus.SUBMITTED_SUCCESS.ordinal(), + ExecutionStatus.RUNNING_EXEUTION.ordinal(), + ExecutionStatus.READY_PAUSE.ordinal(), + ExecutionStatus.READY_STOP.ordinal()}; + + @Autowired + private ProjectMapper projectMapper; + + @Autowired + private ProcessDefinitionMapper processDefineMapper; + + @Autowired + private ProcessInstanceMapper processInstanceMapper; + + @Autowired + private DataSourceMapper dataSourceMapper; + + @Autowired + private ProcessInstanceMapMapper processInstanceMapMapper; + + @Autowired + private TaskInstanceMapper taskInstanceMapper; + + @Autowired + private CommandMapper commandMapper; + + @Autowired + private ScheduleMapper scheduleMapper; + + @Autowired + private UdfFuncMapper udfFuncMapper; + + @Autowired + private ResourceMapper resourceMapper; + + /** + * task queue impl + */ + protected ITaskQueue taskQueue; + + public ProcessDao(){ + init(); + } + + /** + * initialize + */ + @Override + protected void init() { + projectMapper = getMapper(ProjectMapper.class); + processDefineMapper = getMapper(ProcessDefinitionMapper.class); + processInstanceMapper = getMapper(ProcessInstanceMapper.class); + dataSourceMapper = getMapper(DataSourceMapper.class); + processInstanceMapMapper = getMapper(ProcessInstanceMapMapper.class); + taskInstanceMapper = getMapper(TaskInstanceMapper.class); + commandMapper = getMapper(CommandMapper.class); + scheduleMapper = getMapper(ScheduleMapper.class); + udfFuncMapper = getMapper(UdfFuncMapper.class); + resourceMapper = getMapper(ResourceMapper.class); + taskQueue = TaskQueueFactory.getTaskQueueInstance(); + } + + + /** + * find one command from command queue, construct process instance + * @param logger + * @param host + * @param vaildThreadNum + * @return + */ + @Transactional(value = "TransactionManager",rollbackFor = Exception.class) + public ProcessInstance scanCommand(Logger logger, String host, int vaildThreadNum){ + + ProcessInstance processInstance = null; + Command command = findOneCommand(); + + if (command == null) { + return null; + } + logger.info(String.format("find one command: id: %d, type: %s", command.getId(),command.getCommandType().toString())); + + processInstance = constructProcessInstance(command, host); + + //cannot construct process instance, return null; + if(processInstance == null){ + logger.error("scan command, command parameter is error: %s", command.toString()); + }else{ + // check thread number enough for this command, if not, change state to waiting thread. + int commandThreadCount = this.workProcessThreadNumCount(command.getProcessDefinitionId()); + if(vaildThreadNum < commandThreadCount){ + logger.info("there is not enough thread for this command: {}",command.toString() ); + processInstance.setState(ExecutionStatus.WAITTING_THREAD); + if(command.getCommandType() != CommandType.RECOVER_WAITTING_THREAD){ + processInstance.addHistoryCmd(command.getCommandType()); + } + saveProcessInstance(processInstance); + this.setSubProcessParam(processInstance); + createRecoveryWaitingThreadCommand(command, processInstance); + return null; + }else{ + processInstance.setCommandType(command.getCommandType()); + processInstance.addHistoryCmd(command.getCommandType()); + saveProcessInstance(processInstance); + this.setSubProcessParam(processInstance); + } + } + // delete command + delCommandByid(command.getId()); + return processInstance; + } + + /** + * insert one command + */ + public int createCommand(Command command) { + int result = 0; + if (command != null){ + result = commandMapper.insert(command); + } + return result; + } + + /** + * + * find one command from queue list + * @return + */ + public Command findOneCommand(){ + return commandMapper.queryOneCommand(); + } + + /** + * check the input command exists in queue list + * @param command + * @return + */ + public Boolean verifyIsNeedCreateCommand(Command command){ + Boolean isNeedCreate = true; + Map cmdTypeMap = new HashMap(); + cmdTypeMap.put(CommandType.REPEAT_RUNNING,1); + cmdTypeMap.put(CommandType.RECOVER_SUSPENDED_PROCESS,1); + cmdTypeMap.put(CommandType.START_FAILURE_TASK_PROCESS,1); + CommandType commandType = command.getCommandType(); + + if(cmdTypeMap.containsKey(commandType)){ + JSONObject cmdParamObj = (JSONObject) JSONObject.parse(command.getCommandParam()); + JSONObject tempObj; + int processInstanceId = cmdParamObj.getInteger(CMDPARAM_RECOVER_PROCESS_ID_STRING); + + List commands = commandMapper.queryAllCommand(); + //遍历所有命令 + for (Command tmpCommand:commands){ + if(cmdTypeMap.containsKey(tmpCommand.getCommandType())){ + tempObj = (JSONObject) JSONObject.parse(tmpCommand.getCommandParam()); + if(tempObj != null && processInstanceId == tempObj.getInteger(CMDPARAM_RECOVER_PROCESS_ID_STRING)){ + isNeedCreate = false; + break; + } + } + } + } + return isNeedCreate; + } + + /** + * find process instance detail by id + * @param processId + * @return + */ + public ProcessInstance findProcessInstanceDetailById(int processId){ + return processInstanceMapper.queryDetailById(processId); + } + + /** + * find process instance by id + * @param processId + * @return + */ + public ProcessInstance findProcessInstanceById(int processId){ + + return processInstanceMapper.queryById(processId); + } + + /** + * find process instance by scheduler time. + * @param defineId + * @param scheduleTime + * @return + */ + public ProcessInstance findProcessInstanceByScheduleTime(int defineId, Date scheduleTime){ + + return processInstanceMapper.queryByScheduleTime(defineId, + DateUtils.dateToString(scheduleTime), 0,null, null); + } + + /** + * find process define by id. + * @param processDefinitionId + * @return + */ + public ProcessDefinition findProcessDefineById(int processDefinitionId) { + return processDefineMapper.queryByDefineId(processDefinitionId); + } + + /** + * delete work process instance by id + * @param processInstanceId + * @return + */ + public int deleteWorkProcessInstanceById(int processInstanceId){ + return processInstanceMapper.delete(processInstanceId); + } + + /** + * + * delete all sub process by parent instance id + * @return + */ + public int deleteAllSubWorkProcessByParentId(int processInstanceId){ + + List subProcessIdList = processInstanceMapper.querySubIdListByParentId(processInstanceId); + + for(Integer subId : subProcessIdList ){ + deleteAllSubWorkProcessByParentId(subId); + deleteWorkProcessMapByParentId(subId); + deleteWorkProcessInstanceById(subId); + } + return 1; + } + + /** + * create process define + * @param processDefinition + * @return + */ + public int createProcessDefine(ProcessDefinition processDefinition){ + int count = 0; + if(processDefinition != null){ + count = this.processDefineMapper.insert(processDefinition); + } + return count; + } + + + /** + * calculate sub process number in the process define. + * @param processDefinitionId + * @return + */ + private Integer workProcessThreadNumCount(Integer processDefinitionId){ + List ids = new ArrayList<>(); + recurseFindSubProcessId(processDefinitionId, ids); + return ids.size()+1; + } + + /** + * recursive query sub process definition id by parent id. + * @param parentId + * @param ids + */ + public void recurseFindSubProcessId(int parentId, List ids){ + ProcessDefinition processDefinition = processDefineMapper.queryByDefineId(parentId); + String processDefinitionJson = processDefinition.getProcessDefinitionJson(); + + ProcessData processData = JSONUtils.parseObject(processDefinitionJson, ProcessData.class); + + List taskNodeList = processData.getTasks(); + + if (taskNodeList != null && taskNodeList.size() > 0){ + + for (TaskNode taskNode : taskNodeList){ + String parameter = taskNode.getParams(); + if (parameter.contains(CMDPARAM_SUB_PROCESS_DEFINE_ID)){ + SubProcessParameters subProcessParam = JSONObject.parseObject(parameter, SubProcessParameters.class); + ids.add(String.valueOf(subProcessParam.getProcessDefinitionId())); + recurseFindSubProcessId(subProcessParam.getProcessDefinitionId(),ids); + } + } + } + } + + /** + * create recovery waiting thread command when thread pool is not enough for the process instance. + * sub work process instance need not to create recovery command. + * create recovery waiting thread command and delete origin command at the same time. + * if the recovery command is exists, only update the field update_time + * @param originCommand + * @param processInstance + */ + public void createRecoveryWaitingThreadCommand(Command originCommand, ProcessInstance processInstance) { + + // sub process doesnot need to create wait command + if(processInstance.getIsSubProcess() == Flag.YES){ + if(originCommand != null){ + commandMapper.delete(originCommand.getId()); + } + return; + } + Map cmdParam = new HashMap<>(); + cmdParam.put(Constants.CMDPARAM_RECOVERY_WAITTING_THREAD, String.valueOf(processInstance.getId())); + // process instance quit by "waiting thread" state + if(originCommand == null){ + Command command = new Command( + CommandType.RECOVER_WAITTING_THREAD, + processInstance.getTaskDependType(), + processInstance.getFailureStrategy(), + processInstance.getExecutorId(), + processInstance.getProcessDefinitionId(), + JSONUtils.toJson(cmdParam), + processInstance.getWarningType(), + processInstance.getWarningGroupId(), + processInstance.getScheduleTime(), + processInstance.getProcessInstancePriority() + ); + saveCommand(command); + return ; + } + + // update the command time if current command if recover from waiting + if(originCommand.getCommandType() == CommandType.RECOVER_WAITTING_THREAD){ + originCommand.setUpdateTime(new Date()); + saveCommand(originCommand); + }else{ + // delete old command and create new waiting thread command + commandMapper.delete(originCommand.getId()); + originCommand.setId(0); + originCommand.setCommandType(CommandType.RECOVER_WAITTING_THREAD); + originCommand.setUpdateTime(new Date()); + originCommand.setCommandParam(JSONUtils.toJson(cmdParam)); + originCommand.setProcessInstancePriority(processInstance.getProcessInstancePriority()); + saveCommand(originCommand); + } + } + + /** + * get schedule time from command + * @param command + * @param cmdParam + * @return + */ + private Date getScheduleTime(Command command, Map cmdParam){ + Date scheduleTime = command.getScheduleTime(); + if(scheduleTime == null){ + if(cmdParam != null && cmdParam.containsKey(CMDPARAM_COMPLEMENT_DATA_START_DATE)){ + scheduleTime = DateUtils.stringToDate(cmdParam.get(CMDPARAM_COMPLEMENT_DATA_START_DATE)); + } + } + return scheduleTime; + } + + /** + * generate a new work process instance from command. + * @param processDefinition + * @param command + * @param cmdParam + * @return + */ + private ProcessInstance generateNewProcessInstance(ProcessDefinition processDefinition, + Command command, + Map cmdParam){ + ProcessInstance processInstance = new ProcessInstance(processDefinition); + processInstance.setState(ExecutionStatus.RUNNING_EXEUTION); + processInstance.setRecovery(Flag.NO); + processInstance.setStartTime(new Date()); + processInstance.setRunTimes(1); + processInstance.setMaxTryTimes(0); + processInstance.setProcessDefinitionId(command.getProcessDefinitionId()); + processInstance.setCommandParam(command.getCommandParam()); + processInstance.setCommandType(command.getCommandType()); + processInstance.setIsSubProcess(Flag.NO); + processInstance.setTaskDependType(command.getTaskDependType()); + processInstance.setFailureStrategy(command.getFailureStrategy()); + processInstance.setExecutorId(command.getExecutorId()); + WarningType warningType = command.getWarningType() == null ? WarningType.NONE : command.getWarningType(); + processInstance.setWarningType(warningType); + Integer warningGroupId = command.getWarningGroupId() == null ? 0 : command.getWarningGroupId(); + processInstance.setWarningGroupId(warningGroupId); + + // schedule time + Date scheduleTime = getScheduleTime(command, cmdParam); + if(scheduleTime != null){ + processInstance.setScheduleTime(scheduleTime); + } + processInstance.setCommandStartTime(command.getStartTime()); + processInstance.setLocations(processDefinition.getLocations()); + processInstance.setConnects(processDefinition.getConnects()); + // curing global params + processInstance.setGlobalParams(ParameterUtils.curingGlobalParams( + processDefinition.getGlobalParamMap(), + processDefinition.getGlobalParamList(), + getCommandTypeIfComplement(processInstance, command), + processInstance.getScheduleTime())); + + //copy process define json to process instance + processInstance.setProcessInstanceJson(processDefinition.getProcessDefinitionJson()); + // set process instance priority + processInstance.setProcessInstancePriority(command.getProcessInstancePriority()); + return processInstance; + } + + + /** + * check command parameters is valid + * @param command + * @param cmdParam + * @return + */ + private Boolean checkCmdParam(Command command, Map cmdParam){ + if(command.getTaskDependType() == TaskDependType.TASK_ONLY || command.getTaskDependType()== TaskDependType.TASK_PRE){ + if(cmdParam == null + || !cmdParam.containsKey(Constants.CMDPARAM_START_NODE_NAMES) + || cmdParam.get(Constants.CMDPARAM_START_NODE_NAMES).isEmpty()){ + logger.error(String.format("command node depend type is %s, but start nodes is null ", command.getTaskDependType().toString())); + return false; + } + } + return true; + } + + /** + * construct process instance according to one command. + * @param command + * @param host + * @return + */ + private ProcessInstance constructProcessInstance(Command command, String host){ + + ProcessInstance processInstance = null; + CommandType commandType = command.getCommandType(); + Map cmdParam = JSONUtils.toMap(command.getCommandParam()); + + ProcessDefinition processDefinition = null; + if(command.getProcessDefinitionId() != 0){ + processDefinition = processDefineMapper.queryByDefineId(command.getProcessDefinitionId()); + if(processDefinition == null){ + logger.error(String.format("cannot find the work process define! define id : %d", command.getProcessDefinitionId())); + return null; + } + } + + if(cmdParam != null ){ + Integer processInstanceId = 0; + // recover from failure or pause tasks + if(cmdParam.containsKey(Constants.CMDPARAM_RECOVER_PROCESS_ID_STRING)) { + String processId = cmdParam.get(Constants.CMDPARAM_RECOVER_PROCESS_ID_STRING); + processInstanceId = Integer.parseInt(processId); + if (processInstanceId == 0) { + logger.error("command parameter is error, [ ProcessInstanceId ] is 0"); + return null; + } + }else if(cmdParam.containsKey(Constants.CMDPARAM_SUB_PROCESS)){ + // sub process map + String pId = cmdParam.get(Constants.CMDPARAM_SUB_PROCESS); + processInstanceId = Integer.parseInt(pId); + }else if(cmdParam.containsKey(Constants.CMDPARAM_RECOVERY_WAITTING_THREAD)){ + // waiting thread command + String pId = cmdParam.get(Constants.CMDPARAM_RECOVERY_WAITTING_THREAD); + processInstanceId = Integer.parseInt(pId); + } + if(processInstanceId ==0){ + processInstance = generateNewProcessInstance(processDefinition, command, cmdParam); + }else{ + processInstance = this.findProcessInstanceDetailById(processInstanceId); + } + processDefinition = processDefineMapper.queryByDefineId(processInstance.getProcessDefinitionId()); + processInstance.setProcessDefinition(processDefinition); + + //reset command parameter + if(processInstance.getCommandParam() != null){ + Map processCmdParam = JSONUtils.toMap(processInstance.getCommandParam()); + for(String key : processCmdParam.keySet()){ + if(!cmdParam.containsKey(key)){ + cmdParam.put(key,processCmdParam.get(key)); + } + } + } + // reset command parameter if sub process + if(cmdParam.containsKey(Constants.CMDPARAM_SUB_PROCESS)){ + processInstance.setCommandParam(command.getCommandParam()); + } + }else{ + // generate one new process instance + processInstance = generateNewProcessInstance(processDefinition, command, cmdParam); + } + if(!checkCmdParam(command, cmdParam)){ + logger.error("command parameter check failed!"); + return null; + } + + if(command.getScheduleTime() != null){ + processInstance.setScheduleTime(command.getScheduleTime()); + } + processInstance.setHost(host); + int runTime = processInstance.getRunTimes(); + switch (commandType){ + case START_PROCESS: + break; + case START_FAILURE_TASK_PROCESS: + // find failed tasks and init these tasks + List failedList = this.findTaskIdByInstanceState(processInstance.getId(), ExecutionStatus.FAILURE); + List killedList = this.findTaskIdByInstanceState(processInstance.getId(), ExecutionStatus.KILL); + cmdParam.remove(Constants.CMDPARAM_RECOVERY_START_NODE_STRING); + + failedList.addAll(killedList); + for(Integer taskId : failedList){ + initTaskInstance(this.findTaskInstanceById(taskId)); + } + cmdParam.put(Constants.CMDPARAM_RECOVERY_START_NODE_STRING, + String.join(Constants.COMMA, convertIntListToString(failedList))); + processInstance.setCommandParam(JSONUtils.toJson(cmdParam)); + processInstance.setRunTimes(runTime +1 ); + break; + case START_CURRENT_TASK_PROCESS: + break; + case RECOVER_WAITTING_THREAD: + break; + case RECOVER_SUSPENDED_PROCESS: + // find pause tasks and init task's state + cmdParam.remove(Constants.CMDPARAM_RECOVERY_START_NODE_STRING); + List suspendedNodeList = this.findTaskIdByInstanceState(processInstance.getId(), ExecutionStatus.PAUSE); + for(Integer taskId : suspendedNodeList){ + // 把暂停状态初始化 + initTaskInstance(this.findTaskInstanceById(taskId)); + } + cmdParam.put(Constants.CMDPARAM_RECOVERY_START_NODE_STRING, String.join(",", convertIntListToString(suspendedNodeList))); + processInstance.setCommandParam(JSONUtils.toJson(cmdParam)); + processInstance.setRunTimes(runTime +1); + break; + case RECOVER_TOLERANCE_FAULT_PROCESS: + // recover tolerance fault process + processInstance.setRecovery(Flag.YES); + break; + case COMPLEMENT_DATA: + // delete all the valid tasks when complement data + List taskInstanceList = this.findValidTaskListByProcessId(processInstance.getId()); + for(TaskInstance taskInstance : taskInstanceList){ + taskInstance.setFlag(Flag.NO); + this.updateTaskInstance(taskInstance); + } + break; + case REPEAT_RUNNING: + // delete the recover task names from command parameter + if(cmdParam.containsKey(Constants.CMDPARAM_RECOVERY_START_NODE_STRING)){ + cmdParam.remove(Constants.CMDPARAM_RECOVERY_START_NODE_STRING); + processInstance.setCommandParam(JSONUtils.toJson(cmdParam)); + } + // delete all the valid tasks when repeat running + List validTaskList = findValidTaskListByProcessId(processInstance.getId()); + for(TaskInstance taskInstance : validTaskList){ + taskInstance.setFlag(Flag.NO); + updateTaskInstance(taskInstance); + } + processInstance.setStartTime(new Date()); + processInstance.setRunTimes(runTime +1); + initComplementDataParam(processDefinition, processInstance, cmdParam); + break; + case SCHEDULER: + break; + default: + break; + } + processInstance.setState(ExecutionStatus.RUNNING_EXEUTION); + return processInstance; + } + + /** + * return complement data if the process start with complement data + */ + private CommandType getCommandTypeIfComplement(ProcessInstance processInstance, Command command){ + if(CommandType.COMPLEMENT_DATA == processInstance.getCmdTypeIfComplement()){ + return CommandType.COMPLEMENT_DATA; + }else{ + return command.getCommandType(); + } + } + + /** + * initialize complement data parameters + * @param processDefinition + * @param processInstance + * @param cmdParam + */ + private void initComplementDataParam(ProcessDefinition processDefinition, ProcessInstance processInstance, Map cmdParam) { + if(!processInstance.isComplementData()){ + return; + } + + Date startComplementTime = DateUtils.parse(cmdParam.get(CMDPARAM_COMPLEMENT_DATA_START_DATE), + YYYY_MM_DD_HH_MM_SS); + processInstance.setScheduleTime(startComplementTime); + processInstance.setGlobalParams(ParameterUtils.curingGlobalParams( + processDefinition.getGlobalParamMap(), + processDefinition.getGlobalParamList(), + CommandType.COMPLEMENT_DATA, processInstance.getScheduleTime())); + + } + + /** + * set sub work process parameters. + * handle sub work process instance, update relation table and command parameters + * set sub work process flag, extends parent work process command parameters. + */ + public ProcessInstance setSubProcessParam(ProcessInstance processInstance){ + String cmdParam = processInstance.getCommandParam(); + if(StringUtils.isEmpty(cmdParam)){ + return processInstance; + } + Map paramMap = JSONUtils.toMap(cmdParam); + // write sub process id into cmd param. + if(paramMap.containsKey(CMDPARAM_SUB_PROCESS) + && CMDPARAM_EMPTY_SUB_PROCESS.equals(paramMap.get(CMDPARAM_SUB_PROCESS))){ + paramMap.remove(CMDPARAM_SUB_PROCESS); + paramMap.put(CMDPARAM_SUB_PROCESS, String.valueOf(processInstance.getId())); + processInstance.setCommandParam(JSONUtils.toJson(paramMap)); + processInstance.setIsSubProcess(Flag.YES); + this.updateProcessInstance(processInstance); + } + // copy parent instance user def params to sub process.. + String parentInstanceId = paramMap.get(CMDPARAM_SUB_PROCESS_PARENT_INSTANCE_ID); + if(StringUtils.isNotEmpty(parentInstanceId)){ + ProcessInstance parentInstance = findProcessInstanceDetailById(Integer.parseInt(parentInstanceId)); + if(parentInstance != null){ + processInstance.setGlobalParams(parentInstance.getGlobalParams()); + this.updateProcessInstance(processInstance); + }else{ + logger.error("sub process command params error, cannot find parent instance: {} ", cmdParam); + } + } + ProcessInstanceMap processInstanceMap = JSONUtils.parseObject(cmdParam, ProcessInstanceMap.class); + if(processInstanceMap == null || processInstanceMap.getParentProcessInstanceId() == 0){ + return processInstance; + } + // update sub process id to process map table + processInstanceMap.setProcessInstanceId(processInstance.getId()); + + this.updateWorkProcessInstanceMap(processInstanceMap); + return processInstance; + } + + /** + * initialize task instance + * @param taskInstance + */ + private void initTaskInstance(TaskInstance taskInstance){ + if(taskInstance.getState().typeIsFailure() && !taskInstance.isSubProcess()){ + taskInstance.setFlag(Flag.NO); + updateTaskInstance(taskInstance); + }else{ + taskInstance.setState(ExecutionStatus.SUBMITTED_SUCCESS); + updateTaskInstance(taskInstance); + } + } + + /** + * submit task to mysql and task queue + * submit sub process to command + * @param taskInstance + * @return + */ + @Transactional(value = "TransactionManager",rollbackFor = Exception.class) + public TaskInstance submitTask(TaskInstance taskInstance, ProcessInstance processInstance){ + logger.info("start submit task : {}, instance id:{}, state: {}, ", + taskInstance.getName(), processInstance.getId(), processInstance.getState() ); + processInstance = this.findProcessInstanceDetailById(processInstance.getId()); + //submit to mysql + TaskInstance task= submitTaskInstanceToMysql(taskInstance, processInstance); + if(task.isSubProcess() && !task.getState().typeIsFinished()){ + ProcessInstanceMap processInstanceMap = setProcessInstanceMap(processInstance, task); + + TaskNode taskNode = JSONUtils.parseObject(task.getTaskJson(), TaskNode.class); + Map subProcessParam = JSONUtils.toMap(taskNode.getParams()); + Integer defineId = Integer.parseInt(subProcessParam.get(Constants.CMDPARAM_SUB_PROCESS_DEFINE_ID)); + createSubWorkProcessCommand(processInstance, processInstanceMap, defineId, task); + }else if(!task.getState().typeIsFinished()){ + //submit to task queue + task.setProcessInstancePriority(processInstance.getProcessInstancePriority()); + submitTaskToQueue(task); + } + logger.info("submit task :{} state:{} complete, instance id:{} state: {} ", + taskInstance.getName(), task.getState(), processInstance.getId(), processInstance.getState()); + return task; + } + + /** + * set work process instance map + * @param parentInstance + * @param parentTask + * @return + */ + private ProcessInstanceMap setProcessInstanceMap(ProcessInstance parentInstance, TaskInstance parentTask){ + ProcessInstanceMap processMap = findWorkProcessMapByParent(parentInstance.getId(), parentTask.getId()); + if(processMap != null){ + return processMap; + }else if(parentInstance.getCommandType() == CommandType.REPEAT_RUNNING + || parentInstance.isComplementData()){ + // update current task id to map + // repeat running does not generate new sub process instance + processMap = findPreviousTaskProcessMap(parentInstance, parentTask); + if(processMap!= null){ + processMap.setParentTaskInstanceId(parentTask.getId()); + updateWorkProcessInstanceMap(processMap); + return processMap; + } + } + // new task + processMap = new ProcessInstanceMap(); + processMap.setParentProcessInstanceId(parentInstance.getId()); + processMap.setParentTaskInstanceId(parentTask.getId()); + createWorkProcessInstanceMap(processMap); + return processMap; + } + + /** + * find previous task work process map. + * @param parentProcessInstance + * @param parentTask + * @return + */ + private ProcessInstanceMap findPreviousTaskProcessMap(ProcessInstance parentProcessInstance, + TaskInstance parentTask) { + + Integer preTaskId = 0; + List preTaskList = this.findPreviousTaskListByWorkProcessId(parentProcessInstance.getId()); + for(TaskInstance task : preTaskList){ + if(task.getName().equals(parentTask.getName())){ + preTaskId = task.getId(); + ProcessInstanceMap map = findWorkProcessMapByParent(parentProcessInstance.getId(), preTaskId); + if(map!=null){ + return map; + } + } + } + logger.info("sub process instance is not found,parent task:{},parent instance:{}", + parentTask.getId(), parentProcessInstance.getId()); + return null; + } + + /** + * create sub work process command + * @param parentProcessInstance + * @param instanceMap + * @param childDefineId + * @param task + */ + private void createSubWorkProcessCommand(ProcessInstance parentProcessInstance, + ProcessInstanceMap instanceMap, + Integer childDefineId, TaskInstance task){ + ProcessInstance childInstance = findSubProcessInstance(parentProcessInstance.getId(), task.getId()); + + CommandType fatherType = parentProcessInstance.getCommandType(); + CommandType commandType = fatherType; + if(childInstance == null || commandType == CommandType.REPEAT_RUNNING){ + String fatherHistoryCommand = parentProcessInstance.getHistoryCmd(); + // sub process must begin with schedule/complement data + // if father begin with scheduler/complement data + if(fatherHistoryCommand.startsWith(CommandType.SCHEDULER.toString()) || + fatherHistoryCommand.startsWith(CommandType.COMPLEMENT_DATA.toString())){ + commandType = CommandType.valueOf(fatherHistoryCommand.split(Constants.COMMA)[0]); + } + } + + if(childInstance != null){ + childInstance.setState(ExecutionStatus.SUBMITTED_SUCCESS); + updateProcessInstance(childInstance); + } + // set sub work process command + String processMapStr = JSONUtils.toJson(instanceMap); + Map cmdParam = JSONUtils.toMap(processMapStr); + + if(commandType == CommandType.COMPLEMENT_DATA || + (childInstance != null && childInstance.isComplementData())){ + Map parentParam = JSONUtils.toMap(parentProcessInstance.getCommandParam()); + String endTime = parentParam.get(CMDPARAM_COMPLEMENT_DATA_END_DATE); + String startTime = parentParam.get(CMDPARAM_COMPLEMENT_DATA_START_DATE); + cmdParam.put(CMDPARAM_COMPLEMENT_DATA_END_DATE, endTime); + cmdParam.put(CMDPARAM_COMPLEMENT_DATA_START_DATE, startTime); + processMapStr = JSONUtils.toJson(cmdParam); + } + Command command = new Command(); + command.setWarningType(parentProcessInstance.getWarningType()); + command.setWarningGroupId(parentProcessInstance.getWarningGroupId()); + command.setFailureStrategy(parentProcessInstance.getFailureStrategy()); + command.setProcessDefinitionId(childDefineId); + command.setScheduleTime(parentProcessInstance.getScheduleTime()); + command.setExecutorId(parentProcessInstance.getExecutorId()); + command.setCommandParam(processMapStr); + command.setCommandType(commandType); + command.setProcessInstancePriority(parentProcessInstance.getProcessInstancePriority()); + createCommand(command); + logger.info("sub process command created: {} ", command.toString()); + } + + /** + * submit task to mysql + * @param taskInstance + * @return + */ + public TaskInstance submitTaskInstanceToMysql(TaskInstance taskInstance, ProcessInstance processInstance){ + ExecutionStatus processInstanceState = processInstance.getState(); + + if(taskInstance.getState().typeIsFailure()){ + if(taskInstance.isSubProcess()){ + taskInstance.setRetryTimes(taskInstance.getRetryTimes() + 1 ); + }else { + + if( processInstanceState != ExecutionStatus.READY_STOP + && processInstanceState != ExecutionStatus.READY_PAUSE){ + // failure task set invalid + taskInstance.setFlag(Flag.NO); + updateTaskInstance(taskInstance); + // crate new task instance + taskInstance.setRetryTimes(taskInstance.getRetryTimes() + 1 ); + taskInstance.setFlag(Flag.YES); + taskInstance.setHost(null); + taskInstance.setId(0); + } + } + } + taskInstance.setProcessInstancePriority(processInstance.getProcessInstancePriority()); + taskInstance.setState(getSubmitTaskState(taskInstance, processInstanceState)); + taskInstance.setSubmitTime(new Date()); + saveTaskInstance(taskInstance); + return taskInstance; + } + + /** + * submit task to queue + * @param task + */ + public Boolean submitTaskToQueue(TaskInstance task) { + + try{ + // task cannot submit when running + if(task.getState() == ExecutionStatus.RUNNING_EXEUTION){ + logger.info(String.format("submit to task queue, but task [%s] state already be running. ", task.getName())); + return true; + } + if(checkTaskExistsInTaskQueue(task)){ + logger.info(String.format("submit to task queue, but task [%s] already exists in the queue.", task.getName())); + return true; + } + logger.info("task ready to queue: {}" , task); + taskQueue.add(SCHEDULER_TASKS_QUEUE, taskZkInfo(task)); + logger.info(String.format("master insert into queue success, task : %s", task.getName()) ); + return true; + }catch (Exception e){ + logger.error("submit task to queue Exception: ", e); + logger.error("task queue error : %s", JSONUtils.toJson(task)); + return false; + + } + } + + /** + * ${processInstancePriority}_${processInstanceId}_${taskInstancePriority}_${taskId} + * + * The tasks with the highest priority are selected by comparing the priorities of the above four levels from high to low. + * + * 流程实例优先级_流程实例id_任务优先级_任务id high <- low + * + * @param task + * @return + */ + private String taskZkInfo(TaskInstance task) { + return String.valueOf(task.getProcessInstancePriority().ordinal()) + Constants.UNDERLINE + task.getProcessInstanceId() + Constants.UNDERLINE + task.getTaskInstancePriority().ordinal() + Constants.UNDERLINE + task.getId(); + } + + /** + * get submit task instance state by the work process state + * cannot modify the task state when running/kill/submit success, or this + * task instance is already exists in task queue . + * return pause if work process state is ready pause + * return stop if work process state is ready stop + * if all of above are not satisfied, return submit success + * + * @param taskInstance + * @param processInstanceState + * @return + */ + public ExecutionStatus getSubmitTaskState(TaskInstance taskInstance, ExecutionStatus processInstanceState){ + ExecutionStatus state = taskInstance.getState(); + if( + // running or killed + // the task already exists in task queue + // return state + state == ExecutionStatus.RUNNING_EXEUTION + || state == ExecutionStatus.KILL + || checkTaskExistsInTaskQueue(taskInstance) + ){ + return state; + } + //return pasue /stop if process instance state is ready pause / stop + // or return submit success + if( processInstanceState == ExecutionStatus.READY_PAUSE){ + state = ExecutionStatus.PAUSE; + }else if(processInstanceState == ExecutionStatus.READY_STOP) { + state = ExecutionStatus.KILL; + }else{ + state = ExecutionStatus.SUBMITTED_SUCCESS; + } + return state; + } + + /** + * check the task instance existing in queue + * @return + */ + public boolean checkTaskExistsInTaskQueue(TaskInstance task){ + if(task.isSubProcess()){ + return false; + } + + String taskZkInfo = taskZkInfo(task); + + return taskQueue.checkTaskExists(SCHEDULER_TASKS_QUEUE, taskZkInfo); + } + + /** + * create a new process instance + * @param processInstance + */ + public void createProcessInstance(ProcessInstance processInstance){ + + if (processInstance != null){ + processInstanceMapper.insert(processInstance); + } + } + + /** + * insert or update work process instance to data base + * @param workProcessInstance + */ + public void saveProcessInstance(ProcessInstance workProcessInstance){ + + if (workProcessInstance == null){ + logger.error("save error, process instance is null!"); + return ; + } + //创建流程实例 + if(workProcessInstance.getId() != 0){ + processInstanceMapper.update(workProcessInstance); + }else{ + createProcessInstance(workProcessInstance); + } + } + + /** + * insert or update command + * @param command + * @return + */ + public int saveCommand(Command command){ + if(command.getId() != 0){ + return commandMapper.update(command); + }else{ + return commandMapper.insert(command); + } + } + + /** + * insert or update task instance + * @param taskInstance + * @return + */ + public boolean saveTaskInstance(TaskInstance taskInstance){ + if(taskInstance.getId() != 0){ + return updateTaskInstance(taskInstance); + }else{ + return createTaskInstance(taskInstance); + } + } + + /** + * insert task instance + * @param taskInstance + * @return + */ + public boolean createTaskInstance(TaskInstance taskInstance) { + int count = taskInstanceMapper.insert(taskInstance); + return count > 0; + } + + /** + * update task instance + * @param taskInstance + * @return + */ + public boolean updateTaskInstance(TaskInstance taskInstance){ + int count = taskInstanceMapper.update(taskInstance); + return count > 0; + } + /** + * delete a command by id + * @param id + */ + public void delCommandByid(int id) { + commandMapper.delete(id); + } + + public TaskInstance findTaskInstanceById(Integer taskId){ + return taskInstanceMapper.queryById(taskId); + } + + /** + * get id list by task state + * @param instanceId + * @param state + * @return + */ + public List findTaskIdByInstanceState(int instanceId, ExecutionStatus state){ + return taskInstanceMapper.queryTaskByProcessIdAndState(instanceId, state.ordinal()); + } + + /** + * + * find valid task list by process definition id + * @param processInstanceId + * @return + */ + public List findValidTaskListByProcessId(Integer processInstanceId){ + return taskInstanceMapper.findValidTaskListByProcessId(processInstanceId, Flag.YES); + } + + /** + * find previous task list by work process id + * @param workProcessInstanceId + * @return + */ + public List findPreviousTaskListByWorkProcessId(Integer workProcessInstanceId){ + return taskInstanceMapper.findValidTaskListByProcessId(workProcessInstanceId, Flag.NO); + } + + /** + * update work process instance map + * @param processInstanceMap + * @return + */ + public int updateWorkProcessInstanceMap(ProcessInstanceMap processInstanceMap){ + return processInstanceMapMapper.update(processInstanceMap); + } + + + /** + * create work process instance map + * @param processInstanceMap + * @return + */ + public int createWorkProcessInstanceMap(ProcessInstanceMap processInstanceMap){ + Integer count = 0; + if(processInstanceMap !=null){ + return processInstanceMapMapper.insert(processInstanceMap); + } + return count; + } + + /** + * find work process map by parent process id and parent task id. + * @param parentWorkProcessId + * @param parentTaskId + * @return + */ + public ProcessInstanceMap findWorkProcessMapByParent(Integer parentWorkProcessId, Integer parentTaskId){ + return processInstanceMapMapper.queryByParentId(parentWorkProcessId, parentTaskId); + } + + /** + * delete work process map by parent process id + * @param parentWorkProcessId + * @return + */ + public int deleteWorkProcessMapByParentId(int parentWorkProcessId){ + return processInstanceMapMapper.deleteByParentProcessId(parentWorkProcessId); + + } + + public ProcessInstance findSubProcessInstance(Integer parentProcessId, Integer parentTaskId){ + ProcessInstance processInstance = null; + ProcessInstanceMap processInstanceMap = processInstanceMapMapper.queryByParentId(parentProcessId, parentTaskId); + if(processInstanceMap == null || processInstanceMap.getProcessInstanceId() == 0){ + return processInstance; + } + processInstance = findProcessInstanceById(processInstanceMap.getProcessInstanceId()); + return processInstance; + } + public ProcessInstance findParentProcessInstance(Integer subProcessId) { + ProcessInstance processInstance = null; + ProcessInstanceMap processInstanceMap = processInstanceMapMapper.queryBySubProcessId(subProcessId); + if(processInstanceMap == null || processInstanceMap.getProcessInstanceId() == 0){ + return processInstance; + } + processInstance = findProcessInstanceById(processInstanceMap.getParentProcessInstanceId()); + return processInstance; + } + + + + /** + * change task state + * @param state + * @param startTime + * @param host + * @param executePath + */ + public void changeTaskState(ExecutionStatus state, Date startTime, String host, + String executePath, + String logPath, + int taskInstId) { + + TaskInstance taskInstance = taskInstanceMapper.queryById(taskInstId); + taskInstance.setState(state); + taskInstance.setStartTime(startTime); + taskInstance.setHost(host); + taskInstance.setExecutePath(executePath); + taskInstance.setLogPath(logPath); + saveTaskInstance(taskInstance); + } + + /** + * update process instance + * @param instance + * @return + */ + public int updateProcessInstance(ProcessInstance instance){ + return processInstanceMapper.update(instance); + } + + /** + * update the process instance + * @param processInstanceId + * @param processJson + * @param globalParams + * @param scheduleTime + * @param flag + * @param locations + * @param connects + * @return + */ + public int updateProcessInstance(Integer processInstanceId, String processJson, + String globalParams, Date scheduleTime, Flag flag, + String locations, String connects){ + return processInstanceMapper.updateProcessInstance( processInstanceId, processJson, + globalParams, scheduleTime, locations, connects, flag); + } + + /** + * change task state + * @param state + * @param endTime + */ + public void changeTaskState(ExecutionStatus state, + Date endTime, + int taskInstId) { + TaskInstance taskInstance = taskInstanceMapper.queryById(taskInstId); + taskInstance.setState(state); + taskInstance.setEndTime(endTime); + saveTaskInstance(taskInstance); + } + + /** + * convert integer list to string list + * @param intList + * @return + */ + public List convertIntListToString(List intList){ + if(intList == null){ + return new ArrayList<>(); + } + List result = new ArrayList(intList.size()); + for(Integer intVar : intList){ + result.add(String.valueOf(intVar)); + } + return result; + } + + /** + * set task + * 根据任务实例id设置pid + * @param taskInstId + * @param pid + */ + public void updatePidByTaskInstId(int taskInstId, int pid) { + TaskInstance taskInstance = taskInstanceMapper.queryById(taskInstId); + taskInstance.setPid(pid); + taskInstance.setAppLink(""); + saveTaskInstance(taskInstance); + } + + /** + * update pid and app links field by task instance id + * @param taskInstId + * @param pid + */ + public void updatePidByTaskInstId(int taskInstId, int pid,String appLinks) { + + TaskInstance taskInstance = taskInstanceMapper.queryById(taskInstId); + taskInstance.setPid(pid); + taskInstance.setAppLink(appLinks); + saveTaskInstance(taskInstance); + } + + /** + * query ProcessDefinition by name + * + * @see ProcessDefinition + */ + public ProcessDefinition findProcessDefineByName(int projectId, String name) { + ProcessDefinition projectFlow = processDefineMapper.queryByDefineName(projectId, name); + return projectFlow; + } + + /** + * query Schedule

+ * + * @see Schedule + */ + public Schedule querySchedule(int id) { + return scheduleMapper.queryById(id); + } + + public List queryNeddFailoverProcessInstances(String host){ + return processInstanceMapper.queryByHostAndStatus(host, stateArray); + } + + + /** + * update host null + * @param host + * @return + */ + public int updateNeddFailoverProcessInstances(String host){ + return processInstanceMapper.setFailoverByHostAndStateArray(host, stateArray); + } + + /** + * process need failover process instance + * @param processInstance + */ + @Transactional(value = "TransactionManager",rollbackFor = Exception.class) + public void processNeedFailoverProcessInstances(ProcessInstance processInstance){ + + + //1 update processInstance host is null + processInstance.setHost("null"); + processInstanceMapper.update(processInstance); + + //2 insert into recover command + Command cmd = new Command(); + cmd.setProcessDefinitionId(processInstance.getProcessDefinitionId()); + cmd.setCommandParam(String.format("{\"%s\":%d}", Constants.CMDPARAM_RECOVER_PROCESS_ID_STRING, processInstance.getId())); + cmd.setExecutorId(processInstance.getExecutorId()); + cmd.setCommandType(CommandType.RECOVER_TOLERANCE_FAULT_PROCESS); + createCommand(cmd); + + } + + /** + * query all need failover task instances by host + * @param host + * @return + */ + public List queryNeedFailoverTaskInstances(String host){ + return taskInstanceMapper.queryByHostAndStatus(host,stateArray); + } + + /** + * update host null + * @param host + * @return + */ + public int updateNeedFailoverTaskInstances(String host){ + return taskInstanceMapper.setFailoverByHostAndStateArray(host, stateArray); + } + + /** + * find data source by id + * @param id + * @return + */ + public DataSource findDataSourceById(int id){ + return dataSourceMapper.queryById(id); + } + + + /** + * update process instance state by id + * @param processInstanceId + * @param executionStatus + * @return + */ + public int updateProcessInstanceState(Integer processInstanceId, ExecutionStatus executionStatus) { + return processInstanceMapper.updateState(processInstanceId, executionStatus); + + } + + /** + * find process instance by the task id + * @param taskId + * @return + */ + public ProcessInstance findProcessInstanceByTaskId(int taskId){ + return processInstanceMapper.queryByTaskId(taskId); + } + + /** + * find udf function list by id list string + * @param ids + * @return + */ + public List queryUdfFunListByids(String ids){ + return udfFuncMapper.queryUdfByIdStr(ids); + } + + /** + * find tenant code by resource name + * @param resName + * @return + */ + public String queryTenantCodeByResName(String resName){ + return resourceMapper.queryTenantCodeByResourceName(resName); + } + + /** + * find schedule list by process define id. + * @param ids + * @return + */ + public List selectAllByProcessDefineId(int[] ids){ + return scheduleMapper.selectAllByProcessDefineArray(ids); + } + + /** + * get dependency cycle by work process define id and scheduler fire time + * + * @param masterId + * @param processDefinitionId + * @param scheduledFireTime 任务调度预计触发的时间 + * @return + * @throws Exception + */ + public CycleDependency getCycleDependency(int masterId, int processDefinitionId, Date scheduledFireTime) throws Exception { + List list = getCycleDependencies(masterId,new int[]{processDefinitionId},scheduledFireTime); + return list.size()>0 ? list.get(0) : null; + + } + + /** + * + * get dependency cycle list by work process define id list and scheduler fire time + * @param masterId + * @param ids + * @param scheduledFireTime 任务调度预计触发的时间 + * @return + * @throws Exception + */ + public List getCycleDependencies(int masterId,int[] ids,Date scheduledFireTime) throws Exception { + List cycleDependencyList = new ArrayList(); + if(ArrayUtils.isEmpty(ids)){ + logger.warn("ids[] is empty!is invalid!"); + return cycleDependencyList; + } + if(scheduledFireTime == null){ + logger.warn("scheduledFireTime is null!is invalid!"); + return cycleDependencyList; + } + + + String strCrontab = ""; + CronExpression depCronExpression; + Cron depCron; + List list; + List schedules = this.selectAllByProcessDefineId(ids); + // 遍历所有的调度信息 + for(Schedule depSchedule:schedules){ + strCrontab = depSchedule.getCrontab(); + depCronExpression = CronUtils.parse2CronExpression(strCrontab); + depCron = CronUtils.parse2Cron(strCrontab); + CycleEnum cycleEnum = CronUtils.getMiniCycle(depCron); + if(cycleEnum == null){ + logger.error("{} is not valid",strCrontab); + continue; + } + Calendar calendar = Calendar.getInstance(); + switch (cycleEnum){ + /*case MINUTE: + calendar.add(Calendar.MINUTE,-61);*/ + case HOUR: + calendar.add(Calendar.HOUR,-25); + break; + case DAY: + calendar.add(Calendar.DATE,-32); + break; + case WEEK: + calendar.add(Calendar.DATE,-32); + break; + case MONTH: + calendar.add(Calendar.MONTH,-13); + break; + default: + logger.warn("Dependent process definition's cycleEnum is {},not support!!", cycleEnum.name()); + continue; + } + Date start = calendar.getTime(); + + if(depSchedule.getProcessDefinitionId() == masterId){ + list = CronUtils.getSelfFireDateList(start, scheduledFireTime, depCronExpression); + }else { + list = CronUtils.getFireDateList(start, scheduledFireTime, depCronExpression); + } + if(list.size()>=1){ + start = list.get(list.size()-1); + CycleDependency dependency = new CycleDependency(depSchedule.getProcessDefinitionId(),start, CronUtils.getExpirationTime(start, cycleEnum), cycleEnum); + cycleDependencyList.add(dependency); + } + + } + return cycleDependencyList; + } + + /** + * find process instance by time interval + * @param defineId + * @param startTime + * @param endTime + * @return + */ + public ProcessInstance findProcessInstanceByTimeInterval(int defineId, Date startTime, Date endTime, int excludeId) { + + return processInstanceMapper.queryByScheduleTime(defineId, null, excludeId, + DateUtils.dateToString(startTime), DateUtils.dateToString(endTime)); + } + + public void selfFaultTolerant(int state){ + List processInstanceList = processInstanceMapper.listByStatus(new int[]{state}); + for (ProcessInstance processInstance:processInstanceList){ + selfFaultTolerant(processInstance); + } + + } + + @Transactional(value = "TransactionManager",rollbackFor = Exception.class) + public void selfFaultTolerant(ProcessInstance processInstance){ + + processInstance.setState(ExecutionStatus.FAILURE); + processInstanceMapper.update(processInstance); + // insert to command + + Command command = new Command(); + command.setCommandType(CommandType.START_FAILURE_TASK_PROCESS); + command.setProcessDefinitionId(processInstance.getProcessDefinitionId()); + command.setCommandParam(String.format("{\"%s\":%d}", + CMDPARAM_RECOVER_PROCESS_ID_STRING, processInstance.getId())); + + + command.setExecutorId(processInstance.getExecutorId()); + command.setProcessInstancePriority(processInstance.getProcessInstancePriority()); + + createCommand(command); + + } + + /** + * find last scheduler process instance in the date interval + * @param definitionId + * @param dateInterval + * @return + */ + public ProcessInstance findLastSchedulerProcessInterval(int definitionId, DateInterval dateInterval) { + return processInstanceMapper.queryLastSchedulerProcess(definitionId, + DateUtils.dateToString(dateInterval.getStartTime()), + DateUtils.dateToString(dateInterval.getEndTime())); + } + + public ProcessInstance findLastManualProcessInterval(int definitionId, DateInterval dateInterval) { + return processInstanceMapper.queryLastManualProcess(definitionId, + DateUtils.dateToString(dateInterval.getStartTime()), + DateUtils.dateToString(dateInterval.getEndTime())); + } + + public ProcessInstance findLastRunningProcess(int definitionId, DateInterval dateInterval) { + return processInstanceMapper.queryLastRunningProcess(definitionId, + DateUtils.dateToString(dateInterval.getStartTime()), + DateUtils.dateToString(dateInterval.getEndTime()), + stateArray); + } +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/ServerDao.java b/escheduler-dao/src/main/java/cn/escheduler/dao/ServerDao.java new file mode 100644 index 0000000000..82c71e2855 --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/ServerDao.java @@ -0,0 +1,162 @@ +/* + * 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.dao; + +import cn.escheduler.dao.mapper.MasterServerMapper; +import cn.escheduler.dao.mapper.WorkerServerMapper; +import cn.escheduler.dao.model.MasterServer; +import cn.escheduler.dao.model.WorkerServer; +import org.springframework.beans.factory.annotation.Autowired; + +import java.util.Date; + +import static cn.escheduler.dao.datasource.ConnectionFactory.getMapper; + +/** + * master server + */ +public class ServerDao extends AbstractBaseDao { + + @Autowired + MasterServerMapper masterServerMapper; + + + @Autowired + WorkerServerMapper workerServerMapper; + + @Override + protected void init() { + masterServerMapper = getMapper(MasterServerMapper.class); + workerServerMapper = getMapper(WorkerServerMapper.class); + } + + /** + * register master + * + * @param host + * @param port + * @param zkDirectory + * @param resInfo + * @param createTime + * @param lastHeartbeatTime + * @return + */ + public int registerMaster(String host, int port , String zkDirectory , String resInfo , + Date createTime , Date lastHeartbeatTime) { + + MasterServer masterServer = new MasterServer(); + + masterServer.setHost(host); + masterServer.setPort(port); + masterServer.setZkDirectory(zkDirectory); + masterServer.setResInfo(resInfo); + masterServer.setCreateTime(createTime); + masterServer.setLastHeartbeatTime(lastHeartbeatTime); + + return masterServerMapper.insert(masterServer); + } + + /** + * update master + * + * @param host + * @param port + * @param resInfo + * @param lastHeartbeatTime + * @return + */ + public int updateMaster(String host, int port , String resInfo , Date lastHeartbeatTime) { + + MasterServer masterServer = new MasterServer(); + + masterServer.setHost(host); + masterServer.setPort(port); + masterServer.setResInfo(resInfo); + masterServer.setLastHeartbeatTime(lastHeartbeatTime); + + return masterServerMapper.update(masterServer); + } + + /** + * delete master + * + * @param host + * @return + */ + public int deleteMaster(String host) { + return masterServerMapper.deleteWorkerByHost(host); + } + + /** + * register master + * @param host + * @param port + * @param zkDirectory + * @param resInfo + * @param createTime + * @param lastHeartbeatTime + * @return + */ + public int registerWorker(String host, int port , String zkDirectory , String resInfo , + Date createTime , Date lastHeartbeatTime) { + + WorkerServer workerServer = new WorkerServer(); + + workerServer.setHost(host); + workerServer.setPort(port); + workerServer.setZkDirectory(zkDirectory); + workerServer.setResInfo(resInfo); + workerServer.setCreateTime(createTime); + workerServer.setLastHeartbeatTime(lastHeartbeatTime); + + return workerServerMapper.insert(workerServer); + } + + /** + * + * update worker + * @param host + * @param port + * @param resInfo + * @param lastHeartbeatTime + * @return + */ + public int updateWorker(String host, int port , String resInfo , Date lastHeartbeatTime) { + + WorkerServer workerServer = new WorkerServer(); + + workerServer.setHost(host); + workerServer.setPort(port); + workerServer.setResInfo(resInfo); + workerServer.setLastHeartbeatTime(lastHeartbeatTime); + + return workerServerMapper.update(workerServer); + } + + + + /** + * delete worker by host + * + * @param host + * @return + */ + public int deleteWorker(String host) { + return workerServerMapper.deleteWorkerByHost(host); + } + +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/TaskRecordDao.java b/escheduler-dao/src/main/java/cn/escheduler/dao/TaskRecordDao.java new file mode 100644 index 0000000000..ebc206f9ac --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/TaskRecordDao.java @@ -0,0 +1,253 @@ +/* + * 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.dao; + +import cn.escheduler.common.Constants; +import cn.escheduler.dao.model.TaskRecord; +import org.apache.commons.configuration.Configuration; +import org.apache.commons.configuration.ConfigurationException; +import org.apache.commons.configuration.PropertiesConfiguration; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.sql.*; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + + +/** + * task record dao + */ +public class TaskRecordDao { + + + private static Logger logger = LoggerFactory.getLogger(TaskRecordDao.class.getName()); + + /** + * 加载配置文件 + */ + private static Configuration conf; + + static { + try { + conf = new PropertiesConfiguration(Constants.TASK_RECORD_PROPERTIES_PATH); + }catch (ConfigurationException e){ + logger.error("load configuration excetpion",e); + System.exit(1); + } + } + + /** + * create connection + * @return + */ + private static Connection getConn() { + if(!conf.getBoolean(Constants.TASK_RECORD_FLAG)){ + return null; + } + String driver = "com.mysql.jdbc.Driver"; + String url = conf.getString(Constants.TASK_RECORD_URL); + String username = conf.getString(Constants.TASK_RECORD_USER); + String password = conf.getString(Constants.TASK_RECORD_PWD); + Connection conn = null; + try { + //classLoader,加载对应驱动 + Class.forName(driver); + conn = DriverManager.getConnection(url, username, password); + } catch (ClassNotFoundException e) { + logger.error("Exception ", e); + } catch (SQLException e) { + logger.error("Exception ", e); + } + return conn; + } + + /** + * generate where sql string + * @param filterMap + * @return + */ + private static String getWhereString(Map filterMap) + { + if(filterMap.size() ==0){ + return ""; + } + + String result = " where 1=1 "; + + Object taskName = filterMap.get("taskName"); + if(taskName != null && StringUtils.isNotEmpty(taskName.toString())){ + result += " and PROC_NAME like concat('%', '" + taskName.toString() + "', '%') "; + } + + Object taskDate = filterMap.get("taskDate"); + if(taskDate != null && StringUtils.isNotEmpty(taskDate.toString())){ + result += " and PROC_DATE='" + taskDate.toString() + "'"; + } + + Object state = filterMap.get("state"); + if(state != null && StringUtils.isNotEmpty(state.toString())){ + result += " and NOTE='" + state.toString() + "'"; + } + + Object sourceTable = filterMap.get("sourceTable"); + if(sourceTable!= null && StringUtils.isNotEmpty(sourceTable.toString())){ + result += " and SOURCE_TAB like concat('%', '" + sourceTable.toString()+ "', '%')"; + } + + Object targetTable = filterMap.get("targetTable"); + if(sourceTable!= null && StringUtils.isNotEmpty(targetTable.toString())){ + result += " and TARGET_TAB like concat('%', '"+ targetTable.toString()+"', '%') " ; + } + + Object start = filterMap.get("startTime"); + if(start != null && StringUtils.isNotEmpty(start.toString())){ + result += " and STARTDATE>='" + start.toString() + "'"; + } + + Object end = filterMap.get("endTime"); + if(end != null && StringUtils.isNotEmpty(end.toString())){ + result += " and ENDDATE>='" + end.toString()+ "'"; + } + return result; + } + + /** + * count task record + * @param filterMap + * @return + */ + public static int countTaskRecord(Map filterMap){ + + int count = 0; + Connection conn = null; + try { + conn = getConn(); + if(conn == null){ + return count; + } + String sql = "select count(1) as count from eamp_hive_log_hd"; + sql += getWhereString(filterMap); + PreparedStatement pstmt; + pstmt = conn.prepareStatement(sql); + ResultSet rs = pstmt.executeQuery(); + while(rs.next()){ + count = rs.getInt("count"); + break; + } + } catch (SQLException e) { + logger.error("Exception ", e); + }finally { + try { + if(conn != null){ + conn.close(); + } + } catch (SQLException e) { + logger.error("Exception ", e); + } + } + return count; + } + + /** + * query task record by filter map paging + * @param filterMap + * @return + */ + public static List queryAllTaskRecord(Map filterMap ) { + + String sql = "select * from eamp_hive_log_hd "; + sql += getWhereString(filterMap); + + int offset = Integer.parseInt(filterMap.get("offset")); + int pageSize = Integer.parseInt(filterMap.get("pageSize")); + sql += String.format(" order by STARTDATE desc limit %d,%d", offset, pageSize); + + List recordList = new ArrayList<>(); + try{ + recordList = getQueryResult(sql); + }catch (Exception e){ + logger.error("Exception ", e); + } + return recordList; + } + + /** + * convert result set to task record + * @param resultSet + * @return + * @throws SQLException + */ + private static TaskRecord convertToTaskRecord(ResultSet resultSet) throws SQLException { + + TaskRecord taskRecord = new TaskRecord(); + taskRecord.setId(resultSet.getInt("ID")); + taskRecord.setProcId(resultSet.getInt("PROC_ID")); + taskRecord.setProcName(resultSet.getString("PROC_NAME")); + taskRecord.setProcDate(resultSet.getString("PROC_DATE")); + taskRecord.setStartDate(resultSet.getDate("STARTDATE")); + taskRecord.setEndDate(resultSet.getDate("ENDDATE")); + taskRecord.setResult(resultSet.getString("RESULT")); + taskRecord.setDuration(resultSet.getInt("DURATION")); + taskRecord.setNote(resultSet.getString("NOTE")); + taskRecord.setSchema(resultSet.getString("SCHEMA")); + taskRecord.setJobId(resultSet.getString("JOB_ID")); + taskRecord.setSourceTab(resultSet.getString("SOURCE_TAB")); + taskRecord.setSourceRowCount(resultSet.getLong("SOURCE_ROW_COUNT")); + taskRecord.setTargetTab(resultSet.getString("TARGET_TAB")); + taskRecord.setTargetRowCount(resultSet.getLong("TARGET_ROW_COUNT")); + taskRecord.setErrorCode(resultSet.getString("ERROR_CODE")); + return taskRecord; + } + + /** + * query task list by select sql + * @param selectSql + * @return + */ + private static List getQueryResult(String selectSql) { + List recordList = new ArrayList<>(); + Connection conn = null; + try { + conn = getConn(); + if(conn == null){ + return recordList; + } + PreparedStatement pstmt; + pstmt = conn.prepareStatement(selectSql); + ResultSet rs = pstmt.executeQuery(); + + while(rs.next()){ + TaskRecord taskRecord = convertToTaskRecord(rs); + recordList.add(taskRecord); + } + } catch (SQLException e) { + logger.error("Exception ", e); + }finally { + try { + if(conn != null){ + conn.close(); + } + } catch (SQLException e) { + logger.error("Exception ", e); + } + } + return recordList; + } +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/datasource/ConnectionFactory.java b/escheduler-dao/src/main/java/cn/escheduler/dao/datasource/ConnectionFactory.java new file mode 100644 index 0000000000..9b0b1f629a --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/datasource/ConnectionFactory.java @@ -0,0 +1,126 @@ +/* + * 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.dao.datasource; + +import cn.escheduler.common.Constants; +import cn.escheduler.common.utils.CommonUtils; +import cn.escheduler.dao.mapper.ProjectMapper; +import com.alibaba.druid.pool.DruidDataSource; +import org.apache.ibatis.mapping.Environment; +import org.apache.ibatis.session.Configuration; +import org.apache.ibatis.session.SqlSession; +import org.apache.ibatis.session.SqlSessionFactory; +import org.apache.ibatis.session.SqlSessionFactoryBuilder; +import org.apache.ibatis.transaction.TransactionFactory; +import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory; +import org.mybatis.spring.SqlSessionTemplate; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.sql.DataSource; +import java.sql.SQLException; + +import static cn.escheduler.dao.utils.PropertyUtils.*; + + +/** + * data source connection factory + */ +public class ConnectionFactory { + private static final Logger logger = LoggerFactory.getLogger(ConnectionFactory.class); + + private static SqlSessionFactory sqlSessionFactory; + + /** + * get the data source + */ + public static DruidDataSource getDataSource() { + DruidDataSource druidDataSource = new DruidDataSource(); + + druidDataSource.setDriverClassName(getString(Constants.SPRING_DATASOURCE_DRIVER_CLASS_NAME)); + druidDataSource.setUrl(getString(Constants.SPRING_DATASOURCE_URL)); + druidDataSource.setUsername(getString(Constants.SPRING_DATASOURCE_USERNAME)); + druidDataSource.setPassword(getString(Constants.SPRING_DATASOURCE_PASSWORD)); + druidDataSource.setValidationQuery(getString(Constants.SPRING_DATASOURCE_VALIDATION_QUERY)); + + druidDataSource.setPoolPreparedStatements(getBoolean(Constants.SPRING_DATASOURCE_POOL_PREPARED_STATEMENTS)); + druidDataSource.setTestWhileIdle(getBoolean(Constants.SPRING_DATASOURCE_TEST_WHILE_IDLE)); + druidDataSource.setTestOnBorrow(getBoolean(Constants.SPRING_DATASOURCE_TEST_ON_BORROW)); + druidDataSource.setTestOnReturn(getBoolean(Constants.SPRING_DATASOURCE_TEST_ON_RETURN)); + druidDataSource.setKeepAlive(getBoolean(Constants.SPRING_DATASOURCE_KEEP_ALIVE)); + //just for development + if (CommonUtils.isDevelopMode()) { + //Configure filters that are intercepted by monitoring statistics, and SQL can not be counted after removing them.'wall'is used for firewall + try { + druidDataSource.setFilters("stat,wall,log4j"); + } catch (SQLException e) { + logger.error(e.getMessage(), e); + } + } + + druidDataSource.setMinIdle(getInt(Constants.SPRING_DATASOURCE_MIN_IDLE)); + druidDataSource.setMaxActive(getInt(Constants.SPRING_DATASOURCE_MAX_ACTIVE)); + druidDataSource.setMaxWait(getInt(Constants.SPRING_DATASOURCE_MAX_WAIT)); + druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(getInt(Constants.SPRING_DATASOURCE_MAX_POOL_PREPARED_STATEMENT_PER_CONNECTION_SIZE)); + druidDataSource.setInitialSize(getInt(Constants.SPRING_DATASOURCE_INITIAL_SIZE)); + druidDataSource.setTimeBetweenEvictionRunsMillis(getLong(Constants.SPRING_DATASOURCE_TIME_BETWEEN_EVICTION_RUNS_MILLIS)); + druidDataSource.setTimeBetweenConnectErrorMillis(getLong(Constants.SPRING_DATASOURCE_TIME_BETWEEN_CONNECT_ERROR_MILLIS)); + druidDataSource.setMinEvictableIdleTimeMillis(getLong(Constants.SPRING_DATASOURCE_MIN_EVICTABLE_IDLE_TIME_MILLIS)); + druidDataSource.setValidationQueryTimeout(getInt(Constants.SPRING_DATASOURCE_VALIDATION_QUERY_TIMEOUT)); + //auto commit + druidDataSource.setDefaultAutoCommit(getBoolean(Constants.SPRING_DATASOURCE_DEFAULT_AUTO_COMMIT)); + + return druidDataSource; + } + + /** + * get sql session factory + */ + public static SqlSessionFactory getSqlSessionFactory() { + if (sqlSessionFactory == null) { + synchronized (ConnectionFactory.class) { + if (sqlSessionFactory == null) { + DataSource dataSource = getDataSource(); + TransactionFactory transactionFactory = new JdbcTransactionFactory(); + + Environment environment = new Environment(Constants.DEVELOPMENT, transactionFactory, dataSource); + + Configuration configuration = new Configuration(environment); + configuration.setLazyLoadingEnabled(true); + + configuration.addMappers(ProjectMapper.class.getPackage().getName()); + + SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); + sqlSessionFactory = builder.build(configuration); + } + } + } + + return sqlSessionFactory; + } + + /** + * get sql session + */ + public static SqlSession getSqlSession() { + return new SqlSessionTemplate(getSqlSessionFactory()); + } + + public static T getMapper(Class type){ + return getSqlSession().getMapper(type); + } +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/datasource/DatabaseConfiguration.java b/escheduler-dao/src/main/java/cn/escheduler/dao/datasource/DatabaseConfiguration.java new file mode 100644 index 0000000000..15760e5ddf --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/datasource/DatabaseConfiguration.java @@ -0,0 +1,63 @@ +/* + * 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.dao.datasource; + +import com.alibaba.druid.pool.DruidDataSource; +import org.apache.ibatis.session.SqlSessionFactory; +import org.mybatis.spring.SqlSessionFactoryBean; +import org.mybatis.spring.annotation.MapperScan; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; +import org.springframework.context.annotation.PropertySource; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.transaction.PlatformTransactionManager; + +import java.sql.SQLException; + +/** + * data base configuration + */ +@Configuration +@PropertySource({"classpath:dao/data_source.properties"}) +@MapperScan(basePackages = "cn.escheduler.dao.mapper", sqlSessionFactoryRef = "SqlSessionFactory") +public class DatabaseConfiguration { + + /** + * register data source + */ + @Primary + @Bean(name = "DataSource", initMethod = "init", destroyMethod = "close") + public DruidDataSource dataSource() { + return ConnectionFactory.getDataSource(); + } + + @Primary + @Bean(name = "SqlSessionFactory") + public SqlSessionFactory sqlSessionFactory() throws Exception { + SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); + sqlSessionFactoryBean.setDataSource(dataSource()); + + return sqlSessionFactoryBean.getObject(); + } + + @Primary + @Bean(name = "TransactionManager") + public PlatformTransactionManager transactionManager() throws SQLException { + return new DataSourceTransactionManager(dataSource()); + } +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/AlertGroupMapper.java b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/AlertGroupMapper.java new file mode 100644 index 0000000000..20c37b452b --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/AlertGroupMapper.java @@ -0,0 +1,149 @@ +/* + * 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.dao.mapper; + +import cn.escheduler.common.enums.AlertType; +import cn.escheduler.dao.model.AlertGroup; +import org.apache.ibatis.annotations.*; +import org.apache.ibatis.type.EnumOrdinalTypeHandler; +import org.apache.ibatis.type.JdbcType; + +import java.sql.Timestamp; +import java.util.List; + +/** + * alert group mapper + */ +public interface AlertGroupMapper { + /** + * insert warning group + * @param alertGroup + * @return + */ + @InsertProvider(type = AlertGroupMapperProvider.class, method = "insert") + @Options(useGeneratedKeys = true,keyProperty = "alertGroup.id") + @SelectKey(statement = "SELECT LAST_INSERT_ID()", keyProperty = "alertGroup.id", before = false, resultType = int.class) + int insert(@Param("alertGroup") AlertGroup alertGroup); + + + /** + * delete alert group by id + * @param id + * @return + */ + @DeleteProvider(type = AlertGroupMapperProvider.class, method = "delete") + int delete(@Param("id") int id); + + + /** + * update alert group information + * @param alertGroup + * @return + */ + @UpdateProvider(type = AlertGroupMapperProvider.class, method = "update") + int update(@Param("alertGroup") AlertGroup alertGroup); + + + /** + * query alert group by id + * @param alertGroupId + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "groupName", column = "group_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "groupType", column = "group_type", typeHandler = EnumOrdinalTypeHandler.class, javaType = AlertType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "desc", column = "desc", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "createTime", column = "create_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "updateTime", column = "update_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE) + }) + @SelectProvider(type = AlertGroupMapperProvider.class, method = "queryById") + AlertGroup queryById(@Param("alertGroupId") int alertGroupId); + + + /** + * query all alert group list + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "groupName", column = "group_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "groupType", column = "group_type", typeHandler = EnumOrdinalTypeHandler.class, javaType = AlertType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "desc", column = "desc", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "createTime", column = "create_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "updateTime", column = "update_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE) + }) + @SelectProvider(type = AlertGroupMapperProvider.class, method = "queryAllGroupList") + List queryAllGroupList(); + + /** + * count alert group + * @param searchVal + * @return + */ + @SelectProvider(type = AlertGroupMapperProvider.class, method = "countAlertGroupPaging") + Integer countAlertGroupPaging(@Param("searchVal") String searchVal); + + /** + * query alert groups paging + * @param searchVal + * @param offset + * @param pageSize + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "groupName", column = "group_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "groupType", column = "group_type", typeHandler = EnumOrdinalTypeHandler.class, javaType = AlertType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "desc", column = "desc", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "createTime", column = "create_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "updateTime", column = "update_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE) + }) + @SelectProvider(type = AlertGroupMapperProvider.class, method = "queryAlertGroupPaging") + List queryAlertGroupPaging(@Param("searchVal") String searchVal, + @Param("offset") Integer offset, + @Param("pageSize") Integer pageSize); + + /** + * query alert group by user id + * @param userId + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "groupName", column = "group_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "groupType", column = "group_type", typeHandler = EnumOrdinalTypeHandler.class, javaType = AlertType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "desc", column = "desc", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "createTime", column = "create_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "updateTime", column = "update_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE) + }) + @SelectProvider(type = AlertGroupMapperProvider.class, method = "queryByUserId") + List queryByUserId(@Param("userId") int userId); + + + + /** + * query alert group by name + * @param groupName + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "groupName", column = "group_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "groupType", column = "group_type", typeHandler = EnumOrdinalTypeHandler.class, javaType = AlertType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "desc", column = "desc", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "createTime", column = "create_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "updateTime", column = "update_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE) + }) + @SelectProvider(type = AlertGroupMapperProvider.class, method = "queryByGroupName") + AlertGroup queryByGroupName(@Param("groupName") String groupName); +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/AlertGroupMapperProvider.java b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/AlertGroupMapperProvider.java new file mode 100644 index 0000000000..af75c15989 --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/AlertGroupMapperProvider.java @@ -0,0 +1,194 @@ +/* + * 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.dao.mapper; + +import cn.escheduler.common.enums.AlertType; +import cn.escheduler.common.utils.EnumFieldUtil; +import org.apache.commons.lang3.StringUtils; +import org.apache.ibatis.jdbc.SQL; + +import java.util.Map; + +/** + * alert group mapper provider + */ +public class AlertGroupMapperProvider { + + private static final String TABLE_NAME = "t_escheduler_alertgroup"; + + /** + * insert one alert group + * @param parameter + * @return + */ + public String insert(Map parameter) { + return new SQL() { + { + INSERT_INTO(TABLE_NAME); + VALUES("`group_name`", "#{alertGroup.groupName}"); + VALUES("`group_type`", EnumFieldUtil.genFieldStr("alertGroup.groupType", AlertType.class)); + VALUES("`desc`", "#{alertGroup.desc}"); + VALUES("`create_time`", "#{alertGroup.createTime}"); + VALUES("`update_time`", "#{alertGroup.updateTime}"); + } + }.toString(); + } + + /** + * delete alert group by id + * @param parameter + * @return + */ + public String delete(Map parameter) { + return new SQL() { + { + DELETE_FROM(TABLE_NAME); + + WHERE("`id`=#{id}"); + } + }.toString(); + } + + /** + * update alert group + * @param parameter + * @return + */ + public String update(Map parameter) { + return new SQL() { + { + UPDATE(TABLE_NAME); + + SET("`group_name`=#{alertGroup.groupName}"); + SET("`group_type`="+EnumFieldUtil.genFieldStr("alertGroup.groupType", AlertType.class)); + SET("`desc`=#{alertGroup.desc}"); + SET("`update_time`=#{alertGroup.updateTime}"); + + WHERE("`id`=#{alertGroup.id}"); + } + }.toString(); + } + + + /** + * query alert group by id + * @param parameter + * @return + */ + public String queryById(Map parameter) { + return new SQL() { + { + SELECT("*"); + + FROM(TABLE_NAME); + + WHERE("`id` = #{alertGroupId}"); + } + }.toString(); + } + + /** + * query all alert group list + * @param parameter + * @return + */ + public String queryAllGroupList(Map parameter) { + return new SQL() { + { + SELECT("*"); + + FROM(TABLE_NAME); + + ORDER_BY( "update_time desc"); + + } + }.toString(); + } + + /** + * count alert group by search key + * @param parameter + * @return + */ + public String countAlertGroupPaging(Map parameter) { + return new SQL() {{ + SELECT("count(0)"); + + FROM(TABLE_NAME); + + Object searchVal = parameter.get("searchVal"); + if(searchVal != null && StringUtils.isNotEmpty(searchVal.toString())){ + WHERE( " group_name like concat('%', #{searchVal}, '%') "); + } + }}.toString(); + } + + /** + * query alert group list paging by search key + * @param parameter + * @return + */ + public String queryAlertGroupPaging(Map parameter) { + return new SQL() { + { + SELECT("*"); + FROM(TABLE_NAME); + Object searchVal = parameter.get("searchVal"); + if(searchVal != null && StringUtils.isNotEmpty(searchVal.toString())){ + WHERE( " group_name like concat('%', #{searchVal}, '%') "); + } + ORDER_BY(" update_time desc limit #{offset},#{pageSize} "); + } + }.toString(); + + } + + + /** + * query alert group by user id + * @param parameter + * @return + */ + public String queryByUserId(Map parameter) { + return new SQL() { + { + SELECT("g.*"); + + FROM(TABLE_NAME + " g,t_escheduler_relation_user_alertgroup rel"); + + WHERE("rel.alertgroup_id = g.id and rel.user_id = #{userId}"); + } + }.toString(); + } + + + /** + * query alert group by name + * @param parameter + * @return + */ + public String queryByGroupName(Map parameter) { + return new SQL() { + { + SELECT("*"); + FROM(TABLE_NAME); + WHERE("group_name = #{groupName}"); + } + }.toString(); + } + +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/AlertMapper.java b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/AlertMapper.java new file mode 100644 index 0000000000..0a7bb12ed9 --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/AlertMapper.java @@ -0,0 +1,107 @@ +/* + * 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.dao.mapper; + +import cn.escheduler.common.enums.AlertStatus; +import cn.escheduler.common.enums.AlertType; +import cn.escheduler.common.enums.ShowType; +import cn.escheduler.dao.model.Alert; +import org.apache.ibatis.annotations.*; +import org.apache.ibatis.type.EnumOrdinalTypeHandler; +import org.apache.ibatis.type.JdbcType; + +import java.sql.Timestamp; +import java.util.Date; +import java.util.List; + +public interface AlertMapper { + + /** + * insert alert information + * @param alert + * @return + */ + @InsertProvider(type = AlertMapperProvider.class, method = "insert") + @Options(useGeneratedKeys = true,keyProperty = "alert.id") + @SelectKey(statement = "SELECT LAST_INSERT_ID()", keyProperty = "alert.id", before = false, resultType = int.class) + int insert(@Param("alert") Alert alert); + + + /** + * query alert list by status + * @param alertStatus + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "title", column = "title", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "showType", column = "show_type", typeHandler = EnumOrdinalTypeHandler.class, javaType = ShowType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "content", column = "content", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "alertType", column = "alert_type", typeHandler = EnumOrdinalTypeHandler.class, javaType = AlertType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "alertStatus", column = "alert_status", typeHandler = EnumOrdinalTypeHandler.class, javaType = AlertStatus.class, jdbcType = JdbcType.TINYINT), + @Result(property = "log", column = "log", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "alertGroupId", column = "alertgroup_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "receivers", column = "receivers", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "receiversCc", column = "receivers_cc", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "createTime", column = "create_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "updateTime", column = "update_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE) + }) + @SelectProvider(type = AlertMapperProvider.class, method = "queryAlertByStatus") + List queryAlertByStatus(@Param("alertStatus") AlertStatus alertStatus); + + + /** + * update alert information + * @param alertStatus + * @param log + * @param updateTime + * @param id + * @return + */ + @UpdateProvider(type = AlertMapperProvider.class, method = "update") + int update(@Param("alertStatus") AlertStatus alertStatus,@Param("log") String log, + @Param("updateTime") Date updateTime,@Param("id") int id); + + /** + * delete by alert id + * @param alertId + * @return + */ + @UpdateProvider(type = AlertMapperProvider.class, method = "deleteById") + int delete(@Param("alertId") int alertId); + + /** + * list alert information by field alertStatus + * @param alertStatus + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "title", column = "title", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "showType", column = "show_type", typeHandler = EnumOrdinalTypeHandler.class, javaType = ShowType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "content", column = "content", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "alertType", column = "alert_type", typeHandler = EnumOrdinalTypeHandler.class, javaType = AlertType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "alertStatus", column = "alert_status", typeHandler = EnumOrdinalTypeHandler.class, javaType = AlertStatus.class, jdbcType = JdbcType.TINYINT), + @Result(property = "log", column = "log", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "alertGroupId", column = "alertgroup_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "receivers", column = "receivers", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "receiversCc", column = "receivers_cc", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "createTime", column = "create_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "updateTime", column = "update_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE) + }) + @SelectProvider(type = AlertMapperProvider.class, method = "listAlertByStatus") + List listAlertByStatus(@Param("alertStatus") AlertStatus alertStatus); + +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/AlertMapperProvider.java b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/AlertMapperProvider.java new file mode 100644 index 0000000000..e739bdbf26 --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/AlertMapperProvider.java @@ -0,0 +1,121 @@ +/* + * 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.dao.mapper; + +import cn.escheduler.common.enums.AlertStatus; +import cn.escheduler.common.enums.AlertType; +import cn.escheduler.common.enums.ShowType; +import cn.escheduler.common.utils.EnumFieldUtil; +import org.apache.ibatis.jdbc.SQL; + +import java.util.Map; + +public class AlertMapperProvider { + + private static final String TABLE_NAME = "t_escheduler_alert"; + + /** + * 插入告警信息 + * + * @param parameter + * @return + */ + public String insert(Map parameter) { + return new SQL() { + { + INSERT_INTO(TABLE_NAME); + VALUES("`title`", "#{alert.title}"); + VALUES("`show_type`", EnumFieldUtil.genFieldStr("alert.showType", ShowType.class)); + VALUES("`content`", "#{alert.content}"); + VALUES("`alert_type`", EnumFieldUtil.genFieldStr("alert.alertType", AlertType.class)); + VALUES("`alertgroup_id`", "#{alert.alertGroupId}"); + VALUES("`receivers`", "#{alert.receivers}"); + VALUES("`receivers_cc`", "#{alert.receiversCc}"); + VALUES("`create_time`", "#{alert.createTime}"); + VALUES("`update_time`", "#{alert.updateTime}"); + } + }.toString(); + } + + /** + * 根据告警状态查询 + * @param parameter + * @return + */ + public String queryAlertByStatus(Map parameter) { + return new SQL() { + { + SELECT("*"); + + FROM(TABLE_NAME); + + WHERE("`alert_status` = "+EnumFieldUtil.genFieldStr("alertStatus", AlertStatus.class)); + } + }.toString(); + } + + /** + * delete by id + * @param parameter + * @return + */ + public String deleteById(Map parameter){ + + return new SQL() { + { + DELETE_FROM(TABLE_NAME); + WHERE("`id`=#{alertId}"); + + }}.toString(); + } + + /** + * 更新消息信息 + * + * @param parameter + * @return + */ + public String update(Map parameter) { + return new SQL() { + { + UPDATE(TABLE_NAME); + SET("`alert_status`="+EnumFieldUtil.genFieldStr("alertStatus", AlertType.class)); + SET("`log`=#{log}"); + SET("`update_time`=#{updateTime}"); + + WHERE("`id` = #{id}"); + } + }.toString(); + } + + /** + * list alert information by field alertStatus + * @param parameter + * @return + */ + public String listAlertByStatus(Map parameter) { + return new SQL() { + { + SELECT("*"); + + FROM(TABLE_NAME); + + WHERE("`alert_status` = "+EnumFieldUtil.genFieldStr("alertStatus", AlertStatus.class)); + } + }.toString(); + } +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/CommandMapper.java b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/CommandMapper.java new file mode 100644 index 0000000000..4f5e371ed4 --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/CommandMapper.java @@ -0,0 +1,106 @@ +/* + * 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.dao.mapper; + +import cn.escheduler.common.enums.*; +import cn.escheduler.dao.model.Command; +import org.apache.ibatis.annotations.*; +import org.apache.ibatis.type.EnumOrdinalTypeHandler; +import org.apache.ibatis.type.JdbcType; + +import java.sql.Timestamp; +import java.util.List; + +/** + * command mapper + */ +public interface CommandMapper { + + /** + * inert command + * @param command + * @return + */ + @InsertProvider(type = CommandMapperProvider.class, method = "insert") + @Options(useGeneratedKeys = true,keyProperty = "command.id") + @SelectKey(statement = "SELECT LAST_INSERT_ID()", keyProperty = "command.id", before = false, resultType = int.class) + int insert(@Param("command") Command command); + + + /** + * delete command + * @param cmdId + * @return + */ + @DeleteProvider(type = CommandMapperProvider.class, method = "delete") + int delete(@Param("cmdId") int cmdId); + + + /** + * update command + * + * @param command + * @return + */ + @UpdateProvider(type = CommandMapperProvider.class, method = "update") + int update(@Param("command") Command command); + + + /** + * query a command that can run normally + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "commandType", column = "command_type", typeHandler = EnumOrdinalTypeHandler.class, javaType = CommandType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "processDefinitionId", column = "process_definition_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "executorId", column = "executor_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "commandParam", column = "command_param", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "taskDependType", column = "task_depend_type", javaType = TaskDependType.class, typeHandler = EnumOrdinalTypeHandler.class, jdbcType = JdbcType.TINYINT), + @Result(property = "failureStrategy", column = "failure_strategy", javaType = FailureStrategy.class, typeHandler = EnumOrdinalTypeHandler.class, jdbcType = JdbcType.TINYINT), + @Result(property = "warningType", column = "warning_type", javaType = WarningType.class, typeHandler = EnumOrdinalTypeHandler.class, jdbcType = JdbcType.TINYINT), + @Result(property = "warningGroupId", column = "warning_group_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "scheduleTime", column = "schedule_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "updateTime", column = "update_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "startTime", column = "start_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "processInstancePriority", column = "process_instance_priority", javaType = Priority.class, typeHandler = EnumOrdinalTypeHandler.class, jdbcType = JdbcType.TINYINT) + }) + @SelectProvider(type = CommandMapperProvider.class, method = "queryOneCommand") + Command queryOneCommand(); + + + /** + * query all commands + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "commandType", column = "command_type", typeHandler = EnumOrdinalTypeHandler.class, javaType = CommandType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "processDefinitionId", column = "process_definition_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "executorId", column = "executor_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "commandParam", column = "command_param", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "taskDependType", column = "task_depend_type", javaType = TaskDependType.class, typeHandler = EnumOrdinalTypeHandler.class, jdbcType = JdbcType.TINYINT), + @Result(property = "failureStrategy", column = "failure_strategy", javaType = FailureStrategy.class, typeHandler = EnumOrdinalTypeHandler.class, jdbcType = JdbcType.TINYINT), + @Result(property = "warningType", column = "warning_type", javaType = WarningType.class, typeHandler = EnumOrdinalTypeHandler.class, jdbcType = JdbcType.TINYINT), + @Result(property = "warningGroupId", column = "warning_group_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "scheduleTime", column = "schedule_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "updateTime", column = "update_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "startTime", column = "start_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "processInstancePriority", column = "process_instance_priority", javaType = Priority.class, typeHandler = EnumOrdinalTypeHandler.class, jdbcType = JdbcType.TINYINT) + }) + @SelectProvider(type = CommandMapperProvider.class, method = "queryAllCommand") + List queryAllCommand(); + +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/CommandMapperProvider.java b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/CommandMapperProvider.java new file mode 100644 index 0000000000..8f11c8af26 --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/CommandMapperProvider.java @@ -0,0 +1,144 @@ +/* + * 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.dao.mapper; + +import cn.escheduler.common.enums.*; +import cn.escheduler.common.utils.EnumFieldUtil; +import org.apache.ibatis.jdbc.SQL; + +import java.util.Map; + + +/** + * command mapper provider + */ +public class CommandMapperProvider { + private static final String TABLE_NAME = "t_escheduler_command"; + private static final String DEFINE_TABLE_NAME = "t_escheduler_process_definition"; + + /** + * inert command + * + * @param parameter + * @return + */ + public String insert(Map parameter) { + return new SQL() { + { + INSERT_INTO(TABLE_NAME); + VALUES("`command_type`", EnumFieldUtil.genFieldStr("command.commandType", CommandType.class)); + VALUES("`process_definition_id`", "#{command.processDefinitionId}"); + VALUES("`executor_id`", "#{command.executorId}"); + VALUES("`command_param`", "#{command.commandParam}"); + VALUES("`task_depend_type`", EnumFieldUtil.genFieldStr("command.taskDependType", TaskDependType.class)); + VALUES("`failure_strategy`", EnumFieldUtil.genFieldStr("command.failureStrategy", FailureStrategy.class)); + VALUES("`warning_type`", EnumFieldUtil.genFieldStr("command.warningType", WarningType.class)); + VALUES("`process_instance_priority`", EnumFieldUtil.genFieldStr("command.processInstancePriority", Priority.class)); + VALUES("`warning_group_id`", "#{command.warningGroupId}"); + VALUES("`schedule_time`", "#{command.scheduleTime}"); + VALUES("`update_time`", "#{command.updateTime}"); + VALUES("`start_time`", "#{command.startTime}"); + + } + }.toString(); + } + + /** + * delete command + * + * @param parameter + * @return + */ + public String delete(Map parameter) { + return new SQL() { + { + DELETE_FROM(TABLE_NAME); + + WHERE("`id`=#{cmdId}"); + } + }.toString(); + } + + /** + * update command + * + * @param parameter + * @return + */ + public String update(Map parameter) { + return new SQL() { + { + UPDATE(TABLE_NAME); + + SET("`command_type`=" + EnumFieldUtil.genFieldStr("command.commandType", CommandType.class)); + SET("`process_definition_id`=#{command.processDefinitionId}"); + SET("`executor_id`=#{command.executorId}"); + SET("`command_param`=#{command.commandParam}"); + SET("`task_depend_type`="+ EnumFieldUtil.genFieldStr("command.taskDependType", TaskDependType.class)); + SET("`failure_strategy`="+ EnumFieldUtil.genFieldStr("command.failureStrategy", FailureStrategy.class)); + SET("`warning_type`="+ EnumFieldUtil.genFieldStr("command.warningType", WarningType.class)); + SET("`process_instance_priority`="+ EnumFieldUtil.genFieldStr("command.processInstancePriority", Priority.class)); + SET("`warning_group_id`=#{command.warningGroupId}"); + SET("`schedule_time`=#{command.scheduleTime}"); + SET("`update_time`=#{command.updateTime}"); + SET("`start_time`=#{command.startTime}"); + + WHERE("`id`=#{command.id}"); + } + }.toString(); + } + + /** + * query a command that can run normally + * command must be release on line, usable. + * @param parameter + * @return + */ + public String queryOneCommand(Map parameter) { + return new SQL() { + { + SELECT("cmd.*,process_define.id as process_definition_id"); + + FROM(TABLE_NAME + " cmd"); + + JOIN( DEFINE_TABLE_NAME + " process_define ON cmd.process_definition_id = process_define.id"); + WHERE("process_define.release_state =1 AND process_define.flag = 1"); + ORDER_BY("update_time asc"); + + + } + }.toString() + " limit 1"; + } + + /** + * query all commands + * @param parameter + * @return + */ + public String queryAllCommand(Map parameter) { + return new SQL() { + { + SELECT("cmd.*"); + + FROM(TABLE_NAME + " cmd"); + } + }.toString(); + } + + + +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/DataSourceMapper.java b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/DataSourceMapper.java new file mode 100644 index 0000000000..149d15e662 --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/DataSourceMapper.java @@ -0,0 +1,219 @@ +/* + * 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.dao.mapper; + +import cn.escheduler.common.enums.DbType; +import cn.escheduler.dao.model.DataSource; +import org.apache.ibatis.annotations.*; +import org.apache.ibatis.type.EnumOrdinalTypeHandler; +import org.apache.ibatis.type.JdbcType; + +import java.sql.Timestamp; +import java.util.List; + +/** + * data source mapper + */ +public interface DataSourceMapper { + /** + * insert data source + * + * @param dataSource + * @return + */ + @InsertProvider(type = DataSourceMapperProvider.class, method = "insert") + @SelectKey(statement = "SELECT LAST_INSERT_ID() as id", resultType = Integer.class, keyProperty = "dataSource.id", before = false) + int insert(@Param("dataSource") DataSource dataSource); + + /** + * update data source + * + * @param dataSource + * @return + */ + @UpdateProvider(type = DataSourceMapperProvider.class, method = "update") + int update(@Param("dataSource") DataSource dataSource); + + /** + * delete data source by id + * + * @param id + * @return + */ + @DeleteProvider(type = DataSourceMapperProvider.class, method = "deleteDataSourceById") + int deleteDataSourceById(@Param("id") int id); + + /** + * query data source list by type + * @param userId + * @param type + * @return + */ + @Results(value = { + @Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "name", column = "name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "note", column = "note", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "type", column = "type", typeHandler = EnumOrdinalTypeHandler.class, javaType = DbType.class, jdbcType = JdbcType.INTEGER), + @Result(property = "connectionParams", column = "connection_params", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "createTime", column = "create_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "updateTime", column = "update_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE) + }) + @SelectProvider(type = DataSourceMapperProvider.class, method = "queryDataSourceByType") + List queryDataSourceByType(@Param("userId") int userId, @Param("type") Integer type); + + /** + * query data source by id + * + * @param id + * @return + */ + @Results(value = { + @Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "name", column = "name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "note", column = "note", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "type", column = "type", typeHandler = EnumOrdinalTypeHandler.class, javaType = DbType.class, jdbcType = JdbcType.INTEGER), + @Result(property = "userName", column = "user_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "userId", column = "user_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "projectId", column = "project_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "projectName", column = "project_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "connectionParams", column = "connection_params", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "createTime", column = "create_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "updateTime", column = "update_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE) + }) + @SelectProvider(type = DataSourceMapperProvider.class, method = "queryById") + DataSource queryById(@Param("id") Integer id); + + /** + * count data source by user id + * + * @param userId + * @return + */ + @SelectProvider(type = DataSourceMapperProvider.class, method = "countUserDatasource") + int countUserDatasource(@Param("userId") int userId); + + /** + * count data source number + * + * @return + */ + @SelectProvider(type = DataSourceMapperProvider.class, method = "countAllDatasource") + int countAllDatasource(); + + /** + * query data source list paging + * + * @param userId + * @param searchVal + * @param offset + * @param pageSize + * @return + */ + @Results(value = { + @Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "name", column = "name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "note", column = "note", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "type", column = "type", typeHandler = EnumOrdinalTypeHandler.class, javaType = DbType.class, jdbcType = JdbcType.INTEGER), + @Result(property = "userId", column = "user_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "connectionParams", column = "connection_params", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "createTime", column = "create_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "updateTime", column = "update_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE) + }) + @SelectProvider(type = DataSourceMapperProvider.class, method = "queryDataSourcePaging") + List queryDataSourcePaging(@Param("userId") int userId, @Param("searchVal") String searchVal, + @Param("offset") int offset, + @Param("pageSize") int pageSize); + + /** + * query data source list paging + * + * @param searchVal + * @param offset + * @param pageSize + * @return + */ + @Results(value = { + @Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "name", column = "name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "note", column = "note", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "type", column = "type", typeHandler = EnumOrdinalTypeHandler.class, javaType = DbType.class, jdbcType = JdbcType.INTEGER), + @Result(property = "userId", column = "user_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "connectionParams", column = "connection_params", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "createTime", column = "create_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "updateTime", column = "update_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE) + }) + @SelectProvider(type = DataSourceMapperProvider.class, method = "queryAllDataSourcePaging") + List queryAllDataSourcePaging(@Param("searchVal") String searchVal, + @Param("offset") int offset, + @Param("pageSize") int pageSize); + + /** + * query data source by name + * @param name + * @return + */ + @Results(value = { + @Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "name", column = "name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "note", column = "note", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "type", column = "type", typeHandler = EnumOrdinalTypeHandler.class, javaType = DbType.class, jdbcType = JdbcType.INTEGER), + @Result(property = "userId", column = "user_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "connectionParams", column = "connection_params", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "createTime", column = "create_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "updateTime", column = "update_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE) + }) + @SelectProvider(type = DataSourceMapperProvider.class, method = "queryDataSourceByName") + List queryDataSourceByName(@Param("name") String name); + + /** + * authed data source to user + * @param userId + * @return + */ + @Results(value = { + @Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "name", column = "name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "note", column = "note", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "type", column = "type", typeHandler = EnumOrdinalTypeHandler.class, javaType = DbType.class, jdbcType = JdbcType.INTEGER), + @Result(property = "userId", column = "user_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "connectionParams", column = "connection_params", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "createTime", column = "create_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "updateTime", column = "update_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE) + }) + @SelectProvider(type = DataSourceMapperProvider.class, method = "authedDatasource") + List authedDatasource(@Param("userId") int userId); + + + /** + * query data source except user + * @param userId + * @return + */ + @Results(value = { + @Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "name", column = "name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "note", column = "note", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "type", column = "type", typeHandler = EnumOrdinalTypeHandler.class, javaType = DbType.class, jdbcType = JdbcType.INTEGER), + @Result(property = "userId", column = "user_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "connectionParams", column = "connection_params", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "createTime", column = "create_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "updateTime", column = "update_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE) + }) + @SelectProvider(type = DataSourceMapperProvider.class, method = "queryDatasourceExceptUserId") + List queryDatasourceExceptUserId(@Param("userId") int userId); + +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/DataSourceMapperProvider.java b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/DataSourceMapperProvider.java new file mode 100644 index 0000000000..20203da5c6 --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/DataSourceMapperProvider.java @@ -0,0 +1,231 @@ +/* + * 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.dao.mapper; + +import cn.escheduler.common.enums.DbType; +import cn.escheduler.common.utils.EnumFieldUtil; +import org.apache.commons.lang3.StringUtils; +import org.apache.ibatis.jdbc.SQL; + +import java.text.MessageFormat; +import java.util.Map; + +/** + * data source mapper provider + */ +public class DataSourceMapperProvider { + + public static final String TABLE_NAME = "t_escheduler_datasource"; + public static final String USER_TABLE_NAME = "t_escheduler_user"; + public static final String PROJECT_TABLE_NAME = "t_escheduler_project"; + public static final String USER_DATASOURCE_RELATION_TABLE_NAME = "t_escheduler_relation_datasource_user"; + + /** + * insert data source + * + * @param parameter + * @return + */ + public String insert(Map parameter) { + return new SQL() {{ + INSERT_INTO(TABLE_NAME); + + VALUES("`name`", "#{dataSource.name}"); + VALUES("`note`", "#{dataSource.note}"); + VALUES("`type`", EnumFieldUtil.genFieldStr("dataSource.type", DbType.class)); + VALUES("`user_id`", "#{dataSource.userId}"); + VALUES("`connection_params`", "#{dataSource.connectionParams}"); + VALUES("`create_time`", "#{dataSource.createTime}"); + VALUES("`update_time`", "#{dataSource.updateTime}"); + }}.toString(); + } + + /** + * + * update data source + * @param parameter + * @return + */ + public String update(Map parameter) { + return new SQL() {{ + UPDATE(TABLE_NAME); + + SET("`name` = #{dataSource.name}"); + SET("`note` = #{dataSource.note}"); + SET("`user_id` = #{dataSource.userId}"); + SET("`type` = "+ EnumFieldUtil.genFieldStr("dataSource.type", DbType.class)); + SET("`connection_params` = #{dataSource.connectionParams}"); + SET("`update_time` = #{dataSource.updateTime}"); + + WHERE("`id` = #{dataSource.id}"); + }}.toString(); + } + + /** + * delete datasource by id + * @param parameter + * @return + */ + public String deleteDataSourceById(Map parameter) { + return new SQL() {{ + DELETE_FROM(TABLE_NAME); + + WHERE("`id` = #{id}"); + }}.toString(); + } + + + /** + * query datasource list by type + * @param parameter + * @return + */ + public String queryDataSourceByType(Map parameter) { + return new SQL() {{ + SELECT("*"); + FROM(TABLE_NAME ); + WHERE("type = #{type}"); + WHERE("id in (select datasource_id from "+USER_DATASOURCE_RELATION_TABLE_NAME+" where user_id=#{userId} union select id as datasource_id from "+TABLE_NAME+" where user_id=#{userId})"); + }}.toString(); + } + + /** + * query data source by id + * + * @param parameter + * @return + */ + public String queryById(Map parameter) { + return new SQL() {{ + SELECT("r.*,u.user_name as userName"); + + FROM(TABLE_NAME + " r"); + + JOIN(new MessageFormat("{0} as u on u.id = r.user_id").format(new Object[]{USER_TABLE_NAME})); + + WHERE("r.id = #{id}"); + }}.toString(); + } + + /** + * query data source paging + * @param parameter + * @return + */ + public String queryDataSourcePaging(Map parameter) { + return new SQL() {{ + SELECT("*"); + FROM(TABLE_NAME ); + WHERE("id in (select datasource_id from "+USER_DATASOURCE_RELATION_TABLE_NAME+" where user_id=#{userId} union select id as datasource_id from "+TABLE_NAME+" where user_id=#{userId})"); + Object searchVal = parameter.get("searchVal"); + if(searchVal != null && StringUtils.isNotEmpty(searchVal.toString())){ + WHERE( " name like concat('%', #{searchVal}, '%') "); + } + ORDER_BY("update_time desc limit #{offset},#{pageSize} "); + + }}.toString(); + } + + /** + * + * query data source list paging + * @param parameter + * @return + */ + public String queryAllDataSourcePaging(Map parameter) { + return new SQL() {{ + SELECT("*"); + FROM(TABLE_NAME ); + Object searchVal = parameter.get("searchVal"); + if(searchVal != null && StringUtils.isNotEmpty(searchVal.toString())){ + WHERE( " name like concat('%', #{searchVal}, '%') "); + } + ORDER_BY("update_time desc limit #{offset},#{pageSize} "); + + }}.toString(); + } + + /** + * count data source by user id + * + * @param parameter + * @return + */ + public String countUserDatasource(Map parameter) { + return new SQL() {{ + SELECT("count(0)"); + + FROM(TABLE_NAME); + WHERE("id in (select datasource_id from "+USER_DATASOURCE_RELATION_TABLE_NAME+" where user_id=#{userId} union select id as datasource_id from "+TABLE_NAME+" where user_id=#{userId})"); + }}.toString(); + } + + /** + * 查询总的数据源数目 + * + * @param parameter + * @return + */ + public String countAllDatasource(Map parameter) { + return new SQL() {{ + SELECT("count(0)"); + FROM(TABLE_NAME); + }}.toString(); + } + + /** + * query data source by name + * @param parameter + * @return + */ + public String queryDataSourceByName(Map parameter) { + return new SQL() {{ + SELECT("*"); + FROM(TABLE_NAME ); + WHERE("name = #{name}"); + }}.toString(); + } + + /** + * authed data source to user + * + * @param parameter + * @return + */ + public String authedDatasource(Map parameter) { + return new SQL() {{ + SELECT("d.*"); + FROM(TABLE_NAME + " d,t_escheduler_relation_datasource_user rel"); + WHERE(" d.id = rel.datasource_id AND rel.user_id = #{userId}"); + }}.toString(); + } + + + /** + * query data source except user + * + * @param parameter + * @return + */ + public String queryDatasourceExceptUserId(Map parameter) { + return new SQL() {{ + SELECT("*"); + FROM(TABLE_NAME); + WHERE("user_id <> #{userId}"); + }}.toString(); + } +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/DatasourceUserMapper.java b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/DatasourceUserMapper.java new file mode 100644 index 0000000000..6d12ce6d97 --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/DatasourceUserMapper.java @@ -0,0 +1,55 @@ +/* + * 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.dao.mapper; + +import cn.escheduler.dao.model.DatasourceUser; +import org.apache.ibatis.annotations.DeleteProvider; +import org.apache.ibatis.annotations.InsertProvider; +import org.apache.ibatis.annotations.Param; + +/** + * data source user relation mapper + */ +public interface DatasourceUserMapper { + /** + * insert data source user relation + * + * @param datasourceUser + * @return + */ + @InsertProvider(type = DatasourceUserMapperProvider.class, method = "insert") + int insert(@Param("datasourceUser") DatasourceUser datasourceUser); + + + /** + * delete data source user relation by user id + * + * @param userId + * @return + */ + @DeleteProvider(type = DatasourceUserMapperProvider.class, method = "deleteByUserId") + int deleteByUserId(@Param("userId") int userId); + + /** + * delete by data source id + * @param datasourceId + * @return + */ + @DeleteProvider(type = DatasourceUserMapperProvider.class, method = "deleteByDatasourceId") + int deleteByDatasourceId(@Param("datasourceId") int datasourceId); + +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/DatasourceUserMapperProvider.java b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/DatasourceUserMapperProvider.java new file mode 100644 index 0000000000..7010e26303 --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/DatasourceUserMapperProvider.java @@ -0,0 +1,69 @@ +/* + * 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.dao.mapper; + +import org.apache.ibatis.jdbc.SQL; + +import java.util.Map; + +public class DatasourceUserMapperProvider { + + private static final String TABLE_NAME = "t_escheduler_relation_datasource_user"; + + /** + * + * @param parameter + * @return + */ + public String insert(Map parameter) { + return new SQL() {{ + INSERT_INTO(TABLE_NAME); + + VALUES("`datasource_id`", "#{datasourceUser.datasourceId}"); + VALUES("`user_id`", "#{datasourceUser.userId}"); + VALUES("`perm`", "#{datasourceUser.perm}"); + VALUES("`create_time`", "#{datasourceUser.createTime}"); + VALUES("`update_time`", "#{datasourceUser.updateTime}"); + }}.toString(); + } + + + /** + * + * @param parameter + * @return + */ + public String deleteByUserId(Map parameter) { + return new SQL() {{ + DELETE_FROM(TABLE_NAME); + + WHERE("`user_id` = #{userId}"); + }}.toString(); + } + + /** + * @param parameter + * @return + */ + public String deleteByDatasourceId(Map parameter) { + return new SQL() {{ + DELETE_FROM(TABLE_NAME); + + WHERE("`datasource_id` = #{datasourceId}"); + }}.toString(); + } +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/MasterServerMapper.java b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/MasterServerMapper.java new file mode 100644 index 0000000000..4fec8092de --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/MasterServerMapper.java @@ -0,0 +1,81 @@ +/* + * 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.dao.mapper; + +import cn.escheduler.dao.model.MasterServer; +import org.apache.ibatis.annotations.*; +import org.apache.ibatis.type.JdbcType; + +import java.util.Date; +import java.util.List; + +public interface MasterServerMapper { + + /** + * query all masters + * + * @return + */ + @Results(value = { + @Result(property = "id", column = "id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "host", column = "host", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "port", column = "port", javaType = int.class, jdbcType = JdbcType.INTEGER), + @Result(property = "zkDirectory", column = "zk_directory", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "resInfo", column = "res_info", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "createTime", column = "create_time", javaType = Date.class, jdbcType = JdbcType.TIMESTAMP), + @Result(property = "lastHeartbeatTime", column = "last_heartbeat_time", javaType = Date.class, jdbcType = JdbcType.TIMESTAMP) + }) + @SelectProvider(type = MasterServerMapperProvider.class, method = "queryAllMaster") + List queryAllMaster(); + + /** + * insert one master + * + * @param masterServer + * @return + */ + @InsertProvider(type = MasterServerMapperProvider.class, method = "insert") + @SelectKey(statement = "SELECT LAST_INSERT_ID() as id", resultType = Integer.class, keyProperty = "masterServer.id", before = false) + int insert(@Param("masterServer") MasterServer masterServer); + + /** + * update master + * + * @param masterServer + * @return + */ + @UpdateProvider(type = MasterServerMapperProvider.class, method = "update") + int update(@Param("masterServer") MasterServer masterServer); + + /** + * delete master + */ + @DeleteProvider(type = MasterServerMapperProvider.class, method = "delete") + void delete(); + + /** + * delete master by host + * + * @param host + */ + @DeleteProvider(type = MasterServerMapperProvider.class, method = "deleteWorkerByHost") + int deleteWorkerByHost(@Param("host") String host); + + + + +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/MasterServerMapperProvider.java b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/MasterServerMapperProvider.java new file mode 100644 index 0000000000..768f1a3250 --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/MasterServerMapperProvider.java @@ -0,0 +1,99 @@ +/* + * 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.dao.mapper; + + +import org.apache.ibatis.jdbc.SQL; + +import java.util.Map; + +public class MasterServerMapperProvider { + + private static final String TABLE_NAME = "t_escheduler_master_server"; + + /** + * + * @return + */ + public String queryAllMaster() { + return new SQL() {{ + SELECT("*"); + + FROM(TABLE_NAME); + }}.toString(); + } + + /** + * + * @param parameter + * @return + */ + public String insert(Map parameter) { + return new SQL() {{ + INSERT_INTO(TABLE_NAME); + + VALUES("host", "#{masterServer.host}"); + VALUES("port", "#{masterServer.port}"); + VALUES("zk_directory", "#{masterServer.zkDirectory}"); + VALUES("res_info", "#{masterServer.resInfo}"); + VALUES("create_time", "#{masterServer.createTime}"); + VALUES("last_heartbeat_time", "#{masterServer.lastHeartbeatTime}"); + }}.toString(); + } + + /** + * + * @param parameter + * @return + */ + public String update(Map parameter) { + return new SQL() {{ + UPDATE(TABLE_NAME); + + SET("last_heartbeat_time = #{masterServer.lastHeartbeatTime}"); + SET("port = #{masterServer.port}"); + SET("res_info = #{masterServer.resInfo}"); + + WHERE("host = #{masterServer.host}"); + }}.toString(); + } + + /** + * + * @return + */ + public String delete() { + return new SQL() {{ + DELETE_FROM(TABLE_NAME); + }}.toString(); + } + + /** + * + * @param parameter + * @return + */ + public String deleteWorkerByHost(Map parameter) { + return new SQL() {{ + DELETE_FROM(TABLE_NAME); + + WHERE("host = #{host}"); + }}.toString(); + } + + +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ProcessDefinitionMapper.java b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ProcessDefinitionMapper.java new file mode 100644 index 0000000000..0484b7cebe --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ProcessDefinitionMapper.java @@ -0,0 +1,248 @@ +/* + * 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.dao.mapper; + +import cn.escheduler.common.enums.Flag; +import cn.escheduler.common.enums.ReleaseState; +import cn.escheduler.common.enums.UserType; +import cn.escheduler.dao.model.DefinitionGroupByUser; +import cn.escheduler.dao.model.ProcessDefinition; +import org.apache.ibatis.annotations.*; +import org.apache.ibatis.type.EnumOrdinalTypeHandler; +import org.apache.ibatis.type.JdbcType; + +import java.sql.Timestamp; +import java.util.List; + +/** + * process definition mapper + */ +public interface ProcessDefinitionMapper { + + /** + * insert process define + * @param processDefinition + * @return + */ + @InsertProvider(type = ProcessDefinitionMapperProvider.class, method = "insert") + @Options(useGeneratedKeys = true,keyProperty = "processDefinition.id") + @SelectKey(statement = "SELECT LAST_INSERT_ID()", keyProperty = "processDefinition.id", before = false, resultType = int.class) + int insert(@Param("processDefinition") ProcessDefinition processDefinition); + + + /** + * delete process define + * @param processDefinitionId + * @return + */ + @DeleteProvider(type = ProcessDefinitionMapperProvider.class, method = "delete") + int delete(@Param("processDefinitionId") int processDefinitionId); + + + /** + * update process define + * + * @param processDefinition + * @return + */ + @UpdateProvider(type = ProcessDefinitionMapperProvider.class, method = "update") + int update(@Param("processDefinition") ProcessDefinition processDefinition); + + /** + * update release state + * @param processDefinitionId + * @param releaseState + * @return + */ + @UpdateProvider(type = ProcessDefinitionMapperProvider.class, method = "updateProcessDefinitionReleaseState") + int updateProcessDefinitionReleaseState(@Param("processDefinitionId") int processDefinitionId, + @Param("releaseState") ReleaseState releaseState); + + + /** + * query definition by id + * @param processDefinitionId + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "name", column = "name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "version", column = "version", javaType = Integer.class, jdbcType = JdbcType.TINYINT), + @Result(property = "releaseState", column = "release_state", typeHandler = EnumOrdinalTypeHandler.class, javaType = ReleaseState.class, jdbcType = JdbcType.TINYINT), + @Result(property = "projectId", column = "project_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "userId", column = "user_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "processDefinitionJson", column = "process_definition_json", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "desc", column = "desc", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "globalParams", column = "global_params", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "createTime", column = "create_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "updateTime", column = "update_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "flag", column = "flag", typeHandler = EnumOrdinalTypeHandler.class, javaType = Flag.class, jdbcType = JdbcType.TINYINT), + @Result(property = "userName", column = "user_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "locations", column = "locations", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "connects", column = "connects", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "projectName", column = "project_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "receivers", column = "receivers", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "receiversCc", column = "receivers_cc", javaType = String.class, jdbcType = JdbcType.VARCHAR) + + }) + @SelectProvider(type = ProcessDefinitionMapperProvider.class, method = "queryByDefineId") + ProcessDefinition queryByDefineId(@Param("processDefinitionId") int processDefinitionId); + + /** + * query process definition by project id and name + * @param projectId + * @param name + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "name", column = "name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "version", column = "version", javaType = Integer.class, jdbcType = JdbcType.TINYINT), + @Result(property = "releaseState", column = "release_state", typeHandler = EnumOrdinalTypeHandler.class, javaType = ReleaseState.class, jdbcType = JdbcType.TINYINT), + @Result(property = "projectId", column = "project_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "userId", column = "user_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "processDefinitionJson", column = "process_definition_json", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "desc", column = "desc", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "createTime", column = "create_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "updateTime", column = "update_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "flag", column = "flag", typeHandler = EnumOrdinalTypeHandler.class, javaType = Flag.class, jdbcType = JdbcType.TINYINT), + @Result(property = "userName", column = "user_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "locations", column = "locations", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "connects", column = "connects", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "projectName", column = "project_name", javaType = String.class, jdbcType = JdbcType.VARCHAR) + }) + @SelectProvider(type = ProcessDefinitionMapperProvider.class, method = "queryByDefineName") + ProcessDefinition queryByDefineName(@Param("projectId") int projectId, + @Param("processDefinitionName") String name); + + + /** + * count definition number + * @param projectId + * @param userId + * @param searchVal + * @return + */ + @SelectProvider(type = ProcessDefinitionMapperProvider.class, method = "countDefineNumber") + Integer countDefineNumber(@Param("projectId") int projectId, + @Param("userId") int userId, + @Param("searchVal") String searchVal + ); + + /** + * query all definition list + * @param projectId + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "name", column = "name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "version", column = "version", javaType = Integer.class, jdbcType = JdbcType.TINYINT), + @Result(property = "releaseState", column = "release_state", typeHandler = EnumOrdinalTypeHandler.class, javaType = ReleaseState.class, jdbcType = JdbcType.TINYINT), + @Result(property = "projectId", column = "project_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "userId", column = "user_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "desc", column = "desc", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "createTime", column = "create_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "updateTime", column = "update_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "flag", column = "flag", typeHandler = EnumOrdinalTypeHandler.class, javaType = Flag.class, jdbcType = JdbcType.TINYINT), + @Result(property = "userName", column = "user_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "projectName", column = "project_name", javaType = String.class, jdbcType = JdbcType.VARCHAR) + }) + @SelectProvider(type = ProcessDefinitionMapperProvider.class, method = "queryAllDefinitionList") + List queryAllDefinitionList(@Param("projectId") int projectId); + + /** + * query definition list paging + * @param projectId + * @param searchVal + * @param userId + * @param offset + * @param pageSize + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "name", column = "name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "version", column = "version", javaType = Integer.class, jdbcType = JdbcType.TINYINT), + @Result(property = "releaseState", column = "release_state", typeHandler = EnumOrdinalTypeHandler.class, javaType = ReleaseState.class, jdbcType = JdbcType.TINYINT), + @Result(property = "projectId", column = "project_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "userId", column = "user_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "desc", column = "desc", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "createTime", column = "create_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "updateTime", column = "update_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "flag", column = "flag", typeHandler = EnumOrdinalTypeHandler.class, javaType = Flag.class, jdbcType = JdbcType.TINYINT), + @Result(property = "userName", column = "user_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "scheduleReleaseState", column = "schedule_release_state", typeHandler = EnumOrdinalTypeHandler.class, javaType = ReleaseState.class, jdbcType = JdbcType.TINYINT), + @Result(property = "projectName", column = "project_name", javaType = String.class, jdbcType = JdbcType.VARCHAR) + }) + @SelectProvider(type = ProcessDefinitionMapperProvider.class, method = "queryDefineListPaging") + List queryDefineListPaging(@Param("projectId") int projectId, + @Param("searchVal") String searchVal, + @Param("userId") Integer userId, + @Param("offset") int offset, + @Param("pageSize") int pageSize); + + /** + * query definition list by define id list + * @param ids + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "name", column = "name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "version", column = "version", javaType = Integer.class, jdbcType = JdbcType.TINYINT), + @Result(property = "releaseState", column = "release_state", typeHandler = EnumOrdinalTypeHandler.class, javaType = ReleaseState.class, jdbcType = JdbcType.TINYINT), + @Result(property = "projectId", column = "project_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "userId", column = "user_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "processDefinitionJson", column = "process_definition_json", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "desc", column = "desc", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "createTime", column = "create_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "updateTime", column = "update_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "flag", column = "flag", typeHandler = EnumOrdinalTypeHandler.class, javaType = Flag.class, jdbcType = JdbcType.TINYINT), + @Result(property = "locations", column = "locations", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "connects", column = "connects", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "userName", column = "user_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "projectName", column = "project_name", javaType = String.class, jdbcType = JdbcType.VARCHAR) + }) + @SelectProvider(type = ProcessDefinitionMapperProvider.class, method = "queryDefinitionListByIdList") + List queryDefinitionListByIdList(@Param("ids") List ids); + + /** + * count definition number group by users + * @param userId + * @param userType + * @param projectId + * @return + */ + @Results(value = { + @Result(property = "userId", column = "user_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "userName", column = "user_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "count", column = "count", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + }) + @SelectProvider(type = ProcessDefinitionMapperProvider.class, method = "countDefinitionGroupByUser") + List countDefinitionGroupByUser( + @Param("userId") Integer userId, + @Param("userType") UserType userType, + @Param("projectId") Integer projectId); + + /** + * update receivers and cc by definition id + * @param receivers + * @param receiversCc + * @param processDefinitionId + * @return + */ + @UpdateProvider(type = ProcessDefinitionMapperProvider.class, method = "updateReceiversAndCcById") + int updateReceiversAndCcById(@Param("receivers") String receivers, + @Param("receiversCc") String receiversCc, + @Param("processDefinitionId") int processDefinitionId); +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ProcessDefinitionMapperProvider.java b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ProcessDefinitionMapperProvider.java new file mode 100644 index 0000000000..cefbe14bbd --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ProcessDefinitionMapperProvider.java @@ -0,0 +1,292 @@ +/* + * 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.dao.mapper; + +import cn.escheduler.common.enums.Flag; +import cn.escheduler.common.enums.ReleaseState; +import cn.escheduler.common.utils.EnumFieldUtil; +import org.apache.commons.lang3.StringUtils; +import org.apache.ibatis.jdbc.SQL; + +import java.util.List; +import java.util.Map; + +/** + * process definition mapper provider + */ +public class ProcessDefinitionMapperProvider { + + private static final String TABLE_NAME = "t_escheduler_process_definition"; + + + + /** + * 插入流程定义 + * + * @param parameter + * @return + */ + public String insert(Map parameter) { + return new SQL() { + { + INSERT_INTO(TABLE_NAME); + VALUES("`name`", "#{processDefinition.name}"); + VALUES("`version`", "#{processDefinition.version}"); + VALUES("`release_state`", EnumFieldUtil.genFieldStr("processDefinition.releaseState", ReleaseState.class)); + VALUES("`project_id`", "#{processDefinition.projectId}"); + VALUES("`process_definition_json`", "#{processDefinition.processDefinitionJson}"); + VALUES("`desc`", "#{processDefinition.desc}"); + VALUES("`global_params`", "#{processDefinition.globalParams}"); + VALUES("`locations`", "#{processDefinition.locations}"); + VALUES("`connects`", "#{processDefinition.connects}"); + VALUES("`create_time`", "#{processDefinition.createTime}"); + VALUES("`update_time`", "#{processDefinition.updateTime}"); + VALUES("`flag`", EnumFieldUtil.genFieldStr("processDefinition.flag", ReleaseState.class)); + VALUES("`user_id`", "#{processDefinition.userId}"); + + } + }.toString(); + } + + /** + * 删除流程定义 + * + * @param parameter + * @return + */ + public String delete(Map parameter) { + return new SQL() { + { + DELETE_FROM(TABLE_NAME); + + WHERE("`id`=#{processDefinitionId}"); + } + }.toString(); + } + + /** + * 更新流程定义 + * + * @param parameter + * @return + */ + public String update(Map parameter) { + return new SQL() { + { + UPDATE(TABLE_NAME); + + SET("`name`=#{processDefinition.name}"); + SET("`version`=#{processDefinition.version}"); + SET("`release_state`="+EnumFieldUtil.genFieldStr("processDefinition.releaseState", ReleaseState.class)); + SET("`project_id`=#{processDefinition.projectId}"); + SET("`process_definition_json`=#{processDefinition.processDefinitionJson}"); + SET("`desc`=#{processDefinition.desc}"); + SET("`locations`=#{processDefinition.locations}"); + SET("`connects`=#{processDefinition.connects}"); + SET("`global_params`=#{processDefinition.globalParams}"); + SET("`create_time`=#{processDefinition.createTime}"); + SET("`update_time`=#{processDefinition.updateTime}"); + SET("`flag`="+EnumFieldUtil.genFieldStr("processDefinition.flag", Flag.class)); + SET("`user_id`=#{processDefinition.userId}"); + + WHERE("`id`=#{processDefinition.id}"); + + } + }.toString(); + } + + public String updateProcessDefinitionReleaseState(Map parameter) { + return new SQL() { + { + UPDATE(TABLE_NAME); + + SET("`release_state`="+EnumFieldUtil.genFieldStr("releaseState", ReleaseState.class)); + + + WHERE("`id`=#{processDefinitionId}"); + + } + }.toString(); + } + + /** + * 根据流程定义 id 查询 sql + * + * @param parameter + * @return + */ + public String queryByDefineId(Map parameter) { + return new SQL() { + { + SELECT("pd.*,u.user_name,p.name as projectName"); + + FROM(TABLE_NAME + " pd"); + JOIN("t_escheduler_user u ON pd.user_id = u.id"); + JOIN("t_escheduler_project p ON pd.project_id = p.id"); + WHERE("pd.id = #{processDefinitionId}"); + } + }.toString(); + } + + + /** + * query By Define Name + * + * @param parameter + * @return + */ + public String queryByDefineName(Map parameter) { + return new SQL() { + { + SELECT("pd.*,u.user_name,p.name as project_name,t.tenant_code,t.tenant_name,q.queue,q.queue_name"); + + FROM(TABLE_NAME + " pd"); + JOIN("t_escheduler_user u ON pd.user_id = u.id"); + JOIN("t_escheduler_project p ON pd.project_id = p.id"); + JOIN("t_escheduler_tenant t ON t.id = u.tenant_id"); + JOIN("t_escheduler_queue q ON t.queue_id = q.id"); + WHERE("p.id = #{projectId}"); + WHERE("pd.name = #{processDefinitionName}"); + } + }.toString(); + } + + + /** + * query define list paging + * @param parameter + * @return + */ + public String queryDefineListPaging(Map parameter) { + return new SQL() {{ + SELECT("td.id,td.name,td.version,td.release_state,td.project_id,td.user_id,td.`desc`,td.create_time,td.update_time,td.flag,td.global_params,td.receivers,td.receivers_cc,sc.schedule_release_state"); + FROM(TABLE_NAME + " td"); + LEFT_OUTER_JOIN(" (select process_definition_id,release_state as schedule_release_state from `t_escheduler_schedules` " + + "group by `process_definition_id`,`release_state`) sc on sc.process_definition_id = td.id"); + + WHERE("td.project_id = #{projectId} "); + Object searchVal = parameter.get("searchVal"); + if(searchVal != null && StringUtils.isNotEmpty(searchVal.toString())){ + WHERE( " td.name like concat('%', #{searchVal}, '%') "); + } + Object userId = parameter.get("userId"); + if(userId != null && 0 != Integer.parseInt(userId.toString())){ + WHERE("td.user_id = #{userId}"); + } + ORDER_BY(" td.update_time desc limit #{offset},#{pageSize} "); + }}.toString(); + } + /** + * query all define list by project id + * @param parameter + * @return + */ + public String queryAllDefinitionList(Map parameter) { + return new SQL() {{ + SELECT("id,name,version,release_state,project_id,user_id,`desc`,create_time,update_time,flag,global_params,receivers,receivers_cc"); + + FROM(TABLE_NAME ); + + WHERE("project_id = #{projectId}"); + ORDER_BY("create_time desc "); + }}.toString(); + } + /** + * count definition number group by project id + * @param parameter + * @return + */ + public String countDefineNumber(Map parameter) { + return new SQL() {{ + SELECT("count(0)"); + + FROM(TABLE_NAME); + + WHERE("project_id = #{projectId}"); + Object searchVal = parameter.get("searchVal"); + if(searchVal != null && StringUtils.isNotEmpty(searchVal.toString())){ + WHERE( " name like concat('%', #{searchVal}, '%') "); + } + Object userId = parameter.get("userId"); + if(userId != null && 0 != Integer.parseInt(userId.toString())){ + WHERE("user_id = #{userId}"); + } + }}.toString(); + } + + /** + * count definition number by user type + * @param parameter + * @return + */ + public String countDefinitionGroupByUser(Map parameter) { + return new SQL() {{ + + SELECT("td.user_id as user_id, tu.user_name as user_name, count(0) as count"); + FROM(TABLE_NAME + " td"); + JOIN("t_escheduler_user tu on tu.id=td.user_id"); + + if(parameter.get("projectId") != null && (int)parameter.get("projectId") != 0){ + WHERE( "td.project_id = #{projectId} "); + }else{ + if(parameter.get("userType") != null && String.valueOf(parameter.get("userType")) == "GENERAL_USER") { + AND(); + WHERE("td.project_id in (select id as project_id from t_escheduler_project tp where tp.user_id= #{userId} " + + "union select project_id from t_escheduler_relation_project_user tr where tr.user_id= #{userId} )"); + + } + } + GROUP_BY("td.user_id"); + + }}.toString(); + } + + /** + * query definition list by define id list + * @param parameter + * @return + */ + public String queryDefinitionListByIdList(Map parameter){ + List ids = (List) parameter.get("ids"); + + return new SQL() {{ + SELECT("*"); + + FROM(TABLE_NAME); + + WHERE("`id` in (" + String.join(",", ids) + ")"); + }}.toString(); + } + + /** + * update receivers and cc by definition id + * + * @param parameter + * @return + */ + public String updateReceiversAndCcById(Map parameter) { + return new SQL() { + { + UPDATE(TABLE_NAME); + SET("`receivers`=#{receivers}"); + SET("`receivers_cc`=#{receiversCc}"); + WHERE("`id`=#{processDefinitionId}"); + + } + }.toString(); + } +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ProcessInstanceMapMapper.java b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ProcessInstanceMapMapper.java new file mode 100644 index 0000000000..b6945b36f7 --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ProcessInstanceMapMapper.java @@ -0,0 +1,103 @@ +/* + * 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.dao.mapper; + +import cn.escheduler.dao.model.ProcessInstanceMap; +import org.apache.ibatis.annotations.*; +import org.apache.ibatis.type.JdbcType; + +/** + * work process instance map mapper + */ +public interface ProcessInstanceMapMapper { + + /** + * insert process instance relation + * @param processInstanceMap + * @return + */ + @InsertProvider(type = ProcessInstanceMapMapperProvider.class, method = "insert") + @Options(useGeneratedKeys = true,keyProperty = "processInstanceMap.id") + @SelectKey(statement = "SELECT LAST_INSERT_ID()", keyProperty = "processInstanceMap.id", before = false, resultType = int.class) + int insert(@Param("processInstanceMap") ProcessInstanceMap processInstanceMap); + + + /** + * delete process instance relation by id + * @param processInstanceMapId + * @return + */ + @DeleteProvider(type = ProcessInstanceMapMapperProvider.class, method = "delete") + int delete(@Param("processInstanceMapId") int processInstanceMapId); + + /** + * delete process instance relation by parent work process id + * @param parentProcessId + * @return + */ + @DeleteProvider(type = ProcessInstanceMapMapperProvider.class, method = "deleteByParentProcessId") + int deleteByParentProcessId(@Param("parentProcessId") int parentProcessId); + + /** + * update process instance relation + * + * @param processInstanceMap + * @return + */ + @UpdateProvider(type = ProcessInstanceMapMapperProvider.class, method = "update") + int update(@Param("processInstanceMap") ProcessInstanceMap processInstanceMap); + + /** + * query process instance relation by id + * @param processMapId + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "parentProcessInstanceId", column = "parent_process_instance_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "parentTaskInstanceId", column = "parent_task_instance_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "processInstanceId", column = "process_instance_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER) + }) + @SelectProvider(type = ProcessInstanceMapMapperProvider.class, method = "queryById") + ProcessInstanceMap queryById(@Param("processMapId") int processMapId); + + /** + * query by parent instance id + * @param parentProcessId + * @param parentTaskId + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "parentProcessInstanceId", column = "parent_process_instance_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "parentTaskInstanceId", column = "parent_task_instance_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "processInstanceId", column = "process_instance_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER) + }) + @SelectProvider(type = ProcessInstanceMapMapperProvider.class, method = "queryByParentId") + ProcessInstanceMap queryByParentId(@Param("parentProcessId") int parentProcessId, @Param("parentTaskId") int parentTaskId); + + /** + * query relation by sub process id + * @param subProcessId + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "parentProcessInstanceId", column = "parent_process_instance_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "parentTaskInstanceId", column = "parent_task_instance_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "processInstanceId", column = "process_instance_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER) + }) + @SelectProvider(type = ProcessInstanceMapMapperProvider.class, method = "queryBySubProcessId") + ProcessInstanceMap queryBySubProcessId(@Param("subProcessId")Integer subProcessId); +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ProcessInstanceMapMapperProvider.java b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ProcessInstanceMapMapperProvider.java new file mode 100644 index 0000000000..0f29a5104d --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ProcessInstanceMapMapperProvider.java @@ -0,0 +1,150 @@ +/* + * 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.dao.mapper; + +import org.apache.ibatis.jdbc.SQL; + +import java.util.Map; + +/** + * process instance map mapper provider + */ +public class ProcessInstanceMapMapperProvider { + + private static final String TABLE_NAME = "t_escheduler_relation_process_instance"; + + /** + * insert process instance relation + * + * @param parameter + * @return + */ + public String insert(Map parameter) { + return new SQL() { + { + INSERT_INTO(TABLE_NAME); + VALUES("`parent_process_instance_id`", "#{processInstanceMap.parentProcessInstanceId}"); + VALUES("`parent_task_instance_id`", "#{processInstanceMap.parentTaskInstanceId}"); + VALUES("`process_instance_id`", "#{processInstanceMap.processInstanceId}"); + } + }.toString(); + } + + /** + * delete process instance relation + * + * @param parameter + * @return + */ + public String delete(Map parameter) { + return new SQL() { + { + DELETE_FROM(TABLE_NAME); + + WHERE("`id`=#{processInstanceMapId}"); + } + }.toString(); + } + + /** + * delete by parent process id + * + * @param parameter + * @return + */ + public String deleteByParentProcessId(Map parameter) { + return new SQL() { + { + DELETE_FROM(TABLE_NAME); + + WHERE("`parent_process_instance_id`=#{parentProcessId}"); + } + }.toString(); + } + + /** + * update process map + * @param parameter + * @return + */ + public String update(Map parameter) { + return new SQL() { + { + UPDATE(TABLE_NAME); + + SET("`parent_process_instance_id`=#{processInstanceMap.parentProcessInstanceId}"); + SET("`parent_task_instance_id`=#{processInstanceMap.parentTaskInstanceId}"); + SET("`process_instance_id`=#{processInstanceMap.processInstanceId}"); + WHERE("`id`=#{processInstanceMap.id}"); + } + }.toString(); + } + + + /** + * query by map id + * + * @param parameter + * @return + */ + public String queryById(Map parameter) { + return new SQL() { + { + SELECT("*"); + + FROM(TABLE_NAME); + + WHERE("`id` = #{processMapId}"); + } + }.toString(); + } + + /** + * query by parent process instance id and parent task id + * + * @param parameter + * @return + */ + public String queryByParentId(Map parameter) { + return new SQL() { + { + SELECT("*"); + FROM(TABLE_NAME); + WHERE("`parent_process_instance_id` = #{parentProcessId}"); + WHERE("`parent_task_instance_id` = #{parentTaskId}"); + } + }.toString(); + } + + /** + * query by sub process instance id + * + * @param parameter + * @return + */ + public String queryBySubProcessId(Map parameter) { + return new SQL() { + { + SELECT("*"); + FROM(TABLE_NAME); + WHERE("`process_instance_id` = #{subProcessId}"); + } + }.toString(); + } + + +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ProcessInstanceMapper.java b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ProcessInstanceMapper.java new file mode 100644 index 0000000000..3eb77af92b --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ProcessInstanceMapper.java @@ -0,0 +1,614 @@ +/* + * 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.dao.mapper; + +import cn.escheduler.common.enums.*; +import cn.escheduler.dao.model.ExecuteStatusCount; +import cn.escheduler.dao.model.ProcessInstance; +import org.apache.ibatis.annotations.*; +import org.apache.ibatis.type.EnumOrdinalTypeHandler; +import org.apache.ibatis.type.JdbcType; + +import java.sql.Timestamp; +import java.util.Date; +import java.util.List; + +/** + * process instance mapper + */ +public interface ProcessInstanceMapper { + + /** + * insert process instance + * @param processInstance + * @return + */ + @InsertProvider(type = ProcessInstanceMapperProvider.class, method = "insert") + @Options(useGeneratedKeys = true,keyProperty = "processInstance.id") + @SelectKey(statement = "SELECT LAST_INSERT_ID()", keyProperty = "processInstance.id", before = false, resultType = int.class) + int insert(@Param("processInstance") ProcessInstance processInstance); + + + /** + * delete process instance + * @param processId + * @return + */ + @DeleteProvider(type = ProcessInstanceMapperProvider.class, method = "delete") + int delete(@Param("processId") int processId); + + /** + * update process instance + * + * @param processInstance + * @return + */ + @UpdateProvider(type = ProcessInstanceMapperProvider.class, method = "update") + int update(@Param("processInstance") ProcessInstance processInstance); + + + /** + * query instance detail by id + * @param processId + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "processDefinitionId", column = "process_definition_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "state", column = "state", typeHandler = EnumOrdinalTypeHandler.class, javaType = ExecutionStatus.class, jdbcType = JdbcType.TINYINT), + @Result(property = "recovery", column = "recovery", typeHandler = EnumOrdinalTypeHandler.class, javaType = Flag.class, jdbcType = JdbcType.TINYINT), + @Result(property = "startTime", column = "start_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "endTime", column = "end_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "runTimes", column = "run_times", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "name", column = "name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "host", column = "host", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "commandType", column = "command_type", typeHandler = EnumOrdinalTypeHandler.class, javaType = CommandType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "commandParam", column = "command_param", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "taskDependType", column = "task_depend_type", typeHandler = EnumOrdinalTypeHandler.class, javaType = TaskDependType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "maxTryTimes", column = "max_try_times", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "failureStrategy", column = "failure_strategy", typeHandler = EnumOrdinalTypeHandler.class, javaType = FailureStrategy.class, jdbcType = JdbcType.TINYINT), + @Result(property = "warningType", column = "warning_type", javaType = WarningType.class, typeHandler = EnumOrdinalTypeHandler.class, jdbcType = JdbcType.TINYINT), + @Result(property = "warningGroupId", column = "warning_group_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "scheduleTime", column = "schedule_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "commandStartTime", column = "command_start_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "globalParams", column = "global_params", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "executorId", column = "executor_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "processInstanceJson", column = "process_instance_json", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "isSubProcess", column = "is_sub_process", javaType = Flag.class, typeHandler = EnumOrdinalTypeHandler.class, jdbcType = JdbcType.TINYINT), + @Result(property = "locations", column = "locations", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "connects", column = "connects", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "historyCmd", column = "history_cmd", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "dependenceScheduleTimes", column = "dependence_schedule_times", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "duration", column = "duration", javaType = Long.class, jdbcType = JdbcType.BIGINT), + @Result(property = "tenantCode", column = "tenant_code", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "processInstancePriority", column = "process_instance_priority", javaType = Priority.class, typeHandler = EnumOrdinalTypeHandler.class, jdbcType = JdbcType.TINYINT) + }) + @SelectProvider(type = ProcessInstanceMapperProvider.class, method = "queryDetailById") + ProcessInstance queryDetailById(@Param("processId") int processId); + + + /** + * query instance by id + * @param processId + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "processDefinitionId", column = "process_definition_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "state", column = "state", typeHandler = EnumOrdinalTypeHandler.class, javaType = ExecutionStatus.class, jdbcType = JdbcType.TINYINT), + @Result(property = "recovery", column = "recovery", typeHandler = EnumOrdinalTypeHandler.class, javaType = Flag.class, jdbcType = JdbcType.TINYINT), + @Result(property = "startTime", column = "start_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "endTime", column = "end_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "runTimes", column = "run_times", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "name", column = "name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "host", column = "host", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "commandType", column = "command_type", typeHandler = EnumOrdinalTypeHandler.class, javaType = CommandType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "commandParam", column = "command_param", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "taskDependType", column = "task_depend_type", typeHandler = EnumOrdinalTypeHandler.class, javaType = TaskDependType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "maxTryTimes", column = "max_try_times", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "failureStrategy", column = "failure_strategy", typeHandler = EnumOrdinalTypeHandler.class, javaType = FailureStrategy.class, jdbcType = JdbcType.TINYINT), + @Result(property = "warningType", column = "warning_type", javaType = WarningType.class, typeHandler = EnumOrdinalTypeHandler.class, jdbcType = JdbcType.TINYINT), + @Result(property = "warningGroupId", column = "warning_group_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "scheduleTime", column = "schedule_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "commandStartTime", column = "command_start_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "globalParams", column = "global_params", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "executorId", column = "executor_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "processInstanceJson", column = "process_instance_json", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "isSubProcess", column = "is_sub_process", javaType = Flag.class, typeHandler = EnumOrdinalTypeHandler.class, jdbcType = JdbcType.TINYINT), + @Result(property = "locations", column = "locations", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "connects", column = "connects", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "historyCmd", column = "history_cmd", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "dependenceScheduleTimes", column = "dependence_schedule_times", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "processInstancePriority", column = "process_instance_priority", javaType = Priority.class, typeHandler = EnumOrdinalTypeHandler.class, jdbcType = JdbcType.TINYINT) + }) + @SelectProvider(type = ProcessInstanceMapperProvider.class, method = "queryById") + ProcessInstance queryById(@Param("processId") int processId); + + /** + * query instance list by host and state array + * @param host + * @param stateArray + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "processDefinitionId", column = "process_definition_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "state", column = "state", typeHandler = EnumOrdinalTypeHandler.class, javaType = ExecutionStatus.class, jdbcType = JdbcType.TINYINT), + @Result(property = "recovery", column = "recovery", typeHandler = EnumOrdinalTypeHandler.class, javaType = Flag.class, jdbcType = JdbcType.TINYINT), + @Result(property = "startTime", column = "start_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "endTime", column = "end_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "runTimes", column = "run_times", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "name", column = "name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "host", column = "host", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "commandType", column = "command_type", typeHandler = EnumOrdinalTypeHandler.class, javaType = CommandType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "commandParam", column = "command_param", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "taskDependType", column = "task_depend_type", typeHandler = EnumOrdinalTypeHandler.class, javaType = TaskDependType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "maxTryTimes", column = "max_try_times", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "failureStrategy", column = "failure_strategy", typeHandler = EnumOrdinalTypeHandler.class, javaType = FailureStrategy.class, jdbcType = JdbcType.TINYINT), + @Result(property = "warningType", column = "warning_type", javaType = WarningType.class, typeHandler = EnumOrdinalTypeHandler.class, jdbcType = JdbcType.TINYINT), + @Result(property = "warningGroupId", column = "warning_group_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "scheduleTime", column = "schedule_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "commandStartTime", column = "command_start_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "globalParams", column = "global_params", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "executorId", column = "executor_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "isSubProcess", column = "is_sub_process", javaType = Flag.class, typeHandler = EnumOrdinalTypeHandler.class, jdbcType = JdbcType.TINYINT), + @Result(property = "locations", column = "locations", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "connects", column = "connects", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "historyCmd", column = "history_cmd", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "dependenceScheduleTimes", column = "dependence_schedule_times", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "processInstanceJson", column = "process_instance_json", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "processInstancePriority", column = "process_instance_priority", javaType = Priority.class, typeHandler = EnumOrdinalTypeHandler.class, jdbcType = JdbcType.TINYINT) + + }) + @SelectProvider(type = ProcessInstanceMapperProvider.class, method = "queryByHostAndStatus") + List queryByHostAndStatus(@Param("host") String host, @Param("states")int[] stateArray); + + /** + * query instance list by state array + * @param stateArray + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "processDefinitionId", column = "process_definition_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "state", column = "state", typeHandler = EnumOrdinalTypeHandler.class, javaType = ExecutionStatus.class, jdbcType = JdbcType.TINYINT), + @Result(property = "recovery", column = "recovery", typeHandler = EnumOrdinalTypeHandler.class, javaType = Flag.class, jdbcType = JdbcType.TINYINT), + @Result(property = "startTime", column = "start_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "endTime", column = "end_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "runTimes", column = "run_times", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "name", column = "name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "host", column = "host", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "commandType", column = "command_type", typeHandler = EnumOrdinalTypeHandler.class, javaType = CommandType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "commandParam", column = "command_param", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "taskDependType", column = "task_depend_type", typeHandler = EnumOrdinalTypeHandler.class, javaType = TaskDependType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "maxTryTimes", column = "max_try_times", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "failureStrategy", column = "failure_strategy", typeHandler = EnumOrdinalTypeHandler.class, javaType = FailureStrategy.class, jdbcType = JdbcType.TINYINT), + @Result(property = "warningType", column = "warning_type", javaType = WarningType.class, typeHandler = EnumOrdinalTypeHandler.class, jdbcType = JdbcType.TINYINT), + @Result(property = "warningGroupId", column = "warning_group_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "scheduleTime", column = "schedule_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "commandStartTime", column = "command_start_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "globalParams", column = "global_params", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "executorId", column = "executor_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "isSubProcess", column = "is_sub_process", javaType = Flag.class, typeHandler = EnumOrdinalTypeHandler.class, jdbcType = JdbcType.TINYINT), + @Result(property = "locations", column = "locations", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "connects", column = "connects", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "historyCmd", column = "history_cmd", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "dependenceScheduleTimes", column = "dependence_schedule_times", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "processInstanceJson", column = "process_instance_json", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "processInstancePriority", column = "process_instance_priority", javaType = Priority.class, typeHandler = EnumOrdinalTypeHandler.class, jdbcType = JdbcType.TINYINT) + + }) + @SelectProvider(type = ProcessInstanceMapperProvider.class, method = "listByStatus") + List listByStatus(@Param("states")int[] stateArray); + + /** + * query list paging + * + * @param projectId + * @param processDefinitionId + * @param searchVal + * @param statusArray + * @param startTime + * @param endTime + * @param offset + * @param pageSize + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "processDefinitionId", column = "process_definition_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "state", column = "state", typeHandler = EnumOrdinalTypeHandler.class, javaType = ExecutionStatus.class, jdbcType = JdbcType.TINYINT), + @Result(property = "recovery", column = "recovery", typeHandler = EnumOrdinalTypeHandler.class, javaType = Flag.class, jdbcType = JdbcType.TINYINT), + @Result(property = "startTime", column = "start_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "endTime", column = "end_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "runTimes", column = "run_times", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "name", column = "name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "host", column = "host", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "commandType", column = "command_type", typeHandler = EnumOrdinalTypeHandler.class, javaType = CommandType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "commandParam", column = "command_param", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "taskDependType", column = "task_depend_type", typeHandler = EnumOrdinalTypeHandler.class, javaType = TaskDependType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "maxTryTimes", column = "max_try_times", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "failureStrategy", column = "failure_strategy", typeHandler = EnumOrdinalTypeHandler.class, javaType = FailureStrategy.class, jdbcType = JdbcType.TINYINT), + @Result(property = "warningType", column = "warning_type", javaType = WarningType.class, typeHandler = EnumOrdinalTypeHandler.class, jdbcType = JdbcType.TINYINT), + @Result(property = "warningGroupId", column = "warning_group_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "scheduleTime", column = "schedule_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "commandStartTime", column = "command_start_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "globalParams", column = "global_params", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "executorId", column = "executor_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "isSubProcess", column = "is_sub_process", javaType = Flag.class, typeHandler = EnumOrdinalTypeHandler.class, jdbcType = JdbcType.TINYINT), + @Result(property = "locations", column = "locations", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "connects", column = "connects", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "historyCmd", column = "history_cmd", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "dependenceScheduleTimes", column = "dependence_schedule_times", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "duration", column = "duration", javaType = Long.class, jdbcType = JdbcType.BIGINT), + @Result(property = "processInstanceJson", column = "process_instance_json", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "processInstancePriority", column = "process_instance_priority", javaType = Priority.class, typeHandler = EnumOrdinalTypeHandler.class, jdbcType = JdbcType.TINYINT) + + }) + @SelectProvider(type = ProcessInstanceMapperProvider.class, method = "queryProcessInstanceListPaging") + List queryProcessInstanceListPaging(@Param("projectId") int projectId, + @Param("processDefinitionId") Integer processDefinitionId, + @Param("searchVal") String searchVal, + @Param("states")String statusArray, + @Param("host")String host, + @Param("startTime") Date startTime, + @Param("endTime") Date endTime, + @Param("offset") int offset, + @Param("pageSize") int pageSize); + + /** + * count process numbers + * @param projectId + * @param processDefinitionId + * @param statusArray + * @param startTime + * @param endTime + * @param searchVal + * @return + */ + @SelectProvider(type = ProcessInstanceMapperProvider.class, method = "countProcessInstance") + Integer countProcessInstance(@Param("projectId") int projectId, + @Param("processDefinitionId") Integer processDefinitionId, + @Param("states")String statusArray, + @Param("host")String host, + @Param("startTime") Date startTime, + @Param("endTime") Date endTime, + @Param("searchVal") String searchVal + ); + + /** + * update process instance by host and status + * @param host + * @param stateArray + * @return + */ + @UpdateProvider(type = ProcessInstanceMapperProvider.class, method = "setFailoverByHostAndStateArray") + int setFailoverByHostAndStateArray(@Param("host") String host,@Param("states")int[] stateArray); + + /** + * update process instance by state + * @param originState + * @param destState + * @return + */ + @UpdateProvider(type = ProcessInstanceMapperProvider.class, method = "updateProcessInstanceByState") + int updateProcessInstanceByState(@Param("originState")ExecutionStatus originState, @Param("destState")ExecutionStatus destState); + + /** + * update state + * @param processId + * @param executionStatus + * @return + */ + @UpdateProvider(type = ProcessInstanceMapperProvider.class, method = "updateState") + int updateState(@Param("processId")Integer processId, @Param("executionStatus")ExecutionStatus executionStatus); + + + /** + * query process instance by task id + * @param taskId + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "processDefinitionId", column = "process_definition_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "state", column = "state", typeHandler = EnumOrdinalTypeHandler.class, javaType = ExecutionStatus.class, jdbcType = JdbcType.TINYINT), + @Result(property = "recovery", column = "recovery", typeHandler = EnumOrdinalTypeHandler.class, javaType = Flag.class, jdbcType = JdbcType.TINYINT), + @Result(property = "startTime", column = "start_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "endTime", column = "end_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "runTimes", column = "run_times", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "name", column = "name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "host", column = "host", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "commandType", column = "command_type", typeHandler = EnumOrdinalTypeHandler.class, javaType = CommandType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "commandParam", column = "command_param", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "taskDependType", column = "task_depend_type", typeHandler = EnumOrdinalTypeHandler.class, javaType = TaskDependType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "maxTryTimes", column = "max_try_times", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "failureStrategy", column = "failure_strategy", typeHandler = EnumOrdinalTypeHandler.class, javaType = FailureStrategy.class, jdbcType = JdbcType.TINYINT), + @Result(property = "warningType", column = "warning_type", javaType = WarningType.class, typeHandler = EnumOrdinalTypeHandler.class, jdbcType = JdbcType.TINYINT), + @Result(property = "warningGroupId", column = "warning_group_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "scheduleTime", column = "schedule_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "commandStartTime", column = "command_start_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "globalParams", column = "global_params", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "executorId", column = "executor_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "isSubProcess", column = "is_sub_process", javaType = Flag.class, typeHandler = EnumOrdinalTypeHandler.class, jdbcType = JdbcType.TINYINT), + @Result(property = "locations", column = "locations", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "connects", column = "connects", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "historyCmd", column = "history_cmd", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "duration", column = "duration", javaType = Long.class, jdbcType = JdbcType.BIGINT), + @Result(property = "dependenceScheduleTimes", column = "dependence_schedule_times", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "duration", column = "duration", javaType = Long.class, jdbcType = JdbcType.BIGINT), + @Result(property = "processInstanceJson", column = "process_instance_json", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "processInstancePriority", column = "process_instance_priority", javaType = Priority.class, typeHandler = EnumOrdinalTypeHandler.class, jdbcType = JdbcType.TINYINT) + + }) + @SelectProvider(type = ProcessInstanceMapperProvider.class, method = "queryByTaskId") + ProcessInstance queryByTaskId(@Param("taskId") int taskId); + + + /** + * update process instance + * @param processId + * @param processJson + * @param globalParams + * @param scheduleTime + * @param locations + * @param connects + * @param flag + * @return + */ + @UpdateProvider(type = ProcessInstanceMapperProvider.class, method = "updateProcessInstance") + int updateProcessInstance(@Param("processId") Integer processId, + @Param("processJson") String processJson, + @Param("globalParams") String globalParams, + @Param("scheduleTime") Date scheduleTime, + @Param("locations") String locations, + @Param("connects") String connects, + @Param("flag") Flag flag); + + /** + * count process number group by state and user + * @param userId + * @param userType + * @param startTime + * @param endTime + * @param projectId + * @return + */ + @Results(value = { + @Result(property = "state", column = "state", typeHandler = EnumOrdinalTypeHandler.class, javaType = ExecutionStatus.class, jdbcType = JdbcType.TINYINT), + @Result(property = "count", column = "count", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + }) + @SelectProvider(type = ProcessInstanceMapperProvider.class, method = "countInstanceStateByUser") + List countInstanceStateByUser( + @Param("userId") int userId, + @Param("userType") UserType userType, + @Param("startTime") Date startTime, + @Param("endTime") Date endTime, + @Param("projectId") int projectId); + + /** + * query sub process id list by father process instance id + * + * @param parentInstanceId + * @return + */ + @SelectProvider(type = ProcessInstanceMapperProvider.class, method = "querySubIdListByParentId") + List querySubIdListByParentId(@Param("parentInstanceId") int parentInstanceId); + + /** + * query instance by definition id + * @param processDefinitionId + * @param size + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "processDefinitionId", column = "process_definition_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "state", column = "state", typeHandler = EnumOrdinalTypeHandler.class, javaType = ExecutionStatus.class, jdbcType = JdbcType.TINYINT), + @Result(property = "recovery", column = "recovery", typeHandler = EnumOrdinalTypeHandler.class, javaType = Flag.class, jdbcType = JdbcType.TINYINT), + @Result(property = "startTime", column = "start_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "endTime", column = "end_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "runTimes", column = "run_times", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "name", column = "name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "host", column = "host", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "commandType", column = "command_type", typeHandler = EnumOrdinalTypeHandler.class, javaType = CommandType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "commandParam", column = "command_param", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "taskDependType", column = "task_depend_type", typeHandler = EnumOrdinalTypeHandler.class, javaType = TaskDependType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "maxTryTimes", column = "max_try_times", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "failureStrategy", column = "failure_strategy", typeHandler = EnumOrdinalTypeHandler.class, javaType = FailureStrategy.class, jdbcType = JdbcType.TINYINT), + @Result(property = "warningType", column = "warning_type", javaType = WarningType.class, typeHandler = EnumOrdinalTypeHandler.class, jdbcType = JdbcType.TINYINT), + @Result(property = "warningGroupId", column = "warning_group_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "scheduleTime", column = "schedule_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "commandStartTime", column = "command_start_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "globalParams", column = "global_params", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "executorId", column = "executor_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "isSubProcess", column = "is_sub_process", javaType = Flag.class, typeHandler = EnumOrdinalTypeHandler.class, jdbcType = JdbcType.TINYINT), + @Result(property = "locations", column = "locations", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "connects", column = "connects", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "historyCmd", column = "history_cmd", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "duration", column = "duration", javaType = Long.class, jdbcType = JdbcType.BIGINT), + @Result(property = "dependenceScheduleTimes", column = "dependence_schedule_times", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "duration", column = "duration", javaType = Long.class, jdbcType = JdbcType.BIGINT), + @Result(property = "processInstanceJson", column = "process_instance_json", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "processInstancePriority", column = "process_instance_priority", javaType = Priority.class, typeHandler = EnumOrdinalTypeHandler.class, jdbcType = JdbcType.TINYINT) + + }) + @SelectProvider(type = ProcessInstanceMapperProvider.class, method = "queryByProcessDefineId") + List queryByProcessDefineId(@Param("processDefinitionId") int processDefinitionId,@Param("size") int size); + + + /** + * query process instance by definition and scheduler time + * @param processDefinitionId + * @param scheduleTime + * @param excludeId + * @param startTime + * @param endTime + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "processDefinitionId", column = "process_definition_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "state", column = "state", typeHandler = EnumOrdinalTypeHandler.class, javaType = ExecutionStatus.class, jdbcType = JdbcType.TINYINT), + @Result(property = "recovery", column = "recovery", typeHandler = EnumOrdinalTypeHandler.class, javaType = Flag.class, jdbcType = JdbcType.TINYINT), + @Result(property = "startTime", column = "start_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "endTime", column = "end_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "runTimes", column = "run_times", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "name", column = "name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "host", column = "host", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "commandType", column = "command_type", typeHandler = EnumOrdinalTypeHandler.class, javaType = CommandType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "commandParam", column = "command_param", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "taskDependType", column = "task_depend_type", typeHandler = EnumOrdinalTypeHandler.class, javaType = TaskDependType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "maxTryTimes", column = "max_try_times", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "failureStrategy", column = "failure_strategy", typeHandler = EnumOrdinalTypeHandler.class, javaType = FailureStrategy.class, jdbcType = JdbcType.TINYINT), + @Result(property = "warningType", column = "warning_type", javaType = WarningType.class, typeHandler = EnumOrdinalTypeHandler.class, jdbcType = JdbcType.TINYINT), + @Result(property = "warningGroupId", column = "warning_group_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "scheduleTime", column = "schedule_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "commandStartTime", column = "command_start_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "globalParams", column = "global_params", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "executorId", column = "executor_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "isSubProcess", column = "is_sub_process", javaType = Flag.class, typeHandler = EnumOrdinalTypeHandler.class, jdbcType = JdbcType.TINYINT), + @Result(property = "locations", column = "locations", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "connects", column = "connects", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "historyCmd", column = "history_cmd", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "dependenceScheduleTimes", column = "dependence_schedule_times", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "duration", column = "duration", javaType = Long.class, jdbcType = JdbcType.BIGINT), + @Result(property = "processInstanceJson", column = "process_instance_json", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "processInstancePriority", column = "process_instance_priority", javaType = Priority.class, typeHandler = EnumOrdinalTypeHandler.class, jdbcType = JdbcType.TINYINT) + + }) + @SelectProvider(type = ProcessInstanceMapperProvider.class, method = "queryByScheduleTime") + ProcessInstance queryByScheduleTime(@Param("processDefinitionId") int processDefinitionId, + @Param("scheduleTime") String scheduleTime, + @Param("excludeId") int excludeId, + @Param("startTime") String startTime, + @Param("endTime") String endTime); + + /** + * get last scheduler process intance between start time and end time + * @param definitionId + * @param startTime + * @param endTime + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "processDefinitionId", column = "process_definition_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "state", column = "state", typeHandler = EnumOrdinalTypeHandler.class, javaType = ExecutionStatus.class, jdbcType = JdbcType.TINYINT), + @Result(property = "recovery", column = "recovery", typeHandler = EnumOrdinalTypeHandler.class, javaType = Flag.class, jdbcType = JdbcType.TINYINT), + @Result(property = "startTime", column = "start_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "endTime", column = "end_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "runTimes", column = "run_times", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "name", column = "name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "host", column = "host", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "commandType", column = "command_type", typeHandler = EnumOrdinalTypeHandler.class, javaType = CommandType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "commandParam", column = "command_param", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "taskDependType", column = "task_depend_type", typeHandler = EnumOrdinalTypeHandler.class, javaType = TaskDependType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "maxTryTimes", column = "max_try_times", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "failureStrategy", column = "failure_strategy", typeHandler = EnumOrdinalTypeHandler.class, javaType = FailureStrategy.class, jdbcType = JdbcType.TINYINT), + @Result(property = "warningType", column = "warning_type", javaType = WarningType.class, typeHandler = EnumOrdinalTypeHandler.class, jdbcType = JdbcType.TINYINT), + @Result(property = "warningGroupId", column = "warning_group_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "scheduleTime", column = "schedule_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "commandStartTime", column = "command_start_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "globalParams", column = "global_params", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "executorId", column = "executor_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "isSubProcess", column = "is_sub_process", javaType = Flag.class, typeHandler = EnumOrdinalTypeHandler.class, jdbcType = JdbcType.TINYINT), + @Result(property = "locations", column = "locations", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "connects", column = "connects", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "historyCmd", column = "history_cmd", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "dependenceScheduleTimes", column = "dependence_schedule_times", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "processInstanceJson", column = "process_instance_json", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "processInstancePriority", column = "process_instance_priority", javaType = Priority.class, typeHandler = EnumOrdinalTypeHandler.class, jdbcType = JdbcType.TINYINT) + + }) + @SelectProvider(type = ProcessInstanceMapperProvider.class, method = "queryLastSchedulerProcess") + ProcessInstance queryLastSchedulerProcess(@Param("processDefinitionId") int definitionId, + @Param("startTime") String startTime, + @Param("endTime") String endTime); + + /** + * get last running process instance between start time and end time + * @param definitionId + * @param startTime + * @param endTime + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "processDefinitionId", column = "process_definition_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "state", column = "state", typeHandler = EnumOrdinalTypeHandler.class, javaType = ExecutionStatus.class, jdbcType = JdbcType.TINYINT), + @Result(property = "recovery", column = "recovery", typeHandler = EnumOrdinalTypeHandler.class, javaType = Flag.class, jdbcType = JdbcType.TINYINT), + @Result(property = "startTime", column = "start_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "endTime", column = "end_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "runTimes", column = "run_times", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "name", column = "name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "host", column = "host", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "commandType", column = "command_type", typeHandler = EnumOrdinalTypeHandler.class, javaType = CommandType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "commandParam", column = "command_param", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "taskDependType", column = "task_depend_type", typeHandler = EnumOrdinalTypeHandler.class, javaType = TaskDependType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "maxTryTimes", column = "max_try_times", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "failureStrategy", column = "failure_strategy", typeHandler = EnumOrdinalTypeHandler.class, javaType = FailureStrategy.class, jdbcType = JdbcType.TINYINT), + @Result(property = "warningType", column = "warning_type", javaType = WarningType.class, typeHandler = EnumOrdinalTypeHandler.class, jdbcType = JdbcType.TINYINT), + @Result(property = "warningGroupId", column = "warning_group_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "scheduleTime", column = "schedule_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "commandStartTime", column = "command_start_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "globalParams", column = "global_params", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "executorId", column = "executor_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "isSubProcess", column = "is_sub_process", javaType = Flag.class, typeHandler = EnumOrdinalTypeHandler.class, jdbcType = JdbcType.TINYINT), + @Result(property = "locations", column = "locations", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "connects", column = "connects", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "historyCmd", column = "history_cmd", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "dependenceScheduleTimes", column = "dependence_schedule_times", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "processInstanceJson", column = "process_instance_json", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "processInstancePriority", column = "process_instance_priority", javaType = Priority.class, typeHandler = EnumOrdinalTypeHandler.class, jdbcType = JdbcType.TINYINT) + }) + @SelectProvider(type = ProcessInstanceMapperProvider.class, method = "queryLastRunningProcess") + ProcessInstance queryLastRunningProcess(@Param("processDefinitionId") int definitionId, + @Param("startTime") String startTime, + @Param("endTime") String endTime, + @Param("states")int[] stateArray); + + /** + * get last manual process instance between start time and end time + * @param definitionId + * @param startTime + * @param endTime + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "processDefinitionId", column = "process_definition_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "state", column = "state", typeHandler = EnumOrdinalTypeHandler.class, javaType = ExecutionStatus.class, jdbcType = JdbcType.TINYINT), + @Result(property = "recovery", column = "recovery", typeHandler = EnumOrdinalTypeHandler.class, javaType = Flag.class, jdbcType = JdbcType.TINYINT), + @Result(property = "startTime", column = "start_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "endTime", column = "end_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "runTimes", column = "run_times", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "name", column = "name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "host", column = "host", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "commandType", column = "command_type", typeHandler = EnumOrdinalTypeHandler.class, javaType = CommandType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "commandParam", column = "command_param", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "taskDependType", column = "task_depend_type", typeHandler = EnumOrdinalTypeHandler.class, javaType = TaskDependType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "maxTryTimes", column = "max_try_times", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "failureStrategy", column = "failure_strategy", typeHandler = EnumOrdinalTypeHandler.class, javaType = FailureStrategy.class, jdbcType = JdbcType.TINYINT), + @Result(property = "warningType", column = "warning_type", javaType = WarningType.class, typeHandler = EnumOrdinalTypeHandler.class, jdbcType = JdbcType.TINYINT), + @Result(property = "warningGroupId", column = "warning_group_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "scheduleTime", column = "schedule_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "commandStartTime", column = "command_start_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "globalParams", column = "global_params", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "executorId", column = "executor_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "isSubProcess", column = "is_sub_process", javaType = Flag.class, typeHandler = EnumOrdinalTypeHandler.class, jdbcType = JdbcType.TINYINT), + @Result(property = "locations", column = "locations", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "connects", column = "connects", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "historyCmd", column = "history_cmd", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "dependenceScheduleTimes", column = "dependence_schedule_times", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "processInstanceJson", column = "process_instance_json", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "processInstancePriority", column = "process_instance_priority", javaType = Priority.class, typeHandler = EnumOrdinalTypeHandler.class, jdbcType = JdbcType.TINYINT) + }) + @SelectProvider(type = ProcessInstanceMapperProvider.class, method = "queryLastManualProcess") + ProcessInstance queryLastManualProcess(@Param("processDefinitionId") int definitionId, + @Param("startTime") String startTime, + @Param("endTime") String endTime); +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ProcessInstanceMapperProvider.java b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ProcessInstanceMapperProvider.java new file mode 100644 index 0000000000..05e1538c8d --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ProcessInstanceMapperProvider.java @@ -0,0 +1,582 @@ +/* + * 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.dao.mapper; + +import cn.escheduler.common.enums.*; +import cn.escheduler.common.utils.EnumFieldUtil; +import org.apache.commons.lang3.StringUtils; +import org.apache.ibatis.jdbc.SQL; + +import java.util.Map; + +/** + * process instance mapper provider + */ +public class ProcessInstanceMapperProvider { + + private static final String TABLE_NAME = "t_escheduler_process_instance"; + private static final String TABLE_NAME_MAP = "t_escheduler_relation_process_instance"; + private static final String DEFINE_TABLE_NAME = "t_escheduler_process_definition"; + + /** + * insert process instance + * + * @param parameter + * @return + */ + public String insert(Map parameter) { + return new SQL() { + { + INSERT_INTO(TABLE_NAME); + VALUES("`process_definition_id`", "#{processInstance.processDefinitionId}"); + VALUES("`state`", EnumFieldUtil.genFieldStr("processInstance.state", ExecutionStatus.class)); + VALUES("`recovery`", EnumFieldUtil.genFieldStr("processInstance.recovery", Flag.class)); + VALUES("`start_time`", "#{processInstance.startTime}"); + VALUES("`end_time`", "#{processInstance.endTime}"); + VALUES("`run_times`", "#{processInstance.runTimes}"); + VALUES("`name`", "#{processInstance.name}"); + VALUES("`host`", "#{processInstance.host}"); + VALUES("`command_type`", EnumFieldUtil.genFieldStr("processInstance.commandType", CommandType.class)); + VALUES("`command_param`", "#{processInstance.commandParam}"); + VALUES("`task_depend_type`", EnumFieldUtil.genFieldStr("processInstance.taskDependType", TaskDependType.class)); + VALUES("`max_try_times`", "#{processInstance.maxTryTimes}"); + VALUES("`failure_strategy`", EnumFieldUtil.genFieldStr("processInstance.failureStrategy", FailureStrategy.class)); + VALUES("`warning_type`", EnumFieldUtil.genFieldStr("processInstance.warningType", WarningType.class)); + VALUES("`warning_group_id`", "#{processInstance.warningGroupId}"); + VALUES("`schedule_time`", "#{processInstance.scheduleTime}"); + VALUES("`command_start_time`", "#{processInstance.commandStartTime}"); + VALUES("`global_params`", "#{processInstance.globalParams}"); + VALUES("`process_instance_json`", "#{processInstance.processInstanceJson}"); + VALUES("`locations`", "#{processInstance.locations}"); + VALUES("`connects`", "#{processInstance.connects}"); + VALUES("`history_cmd`", "#{processInstance.historyCmd}"); + VALUES("`dependence_schedule_times`", "#{processInstance.dependenceScheduleTimes}"); + VALUES("`is_sub_process`", EnumFieldUtil.genFieldStr("processInstance.isSubProcess", Flag.class)); + VALUES("`executor_id`", "#{processInstance.executorId}"); + VALUES("`process_instance_priority`", EnumFieldUtil.genFieldStr("processInstance.processInstancePriority", Priority.class)); + } + }.toString(); + } + + /** + * delete process instance + * + * @param parameter + * @return + */ + public String delete(Map parameter) { + return new SQL() { + { + DELETE_FROM(TABLE_NAME); + WHERE("id=#{processId}"); + } + }.toString(); + } + + + /** + * 根据父工作流id查询子工作流list + * @param parameter + * @return + */ + public String querySubIdListByParentId(Map parameter) { + return new SQL() { + { + SELECT( "process_instance_id"); + FROM(TABLE_NAME_MAP); + WHERE("parent_process_instance_id = #{parentInstanceId}" ); + } + }.toString(); + } + + /** + * 更新流程实例 + * + * @param parameter + * @return + */ + public String update(Map parameter) { + return new SQL() { + { + UPDATE(TABLE_NAME); + + SET("`process_definition_id`=#{processInstance.processDefinitionId}"); + SET("`state`="+EnumFieldUtil.genFieldStr("processInstance.state", ExecutionStatus.class)); + SET("`recovery`="+EnumFieldUtil.genFieldStr("processInstance.recovery", Flag.class)); + SET("`start_time`=#{processInstance.startTime}"); + SET("`end_time`=#{processInstance.endTime}"); + SET("`run_times`=#{processInstance.runTimes}"); + SET("`name`=#{processInstance.name}"); + SET("`host`=#{processInstance.host}"); + SET("`command_type`="+EnumFieldUtil.genFieldStr("processInstance.commandType", CommandType.class)); + SET("`command_param`=#{processInstance.commandParam}"); + SET("`task_depend_type`="+EnumFieldUtil.genFieldStr("processInstance.taskDependType", TaskDependType.class)); + SET("`max_try_times`=#{processInstance.maxTryTimes}"); + SET("`failure_strategy`="+EnumFieldUtil.genFieldStr("processInstance.failureStrategy", FailureStrategy.class)); + SET("`warning_type`="+ EnumFieldUtil.genFieldStr("processInstance.warningType", WarningType.class)); + SET("`warning_group_id`=#{processInstance.warningGroupId}"); + SET("`schedule_time`=#{processInstance.scheduleTime}"); + SET("`command_start_time`=#{processInstance.commandStartTime}"); + SET("`process_instance_json`=#{processInstance.processInstanceJson}"); + SET("`global_params`=#{processInstance.globalParams}"); + SET("`locations`=#{processInstance.locations}"); + SET("`connects`=#{processInstance.connects}"); + SET("`history_cmd`=#{processInstance.historyCmd}"); + SET("`dependence_schedule_times`=#{processInstance.dependenceScheduleTimes}"); + SET("`is_sub_process`="+EnumFieldUtil.genFieldStr("processInstance.isSubProcess", Flag.class)); + SET("`executor_id`=#{processInstance.executorId}"); + + WHERE("`id`=#{processInstance.id}"); + + } + }.toString(); + } + + public String updateProcessInstance(Map parameter) { + return new SQL() { + { + UPDATE(TABLE_NAME); + if(parameter.get("flag") != null){ + SET("`flag`="+ EnumFieldUtil.genFieldStr("flag", Flag.class)); + } + + if(parameter.get("scheduleTime") != null){ + SET("`schedule_time`=#{scheduleTime}"); + } + + if(parameter.get("processJson") != null){ + SET("`process_instance_json`=#{processJson}"); + SET("`global_params`=#{globalParams}"); + } + if(parameter.get("locations") != null){ + SET("`locations`=#{locations}"); + } + if(parameter.get("connects") != null){ + SET("`connects`=#{connects}"); + } + WHERE("`id`=#{processId}"); + + } + }.toString(); + } + + /** + * update process instance by state + * @param parameter + * @return + */ + public String updateProcessInstanceByState(Map parameter) { + + return new SQL() { + { + UPDATE(TABLE_NAME); + + SET("`state`=" + EnumFieldUtil.genFieldStr("destState", ExecutionStatus.class)); + WHERE("`state`=" + EnumFieldUtil.genFieldStr("originState", ExecutionStatus.class)); + } + }.toString(); + } + + /** + * update state + * @param parameter + * @return + */ + public String updateState(Map parameter) { + + return new SQL() { + { + UPDATE(TABLE_NAME); + + SET("`state`=" + EnumFieldUtil.genFieldStr("executionStatus", ExecutionStatus.class)); + WHERE("`id`=#{processId}"); + } + }.toString(); + } + + /** + * query detail by id + * @param parameter + * @return + */ + public String queryDetailById(Map parameter) { + return new SQL() { + { + SELECT("inst.*,q.queue_name as queue,t.tenant_code as tenantCode,UNIX_TIMESTAMP(inst.end_time)-UNIX_TIMESTAMP(inst.start_time) as duration"); + + FROM(TABLE_NAME + " inst, t_escheduler_user u,t_escheduler_tenant t,t_escheduler_queue q"); + + WHERE("inst.executor_id = u.id AND u.tenant_id = t.id AND t.queue_id = q.id AND inst.id = #{processId}"); + } + }.toString(); + } + + /** + * query by id + * @param parameter + * @return + */ + public String queryById(Map parameter) { + return new SQL() { + { + SELECT("*"); + + FROM(TABLE_NAME ); + + WHERE("`id` = #{processId}"); + } + }.toString(); + } + + /** + * query list paging + * @param parameter + * @return + */ + public String queryProcessInstanceListPaging(Map parameter) { + return new SQL() { + { + SELECT("instance.*, (UNIX_TIMESTAMP(instance.end_time) - UNIX_TIMESTAMP(instance.start_time)) as duration"); + + FROM(TABLE_NAME + " instance"); + + JOIN(DEFINE_TABLE_NAME + " define ON instance.process_definition_id = define.id"); + + if(parameter.get("processDefinitionId") != null && (int)parameter.get("processDefinitionId") != 0){ + WHERE( "instance.process_definition_id = #{processDefinitionId} "); + } + + WHERE("instance.is_sub_process=0 and define.project_id = #{projectId}"); + + Object start = parameter.get("startTime"); + if(start != null && StringUtils.isNotEmpty(start.toString())){ + WHERE("instance.start_time > #{startTime} and instance.start_time <= #{endTime}"); + } + + Object searchVal = parameter.get("searchVal"); + if(searchVal != null && StringUtils.isNotEmpty(searchVal.toString())){ + WHERE( " instance.name like concat('%', #{searchVal}, '%') "); + } + Object states = parameter.get("states"); + if(states != null && StringUtils.isNotEmpty(states.toString())){ + String stateStr = states.toString(); + WHERE("instance.state in ( "+ stateStr + " )"); + } + Object host = parameter.get("host"); + if(host != null && StringUtils.isNotEmpty(host.toString())){ + WHERE( "instance.host like concat('%', #{host}, '%') "); + } + ORDER_BY("instance.start_time desc limit #{offset},#{pageSize} "); + } + }.toString(); + + } + + public String countProcessInstance(Map parameter) { + return new SQL() { + { + SELECT("count(1)"); + FROM(TABLE_NAME + " instance"); + JOIN(DEFINE_TABLE_NAME + " define ON instance.process_definition_id = define.id"); + WHERE(" define.project_id = #{projectId}"); + if(parameter.get("processDefinitionId") != null && (int)parameter.get("processDefinitionId") != 0){ + WHERE( "instance.process_definition_id = #{processDefinitionId} "); + } + WHERE(" instance.is_sub_process=0"); + Object startTime = parameter.get("startTime"); + if(startTime != null && StringUtils.isNotEmpty(startTime.toString())) { + WHERE("instance.start_time > #{startTime} and instance.start_time <= #{endTime}"); + } + Object searchVal = parameter.get("searchVal"); + if(searchVal != null && StringUtils.isNotEmpty(searchVal.toString())){ + WHERE( " instance.name like concat('%', #{searchVal}, '%') "); + } + Object states = parameter.get("states"); + if(states != null && StringUtils.isNotEmpty(states.toString())){ + String stateStr = states.toString(); + WHERE("instance.state in ( "+ stateStr + " )"); + } + Object host = parameter.get("host"); + if(host != null && StringUtils.isNotEmpty(host.toString())){ + WHERE( "instance.host like concat('%', #{host}, '%') "); + } + } + }.toString(); + } + + public String countInstanceStateByUser(Map parameter){ + return new SQL(){ + { + SELECT ("state, count(0) as count"); + FROM(TABLE_NAME + " t"); + JOIN(DEFINE_TABLE_NAME + " d on d.id=t.process_definition_id"); + JOIN("t_escheduler_project p on p.id=d.project_id"); + WHERE("t.flag = 1 and t.is_sub_process = 0"); + WHERE("t.start_time > #{startTime} and t.start_time <= #{endTime}"); + if(parameter.get("projectId") != null && (int)parameter.get("projectId") != 0){ + WHERE( "p.id = #{projectId} "); + }else{ + if(parameter.get("userType") != null && String.valueOf(parameter.get("userType")) == "GENERAL_USER") { + AND(); + WHERE(" p.id in (select project_id as id from `t_escheduler_relation_project_user` where user_id=#{userId} \n" + + "union select id as id from `t_escheduler_project` where user_id =#{userId})"); + } + } + GROUP_BY("t.state"); + } + }.toString(); + } + + /** + * list all processes by status + * + * @param parameter + * @return + */ + public String listByStatus(Map parameter) { + StringBuffer strStates = new StringBuffer(); + int[] stateArray = (int[]) parameter.get("states"); + + for(int i=0;i parameter) { + StringBuffer strStates = new StringBuffer(); + int[] stateArray = (int[]) parameter.get("states"); + + for(int i=0;i parameter) { + StringBuffer strStates = new StringBuffer(); + int[] stateArray = (int[]) parameter.get("states"); + + for(int i=0;i parameter) { + return new SQL() { + { + SELECT("process.*, UNIX_TIMESTAMP(process.end_time)-UNIX_TIMESTAMP(process.start_time) as duration"); + + FROM(TABLE_NAME + " process"); + + JOIN("t_escheduler_task_instance task"); + + WHERE("task.process_instance_id = process.id"); + + WHERE("task.id=#{taskId}"); + } + }.toString(); + } + + /** + * query instance by definition id + * @param parameter + * @return + */ + public String queryByProcessDefineId(Map parameter) { + return new SQL() { + { + SELECT("*,UNIX_TIMESTAMP(end_time)-UNIX_TIMESTAMP(start_time) as duration"); + + FROM(TABLE_NAME); + + WHERE("process_definition_id=#{processDefinitionId}"); + ORDER_BY("start_time desc limit #{size}"); + } + }.toString(); + } + + /** + * query process instance by definition and scheduler time + * @param parameter + * @return + */ + public String queryByScheduleTime(Map parameter) { + return new SQL() { + { + SELECT("*,UNIX_TIMESTAMP(end_time)-UNIX_TIMESTAMP(start_time) as duration"); + + FROM(TABLE_NAME); + + WHERE("process_definition_id=#{processDefinitionId} "); + if(parameter.get("scheduleTime") != null){ + WHERE("schedule_time=#{scheduleTime}"); + } + if(parameter.get("startTime") != null && parameter.get("endTime")!= null){ + WHERE("command_start_time between #{startTime} and #{endTime}"); + } + if(parameter.get("excludeId") != null && Integer.parseInt(parameter.get("excludeId").toString())!= 0){ + WHERE(" id not in ( #{excludeId}) "); + } + ORDER_BY("start_time desc limit 1"); + } + }.toString(); + } + + public String queryLastSchedulerProcess(Map parameter) { + return new SQL() { + { + SELECT("*"); + + FROM(TABLE_NAME); + + WHERE("process_definition_id=#{processDefinitionId} "); + if(parameter.get("startTime") != null && parameter.get("endTime") != null){ + WHERE("schedule_time between #{startTime} and #{endTime}"); + } + + ORDER_BY("end_time desc limit 1"); + } + }.toString(); + } + + public String queryLastManualProcess(Map parameter) { + return new SQL() { + { + SELECT("*"); + + FROM(TABLE_NAME); + + WHERE("process_definition_id=#{processDefinitionId} "); + if(parameter.get("startTime") != null && parameter.get("endTime") != null){ + WHERE("start_time between #{startTime} and #{endTime}"); + WHERE("`schedule_time` is null"); + } + ORDER_BY("end_time desc limit 1"); + } + }.toString(); + } + + public String queryLastRunningProcess(Map parameter) { + StringBuffer strStates = new StringBuffer(); + int[] stateArray = (int[]) parameter.get("states"); + + for(int i=0;i queryProjectListPaging(@Param("userId") Integer userId, + @Param("offset") Integer offset, + @Param("pageSize") Integer pageSize, + @Param("searchVal") String searchVal); + + /** + * count all projects + * @param searchVal + * @return + */ + @SelectProvider(type = ProjectMapperProvider.class, method = "countAllProjects") + Integer countAllProjects(@Param("searchVal") String searchVal); + + /** + * query all project list paging + * @param offset + * @param pageSize + * @param searchVal + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "userId", column = "user_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "name", column = "name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "userName", column = "user_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "desc", column = "desc", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "perm", column = "perm", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "createTime", column = "create_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "updateTime", column = "update_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + }) + @SelectProvider(type = ProjectMapperProvider.class, method = "queryAllProjectListPaging") + List queryAllProjectListPaging( + @Param("offset") Integer offset, + @Param("pageSize") Integer pageSize, + @Param("searchVal") String searchVal); + + /** + * authed project to user + * @param userId + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "userId", column = "user_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "name", column = "name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "userName", column = "user_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "desc", column = "desc", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "perm", column = "perm", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "createTime", column = "create_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "updateTime", column = "update_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + }) + @SelectProvider(type = ProjectMapperProvider.class, method = "authedProject") + List authedProject(@Param("userId") Integer userId); + + /** + * query project except user + * @param userId + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "userId", column = "user_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "name", column = "name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "userName", column = "user_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "desc", column = "desc", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "perm", column = "perm", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "createTime", column = "create_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "updateTime", column = "update_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + }) + @SelectProvider(type = ProjectMapperProvider.class, method = "queryProjectExceptUserId") + List queryProjectExceptUserId(@Param("userId") Integer userId); + + +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ProjectMapperProvider.java b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ProjectMapperProvider.java new file mode 100644 index 0000000000..87d74cda4e --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ProjectMapperProvider.java @@ -0,0 +1,242 @@ +/* + * 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.dao.mapper; + +import org.apache.commons.lang3.StringUtils; +import org.apache.ibatis.jdbc.SQL; + +import java.util.Map; + +/** + * project mapper provider + */ +public class ProjectMapperProvider { + + private static final String TABLE_NAME = "t_escheduler_project"; + private static final String RELEATION_TABLE_NAME = "t_escheduler_relation_project_user"; + + /** + * insert project + * + * @param parameter + * @return + */ + public String insert(Map parameter) { + return new SQL() { + { + INSERT_INTO(TABLE_NAME); + VALUES("`user_id`", "#{project.userId}"); + VALUES("`name`", "#{project.name}"); + VALUES("`desc`", "#{project.desc}"); + } + }.toString(); + } + + /** + * delete project + * + * @param parameter + * @return + */ + public String delete(Map parameter) { + return new SQL() { + { + UPDATE(TABLE_NAME); + SET("flag=0"); + WHERE("`id`=#{projectId}"); + } + }.toString(); + } + + /** + * update project + * + * @param parameter + * @return + */ + public String update(Map parameter) { + return new SQL() { + { + UPDATE(TABLE_NAME); + + SET("`user_id`=#{project.userId}"); + SET("`name`=#{project.name}"); + SET("`desc`=#{project.desc}"); + SET("`update_time`=#{project.updateTime}"); + WHERE("`id`=#{project.id}"); + } + }.toString(); + } + + + + + /** + * query project by id + * + * @param parameter + * @return + */ + public String queryById(Map parameter) { + return new SQL() {{ + SELECT("p.user_id"); + SELECT("u.user_name as userName"); + SELECT("p.*"); + + FROM(TABLE_NAME + " p"); + + JOIN("t_escheduler_user u on p.user_id = u.id"); + + WHERE("p.id = #{projectId}"); + }}.toString(); + } + + + /** + * query project by name + * + * @param parameter + * @return + */ + public String queryByName(Map parameter) { + return new SQL() {{ + SELECT("p.user_id"); + SELECT("u.user_name as userName"); + SELECT("p.*"); + + FROM(TABLE_NAME + " p"); + + JOIN("t_escheduler_user u on p.user_id = u.id"); + + WHERE("p.name = #{name}"); + WHERE("p.flag = 1"); + }}.toString(); + } + + /** + * count project by user id and search value + * @param parameter + * @return + */ + public String countProjects(Map parameter) { + return new SQL() {{ + SELECT("count(0)"); + + FROM(TABLE_NAME + " p"); + WHERE("p.id in " + + "(select project_id from "+ RELEATION_TABLE_NAME+" where user_id=#{userId} " + + "union select id as project_id from "+ TABLE_NAME+" where user_id=#{userId})"); + + Object searchVal = parameter.get("searchVal"); + if(searchVal != null && StringUtils.isNotEmpty(searchVal.toString())){ + WHERE( " p.name like concat('%', #{searchVal}, '%') "); + } + WHERE("p.flag = 1"); + }}.toString(); + } + + /** + * query project list paging + * @param parameter + * @return + */ + public String queryProjectListPaging(Map parameter) { + return new SQL() {{ + SELECT("p.*"); + SELECT("u.user_name as user_name"); + + FROM(TABLE_NAME + " p"); + JOIN("t_escheduler_user u on u.id=p.user_id"); + WHERE("p.id in " + + "(select project_id from "+ RELEATION_TABLE_NAME+" where user_id=#{userId} " + + "union select id as project_id from "+ TABLE_NAME+" where user_id=#{userId})"); + + Object searchVal = parameter.get("searchVal"); + if(searchVal != null && StringUtils.isNotEmpty(searchVal.toString())){ + WHERE( " p.name like concat('%', #{searchVal}, '%') "); + } + WHERE(" p.flag = 1"); + ORDER_BY("p.create_time desc limit #{offset},#{pageSize} "); + }}.toString(); + } + + /** + * count all projects + * @return + */ + public String countAllProjects(Map parameter) { + return new SQL() {{ + SELECT("count(0)"); + + FROM(TABLE_NAME ); + + Object searchVal = parameter.get("searchVal"); + if(searchVal != null && StringUtils.isNotEmpty(searchVal.toString())){ + WHERE( " name like concat('%', #{searchVal}, '%') "); + } + WHERE("flag = 1"); + }}.toString(); + } + + /** + * query all project list paging + * @return + */ + public String queryAllProjectListPaging(Map parameter) { + return new SQL() {{ + SELECT("p.*"); + SELECT("u.user_name as user_name"); + + FROM(TABLE_NAME + " p"); + JOIN("t_escheduler_user u on p.user_id = u.id"); + + Object searchVal = parameter.get("searchVal"); + if(searchVal != null && StringUtils.isNotEmpty(searchVal.toString())){ + WHERE( " p.name like concat('%', #{searchVal}, '%') "); + } + WHERE(" p.flag = 1"); + ORDER_BY("p.create_time desc limit #{offset},#{pageSize} "); + }}.toString(); + } + + /** + * authed project to user + * @param parameter + * @return + */ + public String authedProject(Map parameter) { + return new SQL() {{ + SELECT("p.*"); + FROM(TABLE_NAME + " p,t_escheduler_relation_project_user rel"); + WHERE(" p.id = rel.project_id AND p.flag = 1 AND rel.user_id = #{userId}"); + }}.toString(); + } + + /** + * query project except user + * @param parameter + * @return + */ + public String queryProjectExceptUserId(Map parameter) { + return new SQL() {{ + SELECT("*"); + FROM(TABLE_NAME); + WHERE("flag = 1 AND user_id <> #{userId}"); + }}.toString(); + } + +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ProjectUserMapper.java b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ProjectUserMapper.java new file mode 100644 index 0000000000..5805fbe6b1 --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ProjectUserMapper.java @@ -0,0 +1,83 @@ +/* + * 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.dao.mapper; + +import cn.escheduler.dao.model.ProjectUser; +import org.apache.ibatis.annotations.*; +import org.apache.ibatis.type.JdbcType; + +import java.util.Date; + +/** + * project user relation mapper + */ +public interface ProjectUserMapper { + + /** + * insert project user relation + * + * @param projectUser + * @return + */ + @InsertProvider(type = ProjectUserMapperProvider.class, method = "insert") + int insert(@Param("projectUser") ProjectUser projectUser); + + /** + * delete project user relation + * @param projectId + * @param userId + * @return + */ + @DeleteProvider(type = ProjectUserMapperProvider.class, method = "delete") + int delete(@Param("projectId") int projectId, @Param("userId") int userId); + + /** + * update project user relation + * + * @param projectUser + * @return + */ + @UpdateProvider(type = ProjectUserMapperProvider.class, method = "update") + int update(@Param("projectUser") ProjectUser projectUser); + + /** + * query project user relation by project id and user id + * + * @param projectId + * @param userId + * @return + */ + @Results(value = {@Result(property = "projectId", column = "project_id", javaType = int.class, jdbcType = JdbcType.INTEGER), + @Result(property = "projectName", column = "project_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "userId", column = "user_id", javaType = int.class, jdbcType = JdbcType.INTEGER), + @Result(property = "userName", column = "user_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "perm", column = "perm", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "createTime", column = "create_time", javaType = Date.class, jdbcType = JdbcType.TIMESTAMP), + @Result(property = "updateTime", column = "update_time", javaType = Date.class, jdbcType = JdbcType.TIMESTAMP)}) + @SelectProvider(type = ProjectUserMapperProvider.class, method = "query") + ProjectUser query(@Param("projectId") int projectId, @Param("userId") int userId); + + + /** + * delete project relation by user id + * @param userId + * @return + */ + @DeleteProvider(type = ProjectUserMapperProvider.class, method = "deleteByUserId") + int deleteByUserId(@Param("userId") int userId); + +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ProjectUserMapperProvider.java b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ProjectUserMapperProvider.java new file mode 100644 index 0000000000..1461bd89a7 --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ProjectUserMapperProvider.java @@ -0,0 +1,117 @@ +/* + * 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.dao.mapper; + +import org.apache.ibatis.jdbc.SQL; + +import java.util.Map; + +/** + * project user mapper provider + */ +public class ProjectUserMapperProvider { + + private static final String TABLE_NAME = "t_escheduler_relation_project_user"; + private static final String USER_TABLE_NAME = "t_escheduler_user"; + private static final String PROJECT_TABLE_NAME = "t_escheduler_project"; + + + /** + * insert project user relation + * + * @param parameter + * @return + */ + public String insert(Map parameter) { + return new SQL() {{ + INSERT_INTO(TABLE_NAME); + + VALUES("`project_id`", "#{projectUser.projectId}"); + VALUES("`user_id`", "#{projectUser.userId}"); + VALUES("`perm`", "#{projectUser.perm}"); + VALUES("`create_time`", "#{projectUser.createTime}"); + VALUES("`update_time`", "#{projectUser.updateTime}"); + }}.toString(); + } + + /** + * update project user relation + * + * @param parameter + * @return + */ + public String update(Map parameter) { + return new SQL() {{ + UPDATE(TABLE_NAME); + + SET("`perm`=#{projectUser.perm}"); + SET("`update_time`=#{projectUser.updateTime}"); + + WHERE("`project_id` = #{projectUser.projectId}"); + WHERE("`user_id` = #{projectUser.userId}"); + }}.toString(); + } + + /** + * delete project user relation + * + * @param parameter + * @return + */ + public String delete(Map parameter) { + return new SQL() {{ + DELETE_FROM(TABLE_NAME); + + WHERE("`project_id` = #{projectId}"); + WHERE("`user_id` = #{userId}"); + }}.toString(); + } + + /** + * query project user relation by project id and user id + * + * @param parameter + * @return + */ + public String query(Map parameter) { + return new SQL() {{ + SELECT("p_u.*"); + SELECT("u.user_name as user_name, p.name as project_name"); + + FROM(TABLE_NAME + " p_u"); + + JOIN(USER_TABLE_NAME + " u on p_u.user_id = u.id"); + JOIN(PROJECT_TABLE_NAME + " p on p_u.project_id = p.id"); + WHERE("p_u.project_id = #{projectId} "); + WHERE("p_u.user_id = #{userId}"); + }}.toString(); + } + + /** + * delete project relation by user id + * + * @param parameter + * @return + */ + public String deleteByUserId(Map parameter) { + return new SQL() {{ + DELETE_FROM(TABLE_NAME); + + WHERE("`user_id` = #{userId}"); + }}.toString(); + } +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/QueueMapper.java b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/QueueMapper.java new file mode 100644 index 0000000000..534666c463 --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/QueueMapper.java @@ -0,0 +1,88 @@ +/* + * 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.dao.mapper; + +import cn.escheduler.dao.model.Queue; +import org.apache.ibatis.annotations.*; +import org.apache.ibatis.type.JdbcType; + +import java.util.List; + +/** + * queue mapper + */ +public interface QueueMapper { + + /** + * insert queue + * @param queue + * @return + */ + @InsertProvider(type = QueueMapperProvider.class, method = "insert") + @Options(useGeneratedKeys = true,keyProperty = "queue.id") + @SelectKey(statement = "SELECT LAST_INSERT_ID()", keyProperty = "queue.id", before = false, resultType = int.class) + int insert(@Param("queue") Queue queue); + + + /** + * delete queue + * @param queueId + * @return + */ + @DeleteProvider(type = QueueMapperProvider.class, method = "delete") + int delete(@Param("queueId") int queueId); + + + /** + * update queue + * + * @param queue + * @return + */ + @UpdateProvider(type = QueueMapperProvider.class, method = "update") + int update(@Param("queue") Queue queue); + + + /** + * query queue by id + * @param queueId + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "queueName", column = "queue_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "queue", column = "queue", javaType = String.class, jdbcType = JdbcType.VARCHAR) + }) + @SelectProvider(type = QueueMapperProvider.class, method = "queryById") + Queue queryById(@Param("queueId") int queueId); + + + /** + * query all queue list + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "queueName", column = "queue_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "queue", column = "queue", javaType = String.class, jdbcType = JdbcType.VARCHAR) + }) + @SelectProvider(type = QueueMapperProvider.class, method = "queryAllQueue") + List queryAllQueue(); + + + + + +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/QueueMapperProvider.java b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/QueueMapperProvider.java new file mode 100644 index 0000000000..ee829f1557 --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/QueueMapperProvider.java @@ -0,0 +1,121 @@ +/* + * 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.dao.mapper; + +import org.apache.ibatis.jdbc.SQL; + +import java.util.Map; + +/** + * queue mapper provider + */ +public class QueueMapperProvider { + + private static final String TABLE_NAME = "t_escheduler_queue"; + + /** + * insert queue + * + * @param parameter + * @return + */ + public String insert(Map parameter) { + return new SQL() { + { + INSERT_INTO(TABLE_NAME); + VALUES("`queue_name`", "#{queue.queueName}"); + VALUES("`queue`", "#{queue.queue}"); + + } + }.toString(); + } + + /** + * delete queue + * + * @param parameter + * @return + */ + public String delete(Map parameter) { + return new SQL() { + { + DELETE_FROM(TABLE_NAME); + + WHERE("`id`=#{queueId}"); + } + }.toString(); + } + + /** + * update queue + * + * @param parameter + * @return + */ + public String update(Map parameter) { + return new SQL() { + { + UPDATE(TABLE_NAME); + + SET("`queue_name`=#{queue.queueName}"); + SET("`queue`=#{queue.queue}"); + + WHERE("`id`=#{queue.id}"); + } + }.toString(); + } + + + + + + + /** + * query queue by id + * + * @param parameter + * @return + */ + public String queryById(Map parameter) { + return new SQL() { + { + SELECT("*"); + + FROM(TABLE_NAME); + + WHERE("`id` = #{queueId}"); + } + }.toString(); + } + + /** + * query all queue list + * @param parameter + * @return + */ + public String queryAllQueue(Map parameter) { + return new SQL() { + { + SELECT("*"); + + FROM(TABLE_NAME); + } + }.toString(); + } + + +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ResourceMapper.java b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ResourceMapper.java new file mode 100644 index 0000000000..9d2ab80f21 --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ResourceMapper.java @@ -0,0 +1,278 @@ +/* + * 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.dao.mapper; + +import cn.escheduler.common.enums.ResourceType; +import cn.escheduler.dao.model.Resource; +import org.apache.ibatis.annotations.*; +import org.apache.ibatis.type.EnumOrdinalTypeHandler; +import org.apache.ibatis.type.JdbcType; + +import java.sql.Timestamp; +import java.util.List; + +/** + * resource mapper + */ +public interface ResourceMapper { + + /** + * insert resource + * + * @param resource + * @return + */ + @InsertProvider(type = ResourceMapperProvider.class, method = "insert") + @SelectKey(statement = "SELECT LAST_INSERT_ID() AS id", keyProperty = "resource.id", resultType = int.class, before = false) + int insert(@Param("resource") Resource resource); + + /** + * query resource by alias + * + * @param alias + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = int.class, jdbcType = JdbcType.INTEGER), + @Result(property = "alias", column = "alias", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "fileName", column = "file_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "desc", column = "desc", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "userId", column = "user_id", javaType = int.class, jdbcType = JdbcType.INTEGER), + @Result(property = "type", column = "type", typeHandler = EnumOrdinalTypeHandler.class, javaType = ResourceType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "createTime", column = "create_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "updateTime", column = "update_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE) + }) + @SelectProvider(type = ResourceMapperProvider.class, method = "queryResource") + Resource queryResource(@Param("alias") String alias); + + /** + * query resource by name and resource type + * @param alias + * @param type + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = int.class, jdbcType = JdbcType.INTEGER), + @Result(property = "alias", column = "alias", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "fileName", column = "file_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "desc", column = "desc", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "userId", column = "user_id", javaType = int.class, jdbcType = JdbcType.INTEGER), + @Result(property = "type", column = "type", typeHandler = EnumOrdinalTypeHandler.class, javaType = ResourceType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "createTime", column = "create_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "updateTime", column = "update_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE) + }) + @SelectProvider(type = ResourceMapperProvider.class, method = "queryResourceByNameAndType") + Resource queryResourceByNameAndType(@Param("alias") String alias,@Param("type") int type); + + /** + * query resource by id + * + * @param id + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = int.class, jdbcType = JdbcType.INTEGER), + @Result(property = "alias", column = "alias", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "fileName", column = "file_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "desc", column = "desc", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "userId", column = "user_id", javaType = int.class, jdbcType = JdbcType.INTEGER), + @Result(property = "type", column = "type", typeHandler = EnumOrdinalTypeHandler.class, javaType = ResourceType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "createTime", column = "create_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "updateTime", column = "update_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE) + }) + @SelectProvider(type = ResourceMapperProvider.class, method = "queryResourceById") + Resource queryResourceById(@Param("id") int id); + + /** + * update resource + * + * @param resource + * @return + */ + @UpdateProvider(type = ResourceMapperProvider.class, method = "update") + int update(@Param("resource") Resource resource); + + /** + * delete resource + * + * @param resourceId + * @return + */ + @DeleteProvider(type = ResourceMapperProvider.class, method = "delete") + int delete(@Param("resourceId") int resourceId); + + /** + * query resource list that the appointed user has permission + * @param userId + * @param type + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = int.class, jdbcType = JdbcType.INTEGER), + @Result(property = "alias", column = "alias", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "fileName", column = "file_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "desc", column = "desc", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "userId", column = "user_id", javaType = int.class, jdbcType = JdbcType.INTEGER), + @Result(property = "type", column = "type", typeHandler = EnumOrdinalTypeHandler.class, javaType = ResourceType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "size", column = "size", javaType = Long.class, jdbcType = JdbcType.BIGINT), + @Result(property = "createTime", column = "create_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "updateTime", column = "update_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE) + }) + @SelectProvider(type = ResourceMapperProvider.class, method = "queryResourceListAuthored") + List queryResourceListAuthored(@Param("userId") int userId, @Param("type") int type); + + /** + * query resource list paging by user id + * @param userId + * @param type + * @param searchVal + * @param offset + * @param pageSize + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = int.class, jdbcType = JdbcType.INTEGER), + @Result(property = "alias", column = "alias", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "fileName", column = "file_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "desc", column = "desc", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "userId", column = "user_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "type", column = "type", typeHandler = EnumOrdinalTypeHandler.class, javaType = ResourceType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "size", column = "size", javaType = Long.class, jdbcType = JdbcType.BIGINT), + @Result(property = "createTime", column = "create_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "updateTime", column = "update_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE) + }) + @SelectProvider(type = ResourceMapperProvider.class, method = "queryResourceAuthoredPaging") + List queryResourceAuthoredPaging(@Param("userId") int userId, @Param("type") int type, + @Param("searchVal") String searchVal, + @Param("offset") int offset, + @Param("pageSize") int pageSize); + + /** + * query all resource list paging + * @param type + * @param searchVal + * @param offset + * @param pageSize + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = int.class, jdbcType = JdbcType.INTEGER), + @Result(property = "alias", column = "alias", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "fileName", column = "file_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "desc", column = "desc", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "userId", column = "user_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "type", column = "type", typeHandler = EnumOrdinalTypeHandler.class, javaType = ResourceType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "size", column = "size", javaType = Long.class, jdbcType = JdbcType.BIGINT), + @Result(property = "createTime", column = "create_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "updateTime", column = "update_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE) + }) + @SelectProvider(type = ResourceMapperProvider.class, method = "queryAllResourceListPaging") + List queryAllResourceListPaging(@Param("type") int type, + @Param("searchVal") String searchVal, + @Param("offset") int offset, + @Param("pageSize") int pageSize); + + /** + * count resource number by user id + * + * @param userId + * @return + */ + @SelectProvider(type = ResourceMapperProvider.class, method = "countResourceNumber") + int countResourceNumber(@Param("userId") int userId); + + /** + * count resource number by user id and type + * + * @param userId + * @param type + * @return + */ + @SelectProvider(type = ResourceMapperProvider.class, method = "countResourceNumberByType") + int countResourceNumberByType(@Param("userId") int userId,@Param("type") int type); + + /** + * count resource number by type + * + * @param type + * @return + */ + @SelectProvider(type = ResourceMapperProvider.class, method = "countAllResourceNumberByType") + int countAllResourceNumberByType(@Param("type") int type); + + /** + * query resource list authorized appointed user + * @param userId + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = int.class, jdbcType = JdbcType.INTEGER), + @Result(property = "alias", column = "alias", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "fileName", column = "file_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "desc", column = "desc", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "userId", column = "user_id", javaType = int.class, jdbcType = JdbcType.INTEGER), + @Result(property = "type", column = "type", typeHandler = EnumOrdinalTypeHandler.class, javaType = ResourceType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "size", column = "size", javaType = Long.class, jdbcType = JdbcType.BIGINT), + @Result(property = "createTime", column = "create_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "updateTime", column = "update_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE) + }) + @SelectProvider(type = ResourceMapperProvider.class, method = "queryAuthorizedResourceList") + List queryAuthorizedResourceList(@Param("userId") int userId); + + /** + * + * query all resource list except user + * @param userId + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = int.class, jdbcType = JdbcType.INTEGER), + @Result(property = "alias", column = "alias", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "fileName", column = "file_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "desc", column = "desc", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "userId", column = "user_id", javaType = int.class, jdbcType = JdbcType.INTEGER), + @Result(property = "type", column = "type", typeHandler = EnumOrdinalTypeHandler.class, javaType = ResourceType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "size", column = "size", javaType = Long.class, jdbcType = JdbcType.BIGINT), + @Result(property = "createTime", column = "create_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "updateTime", column = "update_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE) + }) + @SelectProvider(type = ResourceMapperProvider.class, method = "queryResourceExceptUserId") + List queryResourceExceptUserId(@Param("userId") int userId); + + /** + * query resource list that created by the appointed user + * @param userId + * @param type + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = int.class, jdbcType = JdbcType.INTEGER), + @Result(property = "alias", column = "alias", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "fileName", column = "file_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "desc", column = "desc", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "userId", column = "user_id", javaType = int.class, jdbcType = JdbcType.INTEGER), + @Result(property = "type", column = "type", typeHandler = EnumOrdinalTypeHandler.class, javaType = ResourceType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "size", column = "size", javaType = Long.class, jdbcType = JdbcType.BIGINT), + @Result(property = "createTime", column = "create_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "updateTime", column = "update_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE) + }) + @SelectProvider(type = ResourceMapperProvider.class, method = "queryResourceCreatedByUser") + List queryResourceCreatedByUser(@Param("userId") int userId, @Param("type") int type); + + + /** + * query tenant code by resource name + * + * @param resName + * @return + */ + @SelectProvider(type = ResourceMapperProvider.class, method = "queryTenantCodeByResourceName") + String queryTenantCodeByResourceName(@Param("resName") String resName); + + +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ResourceMapperProvider.java b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ResourceMapperProvider.java new file mode 100644 index 0000000000..4122c7722c --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ResourceMapperProvider.java @@ -0,0 +1,297 @@ +/* + * 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.dao.mapper; + +import cn.escheduler.common.enums.ResourceType; +import cn.escheduler.common.utils.EnumFieldUtil; +import org.apache.commons.lang3.StringUtils; +import org.apache.ibatis.jdbc.SQL; + +import java.util.Map; + +/** + * resource mapper provider + */ +public class ResourceMapperProvider { + + private final String TABLE_NAME = "t_escheduler_resources"; + + public static final String USER_TABLE_NAME = "t_escheduler_user"; + public static final String USER_RESOURCE_RELATION_TABLE_NAME = "t_escheduler_relation_resources_user"; + public static final String PROJECT_TABLE_NAME = "t_escheduler_project"; + public static final String TENANT_TABLE_NAME="t_escheduler_tenant"; + + /** + * insert resource + * @param parameter + * @return + */ + public String insert(Map parameter) { + return new SQL() { + { + INSERT_INTO(TABLE_NAME); + + VALUES("`alias`", "#{resource.alias}"); + VALUES("`file_name`", "#{resource.fileName}"); + VALUES("`desc`", "#{resource.desc}"); + VALUES("`user_id`", "#{resource.userId}"); + VALUES("`create_time`", "#{resource.createTime}"); + VALUES("`update_time`", "#{resource.updateTime}"); + VALUES("`type`", EnumFieldUtil.genFieldStr("resource.type", ResourceType.class)); + VALUES("`size`", "#{resource.size}"); + } + }.toString(); + } + + /** + * query resource by name + * + * @param parameter + * @return + */ + public String queryResource(Map parameter) { + return new SQL() { + { + SELECT("*"); + FROM(TABLE_NAME); + WHERE("alias = #{alias}"); + } + }.toString(); + } + + /** + * query resource by name and resource type + * @param parameter + * @return + */ + public String queryResourceByNameAndType(Map parameter) { + return new SQL() { + { + SELECT("*"); + FROM(TABLE_NAME); + WHERE("alias = #{alias}"); + WHERE("type = #{type}"); + } + }.toString(); + } + + /** + * query resource by id + * + * @param parameter + * @return + */ + public String queryResourceById(Map parameter) { + return new SQL() { + { + SELECT("*"); + FROM(TABLE_NAME); + WHERE("id = #{id}"); + } + }.toString(); + } + + /** + * update resource + * + * @param parameter + * @return + */ + public String update(Map parameter) { + return new SQL() {{ + UPDATE(TABLE_NAME); + + SET("`alias` = #{resource.alias}"); + SET("`desc` = #{resource.desc}"); + SET("`update_time` = #{resource.updateTime}"); + WHERE("`id` = #{resource.id}"); + }}.toString(); + } + + /** + * delete resource by id + * + * @param parameter + * @return + */ + public String delete(Map parameter) { + return new SQL() { + { + DELETE_FROM(TABLE_NAME); + + WHERE("`id` = #{resourceId}"); + } + }.toString(); + } + + /** + * query resource list by user id + * + * @param parameter + * @return + */ + public String queryResourceListAuthored(Map parameter) { + return new SQL() {{ + + SELECT("*"); + + FROM(TABLE_NAME); + WHERE("type=#{type}"); + WHERE("id in (select resources_id from "+USER_RESOURCE_RELATION_TABLE_NAME+" where user_id=#{userId} union select id as resources_id from "+TABLE_NAME+" where user_id=#{userId})"); + + }}.toString(); + } + + /** + * query resource list paging by user id + * @param parameter + * @return + */ + public String queryResourceAuthoredPaging(Map parameter) { + + return new SQL() {{ + SELECT("*"); + + FROM(TABLE_NAME ); + WHERE("type=#{type}"); + WHERE("id in (select resources_id from "+USER_RESOURCE_RELATION_TABLE_NAME+" where user_id=#{userId} union select id as resources_id from "+TABLE_NAME+" where user_id=#{userId})"); + Object searchVal = parameter.get("searchVal"); + if(searchVal != null && StringUtils.isNotEmpty(searchVal.toString())){ + WHERE( " alias like concat('%', #{searchVal}, '%') "); + } + ORDER_BY("update_time desc limit #{offset},#{pageSize} "); + }}.toString(); + } + + /** + * + * query all resource list paging + * @param parameter + * @return + */ + public String queryAllResourceListPaging(Map parameter) { + + return new SQL() {{ + SELECT("*"); + + FROM(TABLE_NAME); + WHERE("type=#{type}"); + Object searchVal = parameter.get("searchVal"); + if(searchVal != null && StringUtils.isNotEmpty(searchVal.toString())){ + WHERE( " alias like concat('%', #{searchVal}, '%') "); + } + ORDER_BY("update_time desc limit #{offset},#{pageSize} "); + }}.toString(); + } + + /** + * count resource number by user id + * @param parameter + * @return + */ + public String countResourceNumber(Map parameter) { + return new SQL() {{ + SELECT("count(0)"); + + FROM("(select resources_id from t_escheduler_relation_resources_user where user_id=#{userId} union select id as resources_id from t_escheduler_resources where user_id=#{userId}) t"); + + }}.toString(); + } + + /** + * count resource number by user id and type + * @param parameter + * @return + */ + public String countResourceNumberByType(Map parameter) { + return new SQL() {{ + SELECT("count(0)"); + FROM(TABLE_NAME ); + WHERE("type=#{type}"); + WHERE("id in (select resources_id from " + USER_RESOURCE_RELATION_TABLE_NAME + " where user_id=#{userId} union select id as resources_id from " + TABLE_NAME + " where user_id=#{userId})"); + + }}.toString(); + } + + /** + * count resource number by type + * @param parameter + * @return + */ + public String countAllResourceNumberByType(Map parameter) { + return new SQL() {{ + SELECT("count(0)"); + FROM(TABLE_NAME); + WHERE("type=#{type}"); + }}.toString(); + } + + + + /** + * query resource list authorized appointed user + * @param parameter + * @return + */ + public String queryAuthorizedResourceList(Map parameter) { + return new SQL() {{ + SELECT("r.*"); + FROM(TABLE_NAME + " r,t_escheduler_relation_resources_user rel"); + WHERE(" r.id = rel.resources_id AND rel.user_id = #{userId}"); + }}.toString(); + } + + + /** + * query all resource list except user + * @param parameter + * @return + */ + public String queryResourceExceptUserId(Map parameter) { + return new SQL() {{ + SELECT("*"); + FROM(TABLE_NAME); + WHERE("user_id <> #{userId}"); + }}.toString(); + } + + /** + * query tenant code by resource name + * @param parameter + * @return + */ + public String queryTenantCodeByResourceName(Map parameter) { + return new SQL() {{ + SELECT("tenant_code"); + FROM(TENANT_TABLE_NAME + " t," + USER_TABLE_NAME + " u," + TABLE_NAME + " res"); + WHERE(" t.id = u.tenant_id and u.id = res.user_id and res.type=0 and res.alias= #{resName}"); + }}.toString(); + } + + /** + * query resource list that created by the appointed user + * @param parameter + * @return + */ + public String queryResourceCreatedByUser(Map parameter) { + return new SQL() {{ + SELECT("*"); + FROM(TABLE_NAME); + WHERE("type = #{type} and user_id = #{userId}"); + }}.toString(); + } +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ResourcesUserMapper.java b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ResourcesUserMapper.java new file mode 100644 index 0000000000..6f26f1aa57 --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ResourcesUserMapper.java @@ -0,0 +1,54 @@ +/* + * 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.dao.mapper; + +import cn.escheduler.dao.model.ResourcesUser; +import org.apache.ibatis.annotations.DeleteProvider; +import org.apache.ibatis.annotations.InsertProvider; +import org.apache.ibatis.annotations.Param; + +/** + * resource user mapper + */ +public interface ResourcesUserMapper { + /** + * insert resource user + * + * @param resourcesUser + * @return + */ + @InsertProvider(type = ResourcesUserMapperProvider.class, method = "insert") + int insert(@Param("resourcesUser") ResourcesUser resourcesUser); + + + /** + * delete resource relation by user id + * @param userId + * @return + */ + @DeleteProvider(type = ResourcesUserMapperProvider.class, method = "deleteByUserId") + int deleteByUserId(@Param("userId") int userId); + + /** + * delete resource relation by resource id + * @param resourceId + * @return + */ + @DeleteProvider(type = ResourcesUserMapperProvider.class, method = "deleteByResourceId") + int deleteByResourceId(@Param("resourceId") int resourceId); + +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ResourcesUserMapperProvider.java b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ResourcesUserMapperProvider.java new file mode 100644 index 0000000000..67d2eb47f3 --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ResourcesUserMapperProvider.java @@ -0,0 +1,77 @@ +/* + * 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.dao.mapper; + +import org.apache.ibatis.jdbc.SQL; + +import java.util.Map; + +/** + * resource user mapper provider + */ +public class ResourcesUserMapperProvider { + + private static final String TABLE_NAME = "t_escheduler_relation_resources_user"; + + + /** + * insert resource user + * + * @param parameter + * @return + */ + public String insert(Map parameter) { + return new SQL() {{ + INSERT_INTO(TABLE_NAME); + + VALUES("`resources_id`", "#{resourcesUser.resourcesId}"); + VALUES("`user_id`", "#{resourcesUser.userId}"); + VALUES("`perm`", "#{resourcesUser.perm}"); + VALUES("`create_time`", "#{resourcesUser.createTime}"); + VALUES("`update_time`", "#{resourcesUser.updateTime}"); + }}.toString(); + } + + + /** + * delete resource relation by user id + * + * @param parameter + * @return + */ + public String deleteByUserId(Map parameter) { + return new SQL() {{ + DELETE_FROM(TABLE_NAME); + + WHERE("`user_id` = #{userId}"); + }}.toString(); + } + + /** + * delete resource relation by resource id + * + * @param parameter + * @return + */ + public String deleteByResourceId(Map parameter) { + return new SQL() {{ + DELETE_FROM(TABLE_NAME); + + WHERE("`resources_id` = #{resourceId}"); + }}.toString(); + } +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ScheduleMapper.java b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ScheduleMapper.java new file mode 100644 index 0000000000..2e6f3fc40b --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ScheduleMapper.java @@ -0,0 +1,174 @@ +/* + * 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.dao.mapper; + + +import cn.escheduler.common.enums.FailureStrategy; +import cn.escheduler.common.enums.Priority; +import cn.escheduler.common.enums.ReleaseState; +import cn.escheduler.common.enums.WarningType; +import cn.escheduler.dao.model.Schedule; +import org.apache.ibatis.annotations.*; +import org.apache.ibatis.type.EnumOrdinalTypeHandler; +import org.apache.ibatis.type.JdbcType; + +import java.util.Date; +import java.util.List; + +/** + * scheduler mapper + */ +public interface ScheduleMapper { + + /** + * insert scheduler + * @param schedule + * @return + */ + @InsertProvider(type = ScheduleMapperProvider.class, method = "insert") + int insert(@Param("schedule") Schedule schedule); + + /** + * update schedule info + * @param schedule + * @return + */ + @UpdateProvider(type = ScheduleMapperProvider.class, method = "update") + int update(@Param("schedule") Schedule schedule); + + /** + * query schedule list by process define id + * + * @param processDefinitionId + * @param searchVal + * @param offset + * @param pageSize + * @return + */ + @Results(value = { + @Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "processDefinitionId", column = "process_definition_id",javaType = int.class, jdbcType = JdbcType.INTEGER), + @Result(property = "processDefinitionName", column = "process_definition_name", javaType =String.class, jdbcType = JdbcType.INTEGER), + @Result(property = "projectName", column = "project_name", javaType = String.class, jdbcType = JdbcType.INTEGER), + @Result(property = "startTime", column = "start_time", javaType = Date.class, jdbcType = JdbcType.TIMESTAMP), + @Result(property = "endTime", column = "end_time", javaType = Date.class, jdbcType = JdbcType.TIMESTAMP), + @Result(property = "crontab", column = "crontab", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "failureStrategy", column = "failure_strategy", typeHandler = EnumOrdinalTypeHandler.class, javaType = FailureStrategy.class, jdbcType = JdbcType.TINYINT), + @Result(property = "warningType", column = "warning_type", typeHandler = EnumOrdinalTypeHandler.class, javaType = WarningType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "createTime", column = "create_time", javaType = Date.class, jdbcType = JdbcType.TIMESTAMP), + @Result(property = "updateTime", column = "update_time", javaType = Date.class, jdbcType = JdbcType.TIMESTAMP), + @Result(property = "userId", column = "user_id", javaType = int.class, jdbcType = JdbcType.INTEGER), + @Result(property = "userName", column = "user_name", javaType = String.class, jdbcType = JdbcType.INTEGER), + @Result(property = "releaseState", column = "release_state", typeHandler = EnumOrdinalTypeHandler.class, javaType = ReleaseState.class, jdbcType = JdbcType.TINYINT), + @Result(property = "warningGroupId", column = "warning_group_id", javaType = int.class, jdbcType = JdbcType.INTEGER), + @Result(property = "processInstancePriority", column = "process_instance_priority", javaType = Priority.class, typeHandler = EnumOrdinalTypeHandler.class, jdbcType = JdbcType.TINYINT) + }) + @SelectProvider(type = ScheduleMapperProvider.class, method = "queryByProcessDefineIdPaging") + List queryByProcessDefineIdPaging(@Param("processDefinitionId") int processDefinitionId, + @Param("searchVal") String searchVal, + @Param("offset") int offset, + @Param("pageSize") int pageSize); + + /** + * count schedule number by process definition id and search value + * @param processDefinitionId + * @param searchVal + * @return + */ + @SelectProvider(type = ScheduleMapperProvider.class, method = "countByProcessDefineId") + Integer countByProcessDefineId(@Param("processDefinitionId") Integer processDefinitionId, + @Param("searchVal") String searchVal + ); + + /** + * query schedule list by project id + * + * @param projectName + * @return + */ + @Results(value = { + @Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "projectName", column = "project_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "processDefinitionName", column = "process_definition_name", id = true, javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "desc", column = "desc", id = true, javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "processDefinitionId", column = "process_definition_id", id = true, javaType = int.class, jdbcType = JdbcType.INTEGER), + @Result(property = "startTime", column = "start_time", javaType = Date.class, jdbcType = JdbcType.TIMESTAMP), + @Result(property = "endTime", column = "end_time", javaType = Date.class, jdbcType = JdbcType.TIMESTAMP), + @Result(property = "crontab", column = "crontab", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "failureStrategy", column = "failure_strategy", typeHandler = EnumOrdinalTypeHandler.class, javaType = FailureStrategy.class, jdbcType = JdbcType.TINYINT), + @Result(property = "warningType", column = "warning_type", typeHandler = EnumOrdinalTypeHandler.class, javaType = WarningType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "createTime", column = "create_time", javaType = Date.class, jdbcType = JdbcType.TIMESTAMP), + @Result(property = "updateTime", column = "update_time", javaType = Date.class, jdbcType = JdbcType.TIMESTAMP), + @Result(property = "userId", column = "user_id", javaType = int.class, jdbcType = JdbcType.INTEGER), + @Result(property = "userName", column = "user_name", javaType = String.class, jdbcType = JdbcType.INTEGER), + @Result(property = "releaseState", column = "release_state", typeHandler = EnumOrdinalTypeHandler.class, javaType = ReleaseState.class, jdbcType = JdbcType.TINYINT), + @Result(property = "warningGroupId", column = "warning_group_id", javaType = int.class, jdbcType = JdbcType.INTEGER), + @Result(property = "processInstancePriority", column = "process_instance_priority", javaType = Priority.class, typeHandler = EnumOrdinalTypeHandler.class, jdbcType = JdbcType.TINYINT) + }) + @SelectProvider(type = ScheduleMapperProvider.class, method = "querySchedulerListByProjectName") + List querySchedulerListByProjectName(@Param("projectName") String projectName); + + + /** + * query schedule by id + * @param id + * @return + */ + @Results(value = { + @Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "processDefinitionId", column = "process_definition_id", id = true, javaType = int.class, jdbcType = JdbcType.INTEGER), + @Result(property = "startTime", column = "start_time", javaType = Date.class, jdbcType = JdbcType.TIMESTAMP), + @Result(property = "endTime", column = "end_time", javaType = Date.class, jdbcType = JdbcType.TIMESTAMP), + @Result(property = "crontab", column = "crontab", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "failureStrategy", column = "failure_strategy", typeHandler = EnumOrdinalTypeHandler.class, javaType = FailureStrategy.class, jdbcType = JdbcType.TINYINT), + @Result(property = "warningType", column = "warning_type", typeHandler = EnumOrdinalTypeHandler.class, javaType = WarningType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "createTime", column = "create_time", javaType = Date.class, jdbcType = JdbcType.TIMESTAMP), + @Result(property = "updateTime", column = "update_time", javaType = Date.class, jdbcType = JdbcType.TIMESTAMP), + @Result(property = "userId", column = "user_id", javaType = int.class, jdbcType = JdbcType.INTEGER), + @Result(property = "releaseState", column = "release_state", typeHandler = EnumOrdinalTypeHandler.class, javaType = ReleaseState.class, jdbcType = JdbcType.TINYINT), + @Result(property = "warningGroupId", column = "warning_group_id", javaType = int.class, jdbcType = JdbcType.INTEGER), + @Result(property = "processInstancePriority", column = "process_instance_priority", javaType = Priority.class, typeHandler = EnumOrdinalTypeHandler.class, jdbcType = JdbcType.TINYINT) + }) + @SelectProvider(type = ScheduleMapperProvider.class, method = "queryById") + Schedule queryById(@Param("id") int id); + + /** + * query schedule list by definition array + * @param processDefineIds + * @return + */ + @Results(value = { + @Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "processDefinitionId", column = "process_definition_id", id = true, javaType = int.class, jdbcType = JdbcType.INTEGER), + @Result(property = "startTime", column = "start_time", javaType = Date.class, jdbcType = JdbcType.TIMESTAMP), + @Result(property = "endTime", column = "end_time", javaType = Date.class, jdbcType = JdbcType.TIMESTAMP), + @Result(property = "crontab", column = "crontab", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "failureStrategy", column = "failure_strategy", typeHandler = EnumOrdinalTypeHandler.class, javaType = FailureStrategy.class, jdbcType = JdbcType.TINYINT), + @Result(property = "warningType", column = "warning_type", typeHandler = EnumOrdinalTypeHandler.class, javaType = WarningType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "createTime", column = "create_time", javaType = Date.class, jdbcType = JdbcType.TIMESTAMP), + @Result(property = "updateTime", column = "update_time", javaType = Date.class, jdbcType = JdbcType.TIMESTAMP), + @Result(property = "userId", column = "user_id", javaType = int.class, jdbcType = JdbcType.INTEGER), + @Result(property = "releaseState", column = "release_state", typeHandler = EnumOrdinalTypeHandler.class, javaType = ReleaseState.class, jdbcType = JdbcType.TINYINT), + @Result(property = "warningGroupId", column = "warning_group_id", javaType = int.class, jdbcType = JdbcType.INTEGER), + @Result(property = "processInstancePriority", column = "process_instance_priority", javaType = Priority.class, typeHandler = EnumOrdinalTypeHandler.class, jdbcType = JdbcType.TINYINT) + }) + @SelectProvider(type = ScheduleMapperProvider.class, method = "selectAllByProcessDefineArray") + List selectAllByProcessDefineArray(@Param("processDefineIds") int[] processDefineIds); + + + +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ScheduleMapperProvider.java b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ScheduleMapperProvider.java new file mode 100644 index 0000000000..af82318da2 --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/ScheduleMapperProvider.java @@ -0,0 +1,181 @@ +/* + * 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.dao.mapper; + +import cn.escheduler.common.enums.FailureStrategy; +import cn.escheduler.common.enums.Priority; +import cn.escheduler.common.enums.ReleaseState; +import cn.escheduler.common.enums.WarningType; +import cn.escheduler.common.utils.EnumFieldUtil; +import org.apache.ibatis.jdbc.SQL; + +import java.util.Map; + +/** + * scheduler mapper provider + */ +public class ScheduleMapperProvider { + + public static final String DB_NAME = "t_escheduler_schedules"; + public static final String DEFINE_TABLE_NAME = "t_escheduler_process_definition"; + + public String insert(Map parameter) { + return new SQL() {{ + INSERT_INTO(DB_NAME); + + VALUES("`process_definition_id`", "#{schedule.processDefinitionId}"); + VALUES("`start_time`", "#{schedule.startTime}"); + VALUES("`end_time`", "#{schedule.endTime}"); + VALUES("`crontab`", "#{schedule.crontab}"); + VALUES("`failure_strategy`", EnumFieldUtil.genFieldStr("schedule.failureStrategy", FailureStrategy.class)); + VALUES("`warning_type`", EnumFieldUtil.genFieldStr("schedule.warningType", WarningType.class)); + VALUES("`create_time`", "#{schedule.createTime}"); + VALUES("`update_time`", "#{schedule.updateTime}"); + VALUES("`user_id`", "#{schedule.userId}"); + VALUES("`release_state`", EnumFieldUtil.genFieldStr("schedule.releaseState", ReleaseState.class)); + VALUES("`warning_group_id`", "#{schedule.warningGroupId}"); + VALUES("`process_instance_priority`", EnumFieldUtil.genFieldStr("schedule.processInstancePriority", Priority.class)); + }}.toString(); + } + + public String update(Map parameter) { + return new SQL() { + { + UPDATE(DB_NAME); + + SET("`start_time`=#{schedule.startTime}"); + SET("`end_time`=#{schedule.endTime}"); + SET("`crontab`=#{schedule.crontab}"); + SET("`failure_strategy`=" + EnumFieldUtil.genFieldStr("schedule.failureStrategy", FailureStrategy.class)); + SET("`warning_type`=" + EnumFieldUtil.genFieldStr("schedule.warningType", WarningType.class)); + SET("`create_time`=#{schedule.createTime}"); + SET("`update_time`=#{schedule.updateTime}"); + SET("`user_id`=#{schedule.userId}"); + SET("`release_state`=" + EnumFieldUtil.genFieldStr("schedule.releaseState", ReleaseState.class)); + SET("`warning_group_id`=#{schedule.warningGroupId}"); + SET("`process_instance_priority`="+ EnumFieldUtil.genFieldStr("schedule.processInstancePriority", Priority.class)); + + WHERE("`id` = #{schedule.id}"); + } + }.toString(); + } + + /** + * query schedule by id + * @param parameter + * @return + */ + public String queryById(Map parameter) { + return new SQL() {{ + SELECT("*"); + FROM(DB_NAME); + WHERE("`id` = #{id}"); + }}.toString(); + } + + /** + * query schedule list by process define id + * @param parameter + * @return + */ + public String queryByProcessDefineIdPaging(Map parameter) { + return new SQL() {{ + SELECT("p_f.name as process_definition_name"); + SELECT("p.name as project_name"); + SELECT("u.user_name"); + SELECT("s.*"); + + FROM(DB_NAME + " as s"); + + JOIN(DEFINE_TABLE_NAME + " as p_f on s.process_definition_id = p_f.id"); + JOIN("t_escheduler_project as p on p_f.project_id = p.id"); + JOIN("t_escheduler_user as u on s.user_id = u.id"); + if(parameter.get("processDefinitionId") != null && (int)parameter.get("processDefinitionId") != 0) { + WHERE("s.process_definition_id = #{processDefinitionId}"); + } + ORDER_BY("s.update_time desc limit #{offset},#{pageSize}"); + }}.toString(); + } + + /** + * count schedule number by process definition id and search value + * @param parameter + * @return + */ + public String countByProcessDefineId(Map parameter) { + return new SQL() {{ + SELECT("count(0)"); + + FROM(DB_NAME + " as s"); + + JOIN(DEFINE_TABLE_NAME + " as p_f on s.process_definition_id = p_f.id"); + JOIN("t_escheduler_project as p on p_f.project_id = p.id"); + JOIN("t_escheduler_user as u on s.user_id = u.id"); + if(parameter.get("processDefinitionId") != null && (int)parameter.get("processDefinitionId") != 0) { + WHERE("s.process_definition_id = #{processDefinitionId}"); + } + }}.toString(); + } + + /** + * query schedule list by project id + * @param parameter + * @return + */ + public String querySchedulerListByProjectName(Map parameter) { + return new SQL() {{ + SELECT("p_f.name as process_definition_name"); + SELECT("p_f.desc as `desc`"); + SELECT("p.name as project_name"); + SELECT("u.user_name"); + SELECT("s.*"); + + FROM(DB_NAME + " as s"); + + JOIN( DEFINE_TABLE_NAME + " as p_f on s.process_definition_id = p_f.id"); + JOIN("t_escheduler_project as p on p_f.project_id = p.id"); + JOIN("t_escheduler_user as u on s.user_id = u.id"); + + WHERE("p.name = #{projectName}"); + }}.toString(); + } + + /** + * query schedule list by definition array + * @param parameter + * @return + */ + public String selectAllByProcessDefineArray(Map parameter) { + + StringBuffer strIds = new StringBuffer(); + int[] idsArray = (int[]) parameter.get("processDefineIds"); + for(int i=0;i parameter) { + return new SQL() { + { + INSERT_INTO(TABLE_NAME); + VALUES("`id`", "#{session.id}"); + VALUES("`user_id`", "#{session.userId}"); + VALUES("`ip`", "#{session.ip}"); + VALUES("`last_login_time`", "#{session.lastLoginTime}"); + + } + }.toString(); + } + + /** + * delete session + * + * @param parameter + * @return + */ + public String delete(Map parameter) { + return new SQL() { + { + DELETE_FROM(TABLE_NAME); + + WHERE("`id`=#{sessionId}"); + } + }.toString(); + } + + /** + * update session + * @param parameter + * @return + */ + public String update(Map parameter) { + return new SQL() { + { + UPDATE(TABLE_NAME); + + SET("`last_login_time`=#{loginTime}"); + + WHERE("`id` = #{sessionId}"); + } + }.toString(); + } + + + + + + + /** + * query by session id + * + * @param parameter + * @return + */ + public String queryById(Map parameter) { + return new SQL() { + { + SELECT("*"); + + FROM(TABLE_NAME); + + WHERE("`id` = #{sessionId}"); + } + }.toString(); + } + + /** + * query by session id and ip + * @param parameter + * @return + */ + public String queryByIdAndIp(Map parameter) { + return new SQL() {{ + SELECT("*"); + + FROM(TABLE_NAME); + + WHERE("`id` = #{sessionId}"); + WHERE("`ip` = #{ip}"); + }}.toString(); + } + + /** + * query by user id and ip + * @param parameter + * @return + */ + public String queryByUserIdAndIp(Map parameter) { + return new SQL() {{ + SELECT("*"); + + FROM(TABLE_NAME); + + WHERE("`user_id` = #{userId}"); + WHERE("`ip` = #{ip}"); + }}.toString(); + } +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/TaskInstanceMapper.java b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/TaskInstanceMapper.java new file mode 100644 index 0000000000..e7838e7730 --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/TaskInstanceMapper.java @@ -0,0 +1,307 @@ +/* + * 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.dao.mapper; + +import cn.escheduler.common.enums.ExecutionStatus; +import cn.escheduler.common.enums.Flag; +import cn.escheduler.common.enums.Priority; +import cn.escheduler.common.enums.UserType; +import cn.escheduler.dao.model.ExecuteStatusCount; +import cn.escheduler.dao.model.TaskInstance; +import org.apache.ibatis.annotations.*; +import org.apache.ibatis.type.EnumOrdinalTypeHandler; +import org.apache.ibatis.type.JdbcType; + +import java.sql.Timestamp; +import java.util.Date; +import java.util.List; + +/** + * task intance mapper + */ +public interface TaskInstanceMapper { + + /** + * insert task instance + * @param taskInstance + * @return + */ + @InsertProvider(type = TaskInstanceMapperProvider.class, method = "insert") + @Options(useGeneratedKeys = true,keyProperty = "taskInstance.id") + @SelectKey(statement = "SELECT LAST_INSERT_ID()", keyProperty = "taskInstance.id", before = false, resultType = int.class) + int insert(@Param("taskInstance") TaskInstance taskInstance); + + /** + * delete task instance + * @param taskInstanceId + * @return + */ + @DeleteProvider(type = TaskInstanceMapperProvider.class, method = "delete") + int delete(@Param("taskInstanceId") int taskInstanceId); + + /** + * update task instance + * + * @param taskInstance + * @return + */ + @UpdateProvider(type = TaskInstanceMapperProvider.class, method = "update") + int update(@Param("taskInstance") TaskInstance taskInstance); + + /** + * query task by id + * @param taskInstanceId + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "name", column = "name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "taskType", column = "task_type",javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "processDefinitionId", column = "process_definition_id",javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "processInstanceId", column = "process_instance_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "taskJson", column = "task_json", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "state", column = "state", typeHandler = EnumOrdinalTypeHandler.class, javaType = ExecutionStatus.class, jdbcType = JdbcType.TINYINT), + @Result(property = "submitTime", column = "submit_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "startTime", column = "start_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "endTime", column = "end_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "host", column = "host", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "executePath", column = "execute_path", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "logPath", column = "log_path", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "alertFlag", column = "alert_flag", typeHandler = EnumOrdinalTypeHandler.class, javaType = Flag.class, jdbcType = JdbcType.TINYINT), + @Result(property = "retryTimes", column = "retry_times", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "pid", column = "pid", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "maxRetryTimes", column = "max_retry_times", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "retryInterval", column = "retry_interval", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "appLink", column = "app_link", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "duration", column = "duration", javaType = Long.class, jdbcType = JdbcType.BIGINT), + @Result(property = "flag", column = "flag", typeHandler = EnumOrdinalTypeHandler.class, javaType = Flag.class, jdbcType = JdbcType.TINYINT), + @Result(property = "taskInstancePriority", column = "task_instance_priority", javaType = Priority.class, typeHandler = EnumOrdinalTypeHandler.class, jdbcType = JdbcType.TINYINT) + }) + @SelectProvider(type = TaskInstanceMapperProvider.class, method = "queryById") + TaskInstance queryById(@Param("taskInstanceId") int taskInstanceId); + + /** + * query task id list by process instance id and state + * @param processInstanceId + * @param state + * @return + */ + @Results(value = {@Result(property = "id", column = "id", javaType = Integer.class, jdbcType = JdbcType.INTEGER)}) + @SelectProvider(type = TaskInstanceMapperProvider.class, method = "queryTaskByProcessIdAndState") + List queryTaskByProcessIdAndState(@Param("processInstanceId") Integer processInstanceId, + @Param("state") Integer state); + + /** + * query valid task instance list by process id + * @param processInstanceId + * @param flag + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "name", column = "name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "taskType", column = "task_type",javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "processDefinitionId", column = "process_definition_id",javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "processInstanceId", column = "process_instance_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "taskJson", column = "task_json", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "state", column = "state", typeHandler = EnumOrdinalTypeHandler.class, javaType = ExecutionStatus.class, jdbcType = JdbcType.TINYINT), + @Result(property = "submitTime", column = "submit_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "startTime", column = "start_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "endTime", column = "end_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "host", column = "host", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "executePath", column = "execute_path", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "logPath", column = "log_path", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "alertFlag", column = "alert_flag", typeHandler = EnumOrdinalTypeHandler.class, javaType = Flag.class, jdbcType = JdbcType.TINYINT), + @Result(property = "retryTimes", column = "retry_times", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "maxRetryTimes", column = "max_retry_times", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "retryInterval", column = "retry_interval", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "pid", column = "pid", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "appLink", column = "app_link", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "duration", column = "duration", javaType = Long.class, jdbcType = JdbcType.BIGINT), + @Result(property = "flag", column = "flag", typeHandler = EnumOrdinalTypeHandler.class, javaType = Flag.class, jdbcType = JdbcType.TINYINT), + @Result(property = "taskInstancePriority", column = "task_instance_priority", javaType = Priority.class, typeHandler = EnumOrdinalTypeHandler.class, jdbcType = JdbcType.TINYINT) + }) + @SelectProvider(type = TaskInstanceMapperProvider.class, method = "findValidTaskListByProcessId") + List findValidTaskListByProcessId(@Param("processInstanceId") Integer processInstanceId, + @Param("flag") Flag flag); + + /** + * query task list by host and state + * @param host + * @param stateArray + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "name", column = "name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "taskType", column = "task_type",javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "processDefinitionId", column = "process_definition_id",javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "processInstanceId", column = "process_instance_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "taskJson", column = "task_json", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "state", column = "state", typeHandler = EnumOrdinalTypeHandler.class, javaType = ExecutionStatus.class, jdbcType = JdbcType.TINYINT), + @Result(property = "submitTime", column = "submit_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "startTime", column = "start_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "endTime", column = "end_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "host", column = "host", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "executePath", column = "execute_path", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "logPath", column = "log_path", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "alertFlag", column = "alert_flag", typeHandler = EnumOrdinalTypeHandler.class, javaType = Flag.class, jdbcType = JdbcType.TINYINT), + @Result(property = "retryTimes", column = "retry_times", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "maxRetryTimes", column = "max_retry_times", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "retryInterval", column = "retry_interval", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "pid", column = "pid", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "appLink", column = "app_link", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "duration", column = "duration", javaType = Long.class, jdbcType = JdbcType.BIGINT), + @Result(property = "flag", column = "flag", typeHandler = EnumOrdinalTypeHandler.class, javaType = Flag.class, jdbcType = JdbcType.TINYINT), + @Result(property = "taskInstancePriority", column = "task_instance_priority", javaType = Priority.class, typeHandler = EnumOrdinalTypeHandler.class, jdbcType = JdbcType.TINYINT) + }) + @SelectProvider(type = TaskInstanceMapperProvider.class, method = "queryByHostAndStatus") + List queryByHostAndStatus(@Param("host") String host,@Param("states") int[] stateArray); + + /** + * set task state to need failover when worker down + * @param host + * @param stateArray + * @return + */ + @UpdateProvider(type = TaskInstanceMapperProvider.class, method = "setFailoverByHostAndStateArray") + int setFailoverByHostAndStateArray(@Param("host") String host, @Param("states")int[] stateArray); + + /** + * count task number group by state and user + * @param userId + * @param userType + * @param startTime + * @param endTime + * @param projectId + * @return + */ + @Results(value = { + @Result(property = "state", column = "state", typeHandler = EnumOrdinalTypeHandler.class, javaType = ExecutionStatus.class, jdbcType = JdbcType.TINYINT), + @Result(property = "count", column = "count", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + }) + @SelectProvider(type = TaskInstanceMapperProvider.class, method = "countTaskInstanceStateByUser") + List countTaskInstanceStateByUser(@Param("userId") int userId, + @Param("userType") UserType userType, + @Param("startTime") Date startTime, + @Param("endTime") Date endTime, + @Param("projectId") int projectId); + + /** + * count task number by search fields + * @param projectId + * @param processInstanceId + * @param taskName + * @param statusArray + * @param startTime + * @param endTime + * @param searchVal + * @return + */ + @SelectProvider(type = TaskInstanceMapperProvider.class, method = "countTaskInstance") + Integer countTaskInstance(@Param("projectId") int projectId, + @Param("processInstanceId") Integer processInstanceId, + @Param("taskName") String taskName, + @Param("states") String statusArray, + @Param("host") String host, + @Param("startTime") Date startTime, + @Param("endTime") Date endTime, + @Param("searchVal") String searchVal + ); + + /** + * query task list paging by search fields + * @param projectId + * @param processInstanceId + * @param searchVal + * @param taskName + * @param statusArray + * @param startTime + * @param endTime + * @param offset + * @param pageSize + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "name", column = "name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "taskType", column = "task_type",javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "processDefinitionId", column = "process_definition_id",javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "processInstanceId", column = "process_instance_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "processInstanceName", column = "process_instance_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "taskJson", column = "task_json", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "state", column = "state", typeHandler = EnumOrdinalTypeHandler.class, javaType = ExecutionStatus.class, jdbcType = JdbcType.TINYINT), + @Result(property = "submitTime", column = "submit_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "startTime", column = "start_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "endTime", column = "end_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "host", column = "host", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "executePath", column = "execute_path", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "logPath", column = "log_path", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "alertFlag", column = "alert_flag", typeHandler = EnumOrdinalTypeHandler.class, javaType = Flag.class, jdbcType = JdbcType.TINYINT), + @Result(property = "retryTimes", column = "retry_times", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "maxRetryTimes", column = "max_retry_times", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "retryInterval", column = "retry_interval", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "pid", column = "pid", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "appLink", column = "app_link", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "duration", column = "duration", javaType = Long.class, jdbcType = JdbcType.BIGINT), + @Result(property = "flag", column = "flag", typeHandler = EnumOrdinalTypeHandler.class, javaType = Flag.class, jdbcType = JdbcType.TINYINT), + @Result(property = "taskInstancePriority", column = "task_instance_priority", javaType = Priority.class, typeHandler = EnumOrdinalTypeHandler.class, jdbcType = JdbcType.TINYINT) + }) + @SelectProvider(type = TaskInstanceMapperProvider.class, method = "queryTaskInstanceListPaging") + List queryTaskInstanceListPaging( + @Param("projectId") int projectId, + @Param("processInstanceId") Integer processInstanceId, + @Param("searchVal") String searchVal, + @Param("taskName") String taskName, + @Param("states") String statusArray, + @Param("host") String host, + @Param("startTime") Date startTime, + @Param("endTime") Date endTime, + @Param("offset") int offset, + @Param("pageSize") int pageSize + ); + + /** + * query task list by process id and task name + * @param processInstanceId + * @param name + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "name", column = "name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "taskType", column = "task_type",javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "processDefinitionId", column = "process_definition_id",javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "processInstanceId", column = "process_instance_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "processInstanceName", column = "process_instance_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "taskJson", column = "task_json", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "state", column = "state", typeHandler = EnumOrdinalTypeHandler.class, javaType = ExecutionStatus.class, jdbcType = JdbcType.TINYINT), + @Result(property = "submitTime", column = "submit_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "startTime", column = "start_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "endTime", column = "end_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "host", column = "host", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "executePath", column = "execute_path", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "logPath", column = "log_path", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "alertFlag", column = "alert_flag", typeHandler = EnumOrdinalTypeHandler.class, javaType = Flag.class, jdbcType = JdbcType.TINYINT), + @Result(property = "retryTimes", column = "retry_times", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "maxRetryTimes", column = "max_retry_times", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "retryInterval", column = "retry_interval", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "pid", column = "pid", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "appLink", column = "app_link", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "duration", column = "duration", javaType = Long.class, jdbcType = JdbcType.BIGINT), + @Result(property = "flag", column = "flag", typeHandler = EnumOrdinalTypeHandler.class, javaType = Flag.class, jdbcType = JdbcType.TINYINT), + @Result(property = "taskInstancePriority", column = "task_instance_priority", javaType = Priority.class, typeHandler = EnumOrdinalTypeHandler.class, jdbcType = JdbcType.TINYINT) + }) + @SelectProvider(type = TaskInstanceMapperProvider.class, method = "queryByInstanceIdAndName") + TaskInstance queryByInstanceIdAndName(@Param("processInstanceId") int processInstanceId, + @Param("name") String name); +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/TaskInstanceMapperProvider.java b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/TaskInstanceMapperProvider.java new file mode 100644 index 0000000000..09ffb0125b --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/TaskInstanceMapperProvider.java @@ -0,0 +1,407 @@ +/* + * 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.dao.mapper; + +import cn.escheduler.common.enums.ExecutionStatus; +import cn.escheduler.common.enums.Flag; +import cn.escheduler.common.enums.Priority; +import cn.escheduler.common.utils.EnumFieldUtil; +import org.apache.commons.lang3.StringUtils; +import org.apache.ibatis.jdbc.SQL; + +import java.util.Map; + +/** + * task instance mapper provider + */ +public class TaskInstanceMapperProvider { + + private static final String TABLE_NAME = "t_escheduler_task_instance"; + private static final String DEFINE_TABLE_NAME = "t_escheduler_process_definition"; + private static final String INSTANCE_TABLE_NAME = "t_escheduler_process_instance"; + + /** + * insert task instance + * + * @param parameter + * @return + */ + public String insert(Map parameter) { + return new SQL() { + { + INSERT_INTO(TABLE_NAME); + VALUES("`name`", "#{taskInstance.name}"); + VALUES("`task_type`", "#{taskInstance.taskType}"); + VALUES("`process_definition_id`","#{taskInstance.processDefinitionId}"); + VALUES("`process_instance_id`", "#{taskInstance.processInstanceId}"); + VALUES("`task_json`", "#{taskInstance.taskJson}"); + VALUES("`state`", EnumFieldUtil.genFieldStr("taskInstance.state", ExecutionStatus.class)); + VALUES("`submit_time`", "#{taskInstance.submitTime}"); + VALUES("`start_time`", "#{taskInstance.startTime}"); + VALUES("`end_time`", "#{taskInstance.endTime}"); + VALUES("`host`", "#{taskInstance.host}"); + VALUES("`execute_path`", "#{taskInstance.executePath}"); + VALUES("`log_path`", "#{taskInstance.logPath}"); + VALUES("`alert_flag`", EnumFieldUtil.genFieldStr("taskInstance.alertFlag", Flag.class)); + VALUES("`retry_times`", "#{taskInstance.retryTimes}"); + VALUES("`pid`", "#{taskInstance.pid}"); + VALUES("`max_retry_times`", "#{taskInstance.maxRetryTimes}"); + VALUES("`retry_interval`", "#{taskInstance.retryInterval}"); + VALUES("`app_link`", "#{taskInstance.appLink}"); + VALUES("`flag`", EnumFieldUtil.genFieldStr("taskInstance.flag", Flag.class)); + VALUES("`task_instance_priority`", EnumFieldUtil.genFieldStr("taskInstance.taskInstancePriority", Priority.class)); + + } + }.toString(); + } + + /** + * delete task instance + * + * @param parameter + * @return + */ + public String delete(Map parameter) { + return new SQL() { + { + DELETE_FROM(TABLE_NAME); + + WHERE("`id`=#{taskInstanceId}"); + } + }.toString(); + } + + /** + * update task instance + * + * @param parameter + * @return + */ + public String update(Map parameter) { + return new SQL() { + { + UPDATE(TABLE_NAME); + + SET("`name`=#{taskInstance.name}"); + SET("`task_type`=#{taskInstance.taskType}"); + SET("`process_definition_id`=#{taskInstance.processDefinitionId}"); + SET("`process_instance_id`=#{taskInstance.processInstanceId}"); + SET("`task_json`=#{taskInstance.taskJson}"); + SET("`state`="+ EnumFieldUtil.genFieldStr("taskInstance.state", ExecutionStatus.class)); + SET("`submit_time`=#{taskInstance.submitTime}"); + SET("`start_time`=#{taskInstance.startTime}"); + SET("`end_time`=#{taskInstance.endTime}"); + SET("`host`=#{taskInstance.host}"); + SET("`execute_path`=#{taskInstance.executePath}"); + SET("`log_path`=#{taskInstance.logPath}"); + SET("`alert_flag`="+ EnumFieldUtil.genFieldStr("taskInstance.alertFlag", Flag.class)); + SET("`retry_times`=#{taskInstance.retryTimes}"); + SET("`pid`=#{taskInstance.pid}"); + SET("`max_retry_times`=#{taskInstance.maxRetryTimes}"); + SET("`retry_interval`=#{taskInstance.retryInterval}"); + SET("`app_link`=#{taskInstance.appLink}"); + SET("`flag`="+ EnumFieldUtil.genFieldStr("taskInstance.flag", Flag.class)); + SET("`task_instance_priority`="+ EnumFieldUtil.genFieldStr("taskInstance.taskInstancePriority", Priority.class)); + + WHERE("`id`=#{taskInstance.id}"); + + } + }.toString(); + } + + /** + * query task by id + * @param parameter + * @return + */ + public String queryById(Map parameter) { + return new SQL() { + { + SELECT("*, UNIX_TIMESTAMP(end_time)-UNIX_TIMESTAMP(start_time) as duration"); + FROM(TABLE_NAME); + WHERE("id = #{taskInstanceId}"); + } + }.toString(); + } + + + /** + * query task id list by process instance id and state + * @param parameter + * @return + */ + public String queryTaskByProcessIdAndState(Map parameter){ + return new SQL(){ + { + SELECT("id"); + FROM(TABLE_NAME); + WHERE("`process_instance_id` = #{processInstanceId}"); + WHERE("`state` = #{state}"); + WHERE("`flag` = 1 "); + } + }.toString(); + } + + /** + * query valid task instance list by process id + * @param parameter + * @return + */ + public String findValidTaskListByProcessId(Map parameter) { + return new SQL() + { + { + SELECT("*, UNIX_TIMESTAMP(end_time)-UNIX_TIMESTAMP(start_time) as duration"); + FROM(TABLE_NAME ); + WHERE("`process_instance_id` = #{processInstanceId} "); + WHERE("`flag` = " + EnumFieldUtil.genFieldStr("flag", Flag.class)); + ORDER_BY("start_time desc"); + } + }.toString(); + } + + /** + * + * count task number group by state and user + * @param parameter + * @return + */ + public String countTaskInstanceStateByUser(Map parameter){ + return new SQL(){ + { + SELECT ("state, count(0) as count"); + FROM(TABLE_NAME + " t"); + LEFT_OUTER_JOIN(DEFINE_TABLE_NAME+ " d on d.id=t.process_definition_id"); + LEFT_OUTER_JOIN("t_escheduler_project p on p.id=d.project_id"); + if(parameter.get("projectId") != null && (int)parameter.get("projectId") != 0){ + WHERE( "p.id = #{projectId} "); + }else{ + if(parameter.get("userType") != null && String.valueOf(parameter.get("userType")) == "GENERAL_USER") { + AND(); + WHERE("d.project_id in (select id as project_id from t_escheduler_project tp where tp.user_id= #{userId} " + + "union select project_id from t_escheduler_relation_project_user tr where tr.user_id= #{userId} )"); + + } + } + WHERE("t.flag = 1 and t.start_time > #{startTime} and t.start_time <= #{endTime}"); + GROUP_BY("t.state"); + } + }.toString(); + } + + + /** + * query task list by host and state + * + * @param parameter + * @return + */ + public String queryByHostAndStatus(Map parameter) { + StringBuffer strStates = new StringBuffer(); + int[] stateArray = (int[]) parameter.get("states"); + for(int i=0;i parameter) { + StringBuffer strStates = new StringBuffer(); + int[] stateArray = (int[]) parameter.get("states"); + for(int i=0;i parameter) { + StringBuffer strStates = new StringBuffer(); + int[] stateArray = (int[]) parameter.get("states"); + int state = ExecutionStatus.NEED_FAULT_TOLERANCE.ordinal(); + for(int i=0;i parameter) { + return new SQL() { + { + SELECT("instance.*,process.name as process_instance_name, UNIX_TIMESTAMP(instance.end_time)-UNIX_TIMESTAMP(instance.start_time) as duration"); + + FROM(TABLE_NAME + " instance"); + + JOIN(DEFINE_TABLE_NAME + " define ON instance.process_definition_id = define.id"); + JOIN(INSTANCE_TABLE_NAME + " process on process.id=instance.process_instance_id"); + WHERE("define.project_id = #{projectId}"); + + Object start = parameter.get("startTime"); + if(start != null && StringUtils.isNotEmpty(start.toString())){ + WHERE("instance.start_time > #{startTime} and instance.start_time <= #{endTime}"); + } + + if(parameter.get("processInstanceId") != null && (int)parameter.get("processInstanceId") != 0){ + WHERE( "instance.process_instance_id = #{processInstanceId} "); + } + + Object searchVal = parameter.get("searchVal"); + if(searchVal != null && StringUtils.isNotEmpty(searchVal.toString())){ + WHERE( " instance.name like concat('%', #{searchVal}, '%') "); + } + Object taskName = parameter.get("taskName"); + if(taskName != null && StringUtils.isNotEmpty(taskName.toString())){ + WHERE( " instance.name=#{taskName}"); + } + Object states = parameter.get("states"); + if(states != null && StringUtils.isNotEmpty(states.toString())){ + String stateStr = states.toString(); + WHERE("instance.state in ( "+ stateStr + " )"); + } + Object host = parameter.get("host"); + if(host != null && StringUtils.isNotEmpty(host.toString())){ + WHERE( "instance.host like concat('%', #{host}, '%') "); + } + ORDER_BY("instance.start_time desc limit #{offset},#{pageSize} "); + } + }.toString(); + + } + + + /** + * count task number by search fields + * @param parameter + * @return + */ + public String countTaskInstance(Map parameter) { + return new SQL() { + { + SELECT("count(1)"); + + + FROM(TABLE_NAME + " instance"); + + JOIN(DEFINE_TABLE_NAME + " define ON instance.process_definition_id = define.id"); + WHERE("define.project_id = #{projectId}"); + + if(parameter.get("processInstanceId") != null && (int)parameter.get("processInstanceId") != 0){ + WHERE( "instance.process_instance_id = #{processInstanceId} "); + } + Object startTime = parameter.get("startTime"); + if(startTime != null && StringUtils.isNotEmpty(startTime.toString())) { + WHERE("instance.start_time > #{startTime} and instance.start_time <= #{endTime}"); + } + Object searchVal = parameter.get("searchVal"); + if(searchVal != null && StringUtils.isNotEmpty(searchVal.toString())){ + WHERE( " instance.name like concat('%', #{searchVal}, '%') "); + } + Object taskName = parameter.get("taskName"); + if(taskName != null && StringUtils.isNotEmpty(taskName.toString())){ + WHERE( " instance.name=#{taskName}"); + } + Object states = parameter.get("states"); + if(states != null && StringUtils.isNotEmpty(states.toString())){ + String stateStr = states.toString(); + WHERE("instance.state in ( "+ stateStr + " )"); + } + Object host = parameter.get("host"); + if(host != null && StringUtils.isNotEmpty(host.toString())){ + WHERE( "instance.host like concat('%', #{host}, '%') "); + } + } + }.toString(); + } + + /** + * query task list by process id and task name + * @param parameter + * @return + */ + public String queryByInstanceIdAndName(Map parameter){ + return new SQL(){ + { + SELECT("*,UNIX_TIMESTAMP(end_time)-UNIX_TIMESTAMP(start_time) as duration"); + FROM(TABLE_NAME); + WHERE("`process_instance_id` = #{processInstanceId}"); + WHERE("`name` = #{name}"); + WHERE("`flag` = 1 "); + } + }.toString(); + } + + +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/TenantMapper.java b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/TenantMapper.java new file mode 100644 index 0000000000..c451f6ce20 --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/TenantMapper.java @@ -0,0 +1,137 @@ +/* + * 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.dao.mapper; + +import cn.escheduler.dao.model.Tenant; +import org.apache.ibatis.annotations.*; +import org.apache.ibatis.type.JdbcType; + +import java.sql.Timestamp; +import java.util.List; + +/** + * tenant mapper + */ +public interface TenantMapper { + + /** + * insert tenant + * @param tenant + * @return + */ + @InsertProvider(type = TenantMapperProvider.class, method = "insert") + @Options(useGeneratedKeys = true,keyProperty = "tenant.id") + @SelectKey(statement = "SELECT LAST_INSERT_ID()", keyProperty = "tenant.id", before = false, resultType = int.class) + int insert(@Param("tenant") Tenant tenant); + + + /** + * delete tenant + * @param id + * @return + */ + @DeleteProvider(type = TenantMapperProvider.class, method = "deleteById") + int deleteById(@Param("id") int id); + + + /** + * update tenant + * + * @param tenant + * @return + */ + @UpdateProvider(type = TenantMapperProvider.class, method = "update") + int update(@Param("tenant") Tenant tenant); + + + /** + * query tenant by id + * @param tenantId + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "tenantCode", column = "tenant_code", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "tenantName", column = "tenant_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "desc", column = "desc", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "queueId", column = "queue_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "createTime", column = "create_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "updateTime", column = "update_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + }) + @SelectProvider(type = TenantMapperProvider.class, method = "queryById") + Tenant queryById(@Param("tenantId") int tenantId); + + /** + * query tenant by code + * @param tenantCode + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "tenantCode", column = "tenant_code", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "tenantName", column = "tenant_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "desc", column = "desc", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "queueId", column = "queue_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "createTime", column = "create_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "updateTime", column = "update_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + }) + @SelectProvider(type = TenantMapperProvider.class, method = "queryByTenantCode") + Tenant queryByTenantCode(@Param("tenantCode") String tenantCode); + + /** + * count tenant by search value + * @param searchVal + * @return + */ + @SelectProvider(type = TenantMapperProvider.class, method = "countTenantPaging") + Integer countTenantPaging(@Param("searchVal") String searchVal); + + + /** + * query tenant list paging + * @param searchVal + * @param offset + * @param pageSize + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "tenantCode", column = "tenant_code", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "tenantName", column = "tenant_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "queueId", column = "queue_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "desc", column = "desc", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "queueName", column = "queue_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "createTime", column = "create_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "updateTime", column = "update_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE) + }) + @SelectProvider(type = TenantMapperProvider.class, method = "queryTenantPaging") + List queryTenantPaging(@Param("searchVal") String searchVal, + @Param("offset") Integer offset, + @Param("pageSize") Integer pageSize); + + /** + * query all tenant list + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "tenantCode", column = "tenant_code", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "tenantName", column = "tenant_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "queueId", column = "queue_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "desc", column = "desc", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "createTime", column = "create_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "updateTime", column = "update_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE) + }) + @SelectProvider(type = TenantMapperProvider.class, method = "queryAllTenant") + List queryAllTenant(); +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/TenantMapperProvider.java b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/TenantMapperProvider.java new file mode 100644 index 0000000000..8560fc950b --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/TenantMapperProvider.java @@ -0,0 +1,182 @@ +/* + * 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.dao.mapper; + +import org.apache.commons.lang3.StringUtils; +import org.apache.ibatis.jdbc.SQL; + +import java.util.Map; + +/** + * tenant mapper provider + */ +public class TenantMapperProvider { + + private static final String TABLE_NAME = "t_escheduler_tenant"; + + /** + * insert tenant + * + * @param parameter + * @return + */ + public String insert(Map parameter) { + return new SQL() { + { + INSERT_INTO(TABLE_NAME); + VALUES("`tenant_code`", "#{tenant.tenantCode}"); + VALUES("`tenant_name`", "#{tenant.tenantName}"); + VALUES("`queue_id`", "#{tenant.queueId}"); + VALUES("`desc`", "#{tenant.desc}"); + VALUES("`create_time`", "#{tenant.createTime}"); + VALUES("`update_time`", "#{tenant.updateTime}"); + + } + }.toString(); + } + + /** + * delete tenant + * + * @param parameter + * @return + */ + public String deleteById(Map parameter) { + return new SQL() { + { + DELETE_FROM(TABLE_NAME); + + WHERE("`id`=#{id}"); + } + }.toString(); + } + + /** + * update tenant + * + * @param parameter + * @return + */ + public String update(Map parameter) { + return new SQL() { + { + UPDATE(TABLE_NAME); + + SET("`tenant_name`=#{tenant.tenantName}"); + SET("`tenant_code`=#{tenant.tenantCode}"); + SET("`desc`=#{tenant.desc}"); + SET("`queue_id`=#{tenant.queueId}"); + SET("`update_time`=#{tenant.updateTime}"); + + WHERE("`id`=#{tenant.id}"); + } + }.toString(); + } + + + /** + * query tenant by id + * + * @param parameter + * @return + */ + public String queryById(Map parameter) { + return new SQL() { + { + SELECT("*"); + + FROM(TABLE_NAME); + + WHERE("`id` = #{tenantId}"); + } + }.toString(); + } + + /** + * query tenant by code + * + * @param parameter + * @return + */ + public String queryByTenantCode(Map parameter) { + return new SQL() { + { + SELECT("*"); + + FROM(TABLE_NAME); + + WHERE("`tenant_code` = #{tenantCode}"); + } + }.toString(); + } + + + /** + * count tenant by search value + * @param parameter + * @return + */ + public String countTenantPaging(Map parameter) { + return new SQL() {{ + SELECT("count(0)"); + FROM(TABLE_NAME +" t,t_escheduler_queue q"); + WHERE( " t.queue_id = q.id"); + Object searchVal = parameter.get("searchVal"); + if(searchVal != null && StringUtils.isNotEmpty(searchVal.toString())){ + WHERE( " tenant_name like concat('%', #{searchVal}, '%') "); + } + }}.toString(); + } + + /** + * query tenant list paging + * @param parameter + * @return + */ + public String queryTenantPaging(Map parameter) { + return new SQL() { + { + SELECT("t.*,q.queue_name as queueName"); + FROM(TABLE_NAME +" t,t_escheduler_queue q"); + WHERE( " t.queue_id = q.id"); + Object searchVal = parameter.get("searchVal"); + if(searchVal != null && StringUtils.isNotEmpty(searchVal.toString())){ + WHERE( " t.tenant_name like concat('%', #{searchVal}, '%') "); + } + ORDER_BY(" t.update_time desc limit #{offset},#{pageSize} "); + } + }.toString(); + + } + + /** + * query all tenant list + * @param parameter + * @return + */ + public String queryAllTenant(Map parameter) { + return new SQL() { + { + SELECT("*"); + FROM(TABLE_NAME); + } + }.toString(); + + } + + +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/UDFUserMapper.java b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/UDFUserMapper.java new file mode 100644 index 0000000000..5ad1f13a95 --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/UDFUserMapper.java @@ -0,0 +1,55 @@ +/* + * 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.dao.mapper; + +import cn.escheduler.dao.model.UDFUser; +import org.apache.ibatis.annotations.DeleteProvider; +import org.apache.ibatis.annotations.InsertProvider; +import org.apache.ibatis.annotations.Param; + + +/** + * udf user relation mapper + */ +public interface UDFUserMapper { + + /** + * insert udf user + * @param udfUser + * @return + */ + @InsertProvider(type = UDFUserMapperProvider.class, method = "insert") + int insert(@Param("udfUser") UDFUser udfUser); + + + /** + * delete by user id + * @param userId + * @return + */ + @DeleteProvider(type = UDFUserMapperProvider.class, method = "deleteByUserId") + int deleteByUserId(@Param("userId") int userId); + + /** + * delete by udf function id + * @param udfFuncId + * @return + */ + @DeleteProvider(type = UDFUserMapperProvider.class, method = "deleteByUdfFuncId") + int deleteByUdfFuncId(@Param("udfFuncId") int udfFuncId); + +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/UDFUserMapperProvider.java b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/UDFUserMapperProvider.java new file mode 100644 index 0000000000..bacc0f585e --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/UDFUserMapperProvider.java @@ -0,0 +1,76 @@ +/* + * 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.dao.mapper; + +import org.apache.ibatis.jdbc.SQL; + +import java.util.Map; + +/** + * udf user mapper provider + */ +public class UDFUserMapperProvider { + + private static final String TABLE_NAME = "t_escheduler_relation_udfs_user"; + + + /** + * insert udf user + * + * @param parameter + * @return + */ + public String insert(Map parameter) { + return new SQL() {{ + INSERT_INTO(TABLE_NAME); + + VALUES("`udf_id`", "#{udfUser.udfId}"); + VALUES("`user_id`", "#{udfUser.userId}"); + VALUES("`perm`", "#{udfUser.perm}"); + VALUES("`create_time`", "#{udfUser.createTime}"); + VALUES("`update_time`", "#{udfUser.updateTime}"); + }}.toString(); + } + + + /** + * delete by user id + * @param parameter + * @return + */ + public String deleteByUserId(Map parameter) { + return new SQL() {{ + DELETE_FROM(TABLE_NAME); + + WHERE("`user_id` = #{userId}"); + }}.toString(); + } + + /** + * delete by udf function id + * + * @param parameter + * @return + */ + public String deleteByUdfFuncId(Map parameter) { + return new SQL() {{ + DELETE_FROM(TABLE_NAME); + + WHERE("`udf_id` = #{udfFuncId}"); + }}.toString(); + } +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/UdfFuncMapper.java b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/UdfFuncMapper.java new file mode 100644 index 0000000000..d37ab3a1f0 --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/UdfFuncMapper.java @@ -0,0 +1,273 @@ +/* + * 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.dao.mapper; + +import cn.escheduler.common.enums.UdfType; +import cn.escheduler.dao.model.UdfFunc; +import org.apache.ibatis.annotations.*; +import org.apache.ibatis.type.EnumOrdinalTypeHandler; +import org.apache.ibatis.type.JdbcType; + +import java.sql.Timestamp; +import java.util.List; + +/** + * und function mapper + */ +public interface UdfFuncMapper { + + /** + * insert udf function + * + * @param udf + * @return + */ + @InsertProvider(type = UdfFuncMapperProvider.class, method = "insert") + @SelectKey(statement = "SELECT LAST_INSERT_ID() AS id", keyProperty = "udf.id", resultType = int.class, before = false) + int insert(@Param("udf") UdfFunc udf); + + /** + * update udf function + * + * @param udf + * @return + */ + @UpdateProvider(type = UdfFuncMapperProvider.class, method = "update") + int update(@Param("udf") UdfFunc udf); + + /** + * query udf function by id + * + * @param id + * @return + */ + @Results(value = { + @Result(property = "id", column = "id", id = true, javaType = int.class, jdbcType = JdbcType.INTEGER), + @Result(property = "userId", column = "user_id", javaType = int.class, jdbcType = JdbcType.INTEGER), + @Result(property = "funcName", column = "func_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "className", column = "class_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "argTypes", column = "arg_types", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "database", column = "database", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "desc", column = "desc", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "resourceId", column = "resource_id", javaType = int.class, jdbcType = JdbcType.INTEGER), + @Result(property = "resourceName", column = "resource_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "type", column = "type", typeHandler = EnumOrdinalTypeHandler.class, javaType = UdfType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "createTime", column = "create_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "updateTime", column = "update_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE) + }) + @SelectProvider(type = UdfFuncMapperProvider.class, method = "queryUdfById") + UdfFunc queryUdfById(@Param("id") int id); + + /** + * query udf list by id string + * + * @param ids + * @return + */ + @Results(value = { + @Result(property = "id", column = "id", id = true, javaType = int.class, jdbcType = JdbcType.INTEGER), + @Result(property = "userId", column = "user_id", javaType = int.class, jdbcType = JdbcType.INTEGER), + @Result(property = "funcName", column = "func_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "className", column = "class_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "argTypes", column = "arg_types", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "database", column = "database", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "desc", column = "desc", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "resourceId", column = "resource_id", javaType = int.class, jdbcType = JdbcType.INTEGER), + @Result(property = "resourceName", column = "resource_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "type", column = "type", typeHandler = EnumOrdinalTypeHandler.class, javaType = UdfType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "createTime", column = "create_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "updateTime", column = "update_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE) + }) + @SelectProvider(type = UdfFuncMapperProvider.class, method = "queryUdfByIdStr") + List queryUdfByIdStr(@Param("ids") String ids); + + /** + * count udf number by user id + * + * @param userId + * @return + */ + @SelectProvider(type = UdfFuncMapperProvider.class, method = "countUserUdfFunc") + int countUserUdfFunc(@Param("userId") int userId); + + /** + * count udf number + * + * @return + */ + @SelectProvider(type = UdfFuncMapperProvider.class, method = "countAllUdfFunc") + int countAllUdfFunc(); + + /** + * query udf function paging + * @param userId + * @param searchVal + * @param offset + * @param pageSize + * @return + */ + @Results(value = { + @Result(property = "id", column = "id", id = true, javaType = int.class, jdbcType = JdbcType.INTEGER), + @Result(property = "userId", column = "user_id", javaType = int.class, jdbcType = JdbcType.INTEGER), + @Result(property = "funcName", column = "func_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "className", column = "class_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "argTypes", column = "arg_types", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "database", column = "database", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "desc", column = "desc", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "resourceId", column = "resource_id", javaType = int.class, jdbcType = JdbcType.INTEGER), + @Result(property = "resourceName", column = "resource_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "type", column = "type", typeHandler = EnumOrdinalTypeHandler.class, javaType = UdfType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "createTime", column = "create_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "updateTime", column = "update_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE) + }) + @SelectProvider(type = UdfFuncMapperProvider.class, method = "queryUdfFuncPaging") + List queryUdfFuncPaging(@Param("userId") int userId, @Param("searchVal") String searchVal, + @Param("offset") int offset, + @Param("pageSize") int pageSize); + + /** + * query all udf function paging + * @param searchVal + * @param offset + * @param pageSize + * @return + */ + @Results(value = { + @Result(property = "id", column = "id", id = true, javaType = int.class, jdbcType = JdbcType.INTEGER), + @Result(property = "userId", column = "user_id", javaType = int.class, jdbcType = JdbcType.INTEGER), + @Result(property = "funcName", column = "func_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "className", column = "class_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "argTypes", column = "arg_types", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "database", column = "database", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "desc", column = "desc", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "resourceId", column = "resource_id", javaType = int.class, jdbcType = JdbcType.INTEGER), + @Result(property = "resourceName", column = "resource_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "type", column = "type", typeHandler = EnumOrdinalTypeHandler.class, javaType = UdfType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "createTime", column = "create_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "updateTime", column = "update_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE) + }) + @SelectProvider(type = UdfFuncMapperProvider.class, method = "queryAllUdfFuncPaging") + List queryAllUdfFuncPaging(@Param("searchVal") String searchVal, + @Param("offset") int offset, + @Param("pageSize") int pageSize); + + + /** + * query udf function by type + * @param userId + * @param type + * @return + */ + @Results(value = { + @Result(property = "id", column = "id", id = true, javaType = int.class, jdbcType = JdbcType.INTEGER), + @Result(property = "userId", column = "user_id", javaType = int.class, jdbcType = JdbcType.INTEGER), + @Result(property = "funcName", column = "func_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "className", column = "class_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "argTypes", column = "arg_types", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "database", column = "database", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "desc", column = "desc", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "resourceId", column = "resource_id", javaType = int.class, jdbcType = JdbcType.INTEGER), + @Result(property = "resourceName", column = "resource_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "type", column = "type", typeHandler = EnumOrdinalTypeHandler.class, javaType = UdfType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "createTime", column = "create_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "updateTime", column = "update_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE) + }) + @SelectProvider(type = UdfFuncMapperProvider.class, method = "getUdfFuncByType") + List getUdfFuncByType(@Param("userId") int userId,@Param("type") Integer type); + + + /** + * query udf function by name + * @param funcName + * @return + */ + @Results(value = { + @Result(property = "id", column = "id", id = true, javaType = int.class, jdbcType = JdbcType.INTEGER), + @Result(property = "userId", column = "user_id", javaType = int.class, jdbcType = JdbcType.INTEGER), + @Result(property = "funcName", column = "func_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "className", column = "class_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "argTypes", column = "arg_types", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "database", column = "database", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "desc", column = "desc", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "resourceId", column = "resource_id", javaType = int.class, jdbcType = JdbcType.INTEGER), + @Result(property = "resourceName", column = "resource_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "type", column = "type", typeHandler = EnumOrdinalTypeHandler.class, javaType = UdfType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "createTime", column = "create_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "updateTime", column = "update_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE) + }) + @SelectProvider(type = UdfFuncMapperProvider.class, method = "queryUdfFuncByName") + UdfFunc queryUdfFuncByName(@Param("func_name") String funcName); + + /** + * delete udf function + * + * @param udfFuncId + * @return + */ + @DeleteProvider(type = UdfFuncMapperProvider.class, method = "delete") + int delete(@Param("udfFuncId") int udfFuncId); + + + + /** + * query udf function except user + * @param userId + * @return + */ + @Results(value = { + @Result(property = "id", column = "id", id = true, javaType = int.class, jdbcType = JdbcType.INTEGER), + @Result(property = "userId", column = "user_id", javaType = int.class, jdbcType = JdbcType.INTEGER), + @Result(property = "funcName", column = "func_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "className", column = "class_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "argTypes", column = "arg_types", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "database", column = "database", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "desc", column = "desc", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "resourceId", column = "resource_id", javaType = int.class, jdbcType = JdbcType.INTEGER), + @Result(property = "resourceName", column = "resource_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "type", column = "type", typeHandler = EnumOrdinalTypeHandler.class, javaType = UdfType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "createTime", column = "create_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "updateTime", column = "update_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE) + }) + @SelectProvider(type = UdfFuncMapperProvider.class, method = "queryUdfFuncExceptUserId") + List queryUdfFuncExceptUserId(@Param("userId") int userId); + + + + /** + * query udf function authorized to user + * @param userId + * @return + */ + @Results(value = { + @Result(property = "id", column = "id", id = true, javaType = int.class, jdbcType = JdbcType.INTEGER), + @Result(property = "userId", column = "user_id", javaType = int.class, jdbcType = JdbcType.INTEGER), + @Result(property = "funcName", column = "func_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "className", column = "class_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "argTypes", column = "arg_types", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "database", column = "database", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "desc", column = "desc", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "resourceId", column = "resource_id", javaType = int.class, jdbcType = JdbcType.INTEGER), + @Result(property = "resourceName", column = "resource_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "type", column = "type", typeHandler = EnumOrdinalTypeHandler.class, javaType = UdfType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "createTime", column = "create_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "updateTime", column = "update_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE) + }) + @SelectProvider(type = UdfFuncMapperProvider.class, method = "authedUdfFunc") + List authedUdfFunc(@Param("userId") int userId); + + +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/UdfFuncMapperProvider.java b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/UdfFuncMapperProvider.java new file mode 100644 index 0000000000..55ef65e3a2 --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/UdfFuncMapperProvider.java @@ -0,0 +1,253 @@ +/* + * 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.dao.mapper; + +import cn.escheduler.common.enums.UdfType; +import cn.escheduler.common.utils.EnumFieldUtil; +import org.apache.commons.lang3.StringUtils; +import org.apache.ibatis.jdbc.SQL; + +import java.util.Map; + +/** + * und function mapper + */ +public class UdfFuncMapperProvider { + private final String TABLE_NAME = "t_escheduler_udfs"; + public static final String USER_UDFS_RELATION_TABLE_NAME = "t_escheduler_relation_udfs_user"; + + /** + * insert udf function + * @param parameter + * @return + */ + public String insert(Map parameter) { + return new SQL() { + { + INSERT_INTO(TABLE_NAME); + VALUES("`user_id`", "#{udf.userId}"); + VALUES("`func_name`", "#{udf.funcName,jdbcType=VARCHAR}"); + VALUES("`class_name`", "#{udf.className}"); + VALUES("`arg_types`", "#{udf.argTypes}"); + VALUES("`database`", "#{udf.database}"); + VALUES("`desc`", "#{udf.desc}"); + VALUES("`resource_id`", "#{udf.resourceId}"); + VALUES("`resource_name`", "#{udf.resourceName}"); + VALUES("`type`", EnumFieldUtil.genFieldStr("udf.type", UdfType.class)); + VALUES("`create_time`", "#{udf.createTime}"); + VALUES("`update_time`", "#{udf.updateTime}"); + } + }.toString(); + } + + /** + * update udf function + * + * @param parameter + * @return + */ + public String update(Map parameter) { + return new SQL() { + { + UPDATE(TABLE_NAME); + + SET("`user_id`=#{udf.userId}"); + SET("`func_name`=#{udf.funcName}"); + SET("`class_name`=#{udf.className}"); + SET("`arg_types`=#{udf.argTypes}"); + SET("`database`=#{udf.database}"); + SET("`desc`=#{udf.desc}"); + SET("`resource_id`=#{udf.resourceId}"); + SET("`resource_name`=#{udf.resourceName}"); + SET("`type`="+EnumFieldUtil.genFieldStr("udf.type", UdfType.class)); + SET("`update_time`=#{udf.updateTime}"); + + WHERE("`id`=#{udf.id}"); + } + }.toString(); + } + + /** + * query udf function by id + * + * @param parameter + * @return + */ + public String queryUdfById(Map parameter) { + + return new SQL() {{ + SELECT("r.*"); + + FROM(TABLE_NAME + " r"); + WHERE("r.id = #{id}"); + }}.toString(); + } + + /** + * query udf list by id string + * + * @param parameter + * @return + */ + public String queryUdfByIdStr(Map parameter) { + + String ids = (String) parameter.get("ids"); + + return new SQL() {{ + SELECT("*"); + + FROM(TABLE_NAME); + WHERE("`id` in (" + ids +")"); + ORDER_BY("`id` asc"); + }}.toString(); + } + + /** + * query all udf function paging + * @param parameter + * @return + */ + public String queryUdfFuncPaging(Map parameter) { + return new SQL() {{ + SELECT("*"); + FROM(TABLE_NAME ); + WHERE("id in (select udf_id from "+USER_UDFS_RELATION_TABLE_NAME+" where user_id=#{userId} union select id as udf_id from "+TABLE_NAME+" where user_id=#{userId})"); + Object searchVal = parameter.get("searchVal"); + if(searchVal != null && StringUtils.isNotEmpty(searchVal.toString())){ + WHERE( " name like concat('%', #{searchVal}, '%') "); + } + ORDER_BY("create_time desc limit #{offset},#{pageSize} "); + + }}.toString(); + } + + /** + * query all udf function paging + * @param parameter + * @return + */ + public String queryAllUdfFuncPaging(Map parameter) { + return new SQL() {{ + SELECT("*"); + FROM(TABLE_NAME ); + Object searchVal = parameter.get("searchVal"); + if(searchVal != null && StringUtils.isNotEmpty(searchVal.toString())){ + WHERE( " name like concat('%', #{searchVal}, '%') "); + } + ORDER_BY("create_time desc limit #{offset},#{pageSize} "); + + }}.toString(); + } + + /** + * count udf number by user id + * + * @param parameter + * @return + */ + public String countUserUdfFunc(Map parameter) { + return new SQL() {{ + SELECT("count(0)"); + FROM(TABLE_NAME); + WHERE("id in (select udf_id from "+USER_UDFS_RELATION_TABLE_NAME+" where user_id=#{userId} union select id as udf_id from "+TABLE_NAME+" where user_id=#{userId})"); + }}.toString(); + } + + /** + * count udf number + * + * @param parameter + * @return + */ + public String countAllUdfFunc(Map parameter) { + return new SQL() {{ + SELECT("count(0)"); + FROM(TABLE_NAME); + }}.toString(); + } + + /** + * query udf function by type + * @param parameter + * @return + */ + public String getUdfFuncByType(Map parameter) { + return new SQL() {{ + SELECT("*"); + FROM(TABLE_NAME ); + WHERE("type = #{type}"); + WHERE("id in (select udf_id from "+USER_UDFS_RELATION_TABLE_NAME+" where user_id=#{userId} union select id as udf_id from "+TABLE_NAME+" where user_id=#{userId})"); + }}.toString(); + } + + /** + * query udf function by name + * @param parameter + * @return + */ + public String queryUdfFuncByName(Map parameter) { + return new SQL() {{ + SELECT("*"); + FROM(TABLE_NAME ); + WHERE("func_name = #{func_name}"); + }}.toString(); + } + + /** + * delete udf function + * + * @param parameter + * @return + */ + public String delete(Map parameter) { + return new SQL() { + { + DELETE_FROM(TABLE_NAME); + + WHERE("`id` = #{udfFuncId}"); + } + }.toString(); + } + + /** + * + * query udf function authorized to user + * @param parameter + * @return + */ + public String authedUdfFunc(Map parameter) { + return new SQL() {{ + SELECT("u.*"); + FROM(TABLE_NAME + " u,t_escheduler_relation_udfs_user rel"); + WHERE(" u.id = rel.udf_id AND rel.user_id = #{userId}"); + }}.toString(); + } + + /** + * query udf function except user + * + * @param parameter + * @return + */ + public String queryUdfFuncExceptUserId(Map parameter) { + return new SQL() {{ + SELECT("*"); + FROM(TABLE_NAME); + WHERE("user_id <> #{userId}"); + }}.toString(); + } +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/UserAlertGroupMapper.java b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/UserAlertGroupMapper.java new file mode 100644 index 0000000000..9e13aff997 --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/UserAlertGroupMapper.java @@ -0,0 +1,92 @@ +/* + * 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.dao.mapper; + +import cn.escheduler.common.enums.UserType; +import cn.escheduler.dao.model.User; +import cn.escheduler.dao.model.UserAlertGroup; +import org.apache.ibatis.annotations.*; +import org.apache.ibatis.type.EnumOrdinalTypeHandler; +import org.apache.ibatis.type.JdbcType; + +import java.sql.Timestamp; +import java.util.List; + +/** + * user alert group mapper + */ +public interface UserAlertGroupMapper { + + /** + * insert user alert group + * @param userAlertGroup + * @return + */ + @InsertProvider(type = UserAlertGroupMapperProvider.class, method = "insert") + @Options(useGeneratedKeys = true,keyProperty = "userAlertGroup.id") + @SelectKey(statement = "SELECT LAST_INSERT_ID()", keyProperty = "userAlertGroup.id", before = false, resultType = int.class) + int insert(@Param("userAlertGroup") UserAlertGroup userAlertGroup); + + + /** + * query user list by alert group id + * + * @param alertgroupId + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "userName", column = "user_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "userPassword", column = "user_password", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "email", column = "email", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "phone", column = "phone", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "userType", column = "user_type", typeHandler = EnumOrdinalTypeHandler.class, javaType = UserType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "tenantId", column = "tenant_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "createTime", column = "create_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "updateTime", column = "update_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE) + }) + @SelectProvider(type = UserAlertGroupMapperProvider.class, method = "queryForUser") + List queryForUser(@Param("alertgroupId") int alertgroupId); + + + /** + * delete by alert group id + * @param alertgroupId + * @return + */ + @DeleteProvider(type = UserAlertGroupMapperProvider.class, method = "deleteByAlertgroupId") + int deleteByAlertgroupId(@Param("alertgroupId") int alertgroupId); + + /** + * list user information by alert group id + * + * @param alertgroupId + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "userName", column = "user_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "userPassword", column = "user_password", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "email", column = "email", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "phone", column = "phone", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "userType", column = "user_type", typeHandler = EnumOrdinalTypeHandler.class, javaType = UserType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "tenantId", column = "tenant_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "createTime", column = "create_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "updateTime", column = "update_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + }) + @SelectProvider(type = UserAlertGroupMapperProvider.class, method = "listUserByAlertgroupId") + List listUserByAlertgroupId(@Param("alertgroupId") int alertgroupId); + +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/UserAlertGroupMapperProvider.java b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/UserAlertGroupMapperProvider.java new file mode 100644 index 0000000000..c9f917f6b1 --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/UserAlertGroupMapperProvider.java @@ -0,0 +1,97 @@ +/* + * 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.dao.mapper; + +import org.apache.ibatis.jdbc.SQL; + +import java.util.Map; + +/** + * user alert group mapper provider + */ +public class UserAlertGroupMapperProvider { + + private static final String TABLE_NAME = "t_escheduler_relation_user_alertgroup"; + + /** + * insert user alert grouExecutorService.p + * @param parameter + * @return + */ + public String insert(Map parameter) { + return new SQL() { + { + INSERT_INTO(TABLE_NAME); + VALUES("`alertgroup_id`", "#{userAlertGroup.alertgroupId}"); + VALUES("`user_id`", "#{userAlertGroup.userId}"); + VALUES("`create_time`", "#{userAlertGroup.createTime}"); + VALUES("`update_time`", "#{userAlertGroup.updateTime}"); + + } + }.toString(); + } + + /** + * query user list by alert group id + * + * @param parameter + * @return + */ + public String queryForUser(Map parameter) { + return new SQL() {{ + SELECT("u.*"); + + FROM(TABLE_NAME + " g_u"); + + JOIN("t_escheduler_user u on g_u.user_id = u.id"); + + WHERE("g_u.alertgroup_id = #{alertgroupId}"); + }}.toString(); + } + + /** + * delete by alert group id + * @param parameter + * @return + */ + public String deleteByAlertgroupId(Map parameter) { + return new SQL() {{ + DELETE_FROM(TABLE_NAME); + + WHERE("`alertgroup_id` = #{alertgroupId}"); + }}.toString(); + } + + /** + * list user information by alert group id + * + * @param parameter + * @return + */ + public String listUserByAlertgroupId(Map parameter) { + return new SQL() {{ + SELECT("u.*"); + + FROM(TABLE_NAME + " g_u"); + + JOIN("t_escheduler_user u on g_u.user_id = u.id"); + + WHERE("g_u.alertgroup_id = #{alertgroupId}"); + }}.toString(); + } + +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/UserMapper.java b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/UserMapper.java new file mode 100644 index 0000000000..d33fb9ebfb --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/UserMapper.java @@ -0,0 +1,225 @@ +/* + * 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.dao.mapper; + +import cn.escheduler.common.enums.UserType; +import cn.escheduler.dao.model.User; +import org.apache.ibatis.annotations.*; +import org.apache.ibatis.type.EnumOrdinalTypeHandler; +import org.apache.ibatis.type.JdbcType; + +import java.sql.Timestamp; +import java.util.List; + +public interface UserMapper { + + /** + * insert user + * @param user + * @return + */ + @InsertProvider(type = UserMapperProvider.class, method = "insert") + @Options(useGeneratedKeys = true,keyProperty = "user.id") + @SelectKey(statement = "SELECT LAST_INSERT_ID()", keyProperty = "user.id", before = false, resultType = int.class) + int insert(@Param("user") User user); + + + /** + * delete user + * @param userId + * @return + */ + @DeleteProvider(type = UserMapperProvider.class, method = "delete") + int delete(@Param("userId") int userId); + + + /** + * update user + * + * @param user + * @return + */ + @UpdateProvider(type = UserMapperProvider.class, method = "update") + int update(@Param("user") User user); + + + /** + * query user by id + * @param userId + * @return + */ + @Results(value = { + @Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "userName", column = "user_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "userPassword", column = "user_password", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "email", column = "email", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "phone", column = "phone", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "userType", column = "user_type", typeHandler = EnumOrdinalTypeHandler.class, javaType = UserType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "tenantId", column = "tenant_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "createTime", column = "create_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "updateTime", column = "update_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE) + }) + @SelectProvider(type = UserMapperProvider.class, method = "queryById") + User queryById(@Param("userId") int userId); + + /** + * query all user list + * @return + */ + @Results(value = { + @Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "userName", column = "user_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "userPassword", column = "user_password", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "email", column = "email", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "phone", column = "phone", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "userType", column = "user_type", typeHandler = EnumOrdinalTypeHandler.class, javaType = UserType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "tenantId", column = "tenant_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "createTime", column = "create_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "updateTime", column = "update_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE) + }) + @SelectProvider(type = UserMapperProvider.class, method = "queryAllUsers") + List queryAllUsers(); + + + /** + * check user name and password + * @param userName + * @param userPassword + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "userName", column = "user_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "userPassword", column = "user_password", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "email", column = "email", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "phone", column = "phone", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "userType", column = "user_type", typeHandler = EnumOrdinalTypeHandler.class, javaType = UserType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "tenantId", column = "tenant_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "createTime", column = "create_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "updateTime", column = "update_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE) + }) + @SelectProvider(type = UserMapperProvider.class, method = "queryForCheck") + User queryForCheck(@Param("userName") String userName, @Param("userPassword") String userPassword); + + + /** + * query user by name + * @param userName + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "userName", column = "user_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "userPassword", column = "user_password", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "email", column = "email", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "phone", column = "phone", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "userType", column = "user_type", typeHandler = EnumOrdinalTypeHandler.class, javaType = UserType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "tenantId", column = "tenant_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "createTime", column = "create_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "updateTime", column = "update_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE) + }) + @SelectProvider(type = UserMapperProvider.class, method = "queryByUserName") + User queryByUserName(@Param("userName") String userName); + + /** + * count user by search value + * @param searchVal + * @return + */ + @SelectProvider(type = UserMapperProvider.class, method = "countUserPaging") + Integer countUserPaging(@Param("searchVal") String searchVal); + + + /** + * query user list paging + * @param searchVal + * @param offset + * @param pageSize + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "userName", column = "user_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "userPassword", column = "user_password", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "email", column = "email", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "phone", column = "phone", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "userType", column = "user_type", typeHandler = EnumOrdinalTypeHandler.class, javaType = UserType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "tenantId", column = "tenant_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "createTime", column = "create_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "updateTime", column = "update_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE) + }) + @SelectProvider(type = UserMapperProvider.class, method = "queryUserPaging") + List queryUserPaging(@Param("searchVal") String searchVal, + @Param("offset") Integer offset, + @Param("pageSize") Integer pageSize); + + /** + * query detail by user id + * @param id + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "userName", column = "user_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "userPassword", column = "user_password", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "email", column = "email", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "phone", column = "phone", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "userType", column = "user_type", typeHandler = EnumOrdinalTypeHandler.class, javaType = UserType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "tenantId", column = "tenant_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "tenantName", column = "tenant_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "queueName", column = "queue_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "createTime", column = "create_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "updateTime", column = "update_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE) + }) + @SelectProvider(type = UserMapperProvider.class, method = "queryDetailsById") + User queryDetailsById(@Param("id") int id); + + + /** + * 根据用户id查询已经授权的告警组 + * @param alertgroupId + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "userName", column = "user_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "userPassword", column = "user_password", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "email", column = "email", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "phone", column = "phone", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "userType", column = "user_type", typeHandler = EnumOrdinalTypeHandler.class, javaType = UserType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "tenantId", column = "tenant_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "createTime", column = "create_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "updateTime", column = "update_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE) + }) + @SelectProvider(type = UserMapperProvider.class, method = "queryUserListByAlertGroupId") + List queryUserListByAlertGroupId(@Param("alertgroupId") int alertgroupId); + + + /** + * query tenant code by user id + * @param userId + * @return + */ + @Results(value = {@Result(property = "id", column = "id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "userName", column = "user_name", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "userPassword", column = "user_password", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "email", column = "email", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "phone", column = "phone", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "userType", column = "user_type", typeHandler = EnumOrdinalTypeHandler.class, javaType = UserType.class, jdbcType = JdbcType.TINYINT), + @Result(property = "tenantId", column = "tenant_id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "tenantCode", column = "tenant_code", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "createTime", column = "create_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE), + @Result(property = "updateTime", column = "update_time", javaType = Timestamp.class, jdbcType = JdbcType.DATE) + }) + @SelectProvider(type = UserMapperProvider.class, method = "queryTenantCodeByUserId") + User queryTenantCodeByUserId(@Param("userId") int userId); +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/UserMapperProvider.java b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/UserMapperProvider.java new file mode 100644 index 0000000000..d1cfc34ad9 --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/UserMapperProvider.java @@ -0,0 +1,250 @@ +/* + * 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.dao.mapper; + +import cn.escheduler.common.enums.UserType; +import cn.escheduler.common.utils.EnumFieldUtil; +import org.apache.commons.lang3.StringUtils; +import org.apache.ibatis.jdbc.SQL; + +import java.util.Map; + +/** + * und function mapper provider + * + */ +public class UserMapperProvider { + + private static final String TABLE_NAME = "t_escheduler_user"; + + /** + * insert user + * + * @param parameter + * @return + */ + public String insert(Map parameter) { + return new SQL() { + { + INSERT_INTO(TABLE_NAME); + VALUES("`user_name`", "#{user.userName}"); + VALUES("`user_password`", "#{user.userPassword}"); + VALUES("`email`", "#{user.email}"); + VALUES("`phone`", "#{user.phone}"); + VALUES("`user_type`", EnumFieldUtil.genFieldStr("user.userType", UserType.class)); + VALUES("`tenant_id`", "#{user.tenantId}"); + VALUES("`create_time`", "#{user.createTime}"); + VALUES("`update_time`", "#{user.updateTime}"); + } + }.toString(); + } + + /** + * delete user + * + * @param parameter + * @return + */ + public String delete(Map parameter) { + return new SQL() { + { + DELETE_FROM(TABLE_NAME); + + WHERE("`id`=#{userId}"); + } + }.toString(); + } + + /** + * update user + * + * @param parameter + * @return + */ + public String update(Map parameter) { + return new SQL() { + { + UPDATE(TABLE_NAME); + + SET("`user_name`=#{user.userName}"); + SET("`user_password`=#{user.userPassword}"); + SET("`email`=#{user.email}"); + SET("`phone`=#{user.phone}"); + SET("`user_type`="+EnumFieldUtil.genFieldStr("user.userType", UserType.class)); + SET("`tenant_id`=#{user.tenantId}"); + SET("`create_time`=#{user.createTime}"); + SET("`update_time`=#{user.updateTime}"); + + WHERE("`id`=#{user.id}"); + } + }.toString(); + } + + /** + * query user by id + * @param parameter + * @return + */ + public String queryById(Map parameter) { + return new SQL() { + { + SELECT("*"); + + FROM(TABLE_NAME); + + WHERE("`id` = #{userId}"); + } + }.toString(); + } + + /** + * query all user list + * + * @return + */ + public String queryAllUsers() { + return new SQL() { + { + SELECT("*"); + + FROM(TABLE_NAME); + + WHERE("user_type = 1"); + } + }.toString(); + } + + /** + * check user name and password + * + * @param parameter + * @return + */ + public String queryForCheck(Map parameter) { + return new SQL() { + { + SELECT("*"); + FROM(TABLE_NAME); + WHERE("`user_name` = #{userName} AND `user_password` = #{userPassword}"); + } + }.toString(); + } + + /** + * query user by name + * + * @param parameter + * @return + */ + public String queryByUserName(Map parameter) { + return new SQL() { + { + SELECT("*"); + FROM(TABLE_NAME); + WHERE("`user_name` = #{userName}"); + } + }.toString(); + } + + /** + * count user number by search value + * @param parameter + * @return + */ + public String countUserPaging(Map parameter) { + return new SQL() {{ + SELECT("count(0)"); + FROM(TABLE_NAME); + WHERE("user_type = 1"); + Object searchVal = parameter.get("searchVal"); + if(searchVal != null && StringUtils.isNotEmpty(searchVal.toString())){ + WHERE( " user_name like concat('%', #{searchVal}, '%') "); + } + }}.toString(); + } + + /** + * query user list paging + * @param parameter + * @return + */ + public String queryUserPaging(Map parameter) { + return new SQL() { + { + SELECT("u.*,t.tenant_name as tenantName,q.queue_name as queueName"); + FROM(TABLE_NAME +" u,t_escheduler_tenant t,t_escheduler_queue q"); + WHERE("u.user_type = 1 AND u.tenant_id = t.id and t.queue_id = q.id"); + Object searchVal = parameter.get("searchVal"); + if(searchVal != null && StringUtils.isNotEmpty(searchVal.toString())){ + WHERE( " u.user_name like concat('%', #{searchVal}, '%') "); + } + ORDER_BY(" u.update_time desc limit #{offset},#{pageSize} "); + } + }.toString(); + + } + + /** + * query detail by user id + * @param parameter + * @return + */ + public String queryDetailsById(Map parameter) { + return new SQL() { + { + SELECT("u.*,q.queue_name as queueName,t.tenant_name as tenantName"); + + FROM(TABLE_NAME + " u,t_escheduler_tenant t,t_escheduler_queue q"); + + WHERE("u.tenant_id = t.id and t.queue_id = q.id and u.id = #{id}"); + } + }.toString(); + } + + + /** + * query user list by alert group id + * @param parameter + * @return + */ + public String queryUserListByAlertGroupId(Map parameter) { + return new SQL() { + { + SELECT("u.*"); + FROM(TABLE_NAME + " u,t_escheduler_relation_user_alertgroup rel"); + WHERE("u.id = rel.user_id AND u.user_type = 1 AND rel.alertgroup_id = #{alertgroupId}"); + } + }.toString(); + } + + + /** + * query tenant code by user id + * @param parameter + * @return + */ + public String queryTenantCodeByUserId(Map parameter) { + return new SQL() { + { + SELECT("u.*,t.tenant_code as tenantCode"); + FROM(TABLE_NAME + " u,t_escheduler_tenant t"); + WHERE("u.tenant_id = t.id AND u.id = #{userId}"); + } + }.toString(); + } + +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/WorkerServerMapper.java b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/WorkerServerMapper.java new file mode 100644 index 0000000000..b5ea3aa878 --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/WorkerServerMapper.java @@ -0,0 +1,74 @@ +/* + * 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.dao.mapper; + +import cn.escheduler.dao.model.WorkerServer; +import org.apache.ibatis.annotations.*; +import org.apache.ibatis.type.JdbcType; + +import java.util.Date; +import java.util.List; + +public interface WorkerServerMapper { + + /** + * query worker list + * + * @return + */ + @Results(value = { + @Result(property = "id", column = "id", javaType = Integer.class, jdbcType = JdbcType.INTEGER), + @Result(property = "host", column = "host", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "port", column = "port", javaType = int.class, jdbcType = JdbcType.INTEGER), + @Result(property = "zkDirectory", column = "zk_directory", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "resInfo", column = "res_info", javaType = String.class, jdbcType = JdbcType.VARCHAR), + @Result(property = "createTime", column = "create_time", javaType = Date.class, jdbcType = JdbcType.TIMESTAMP), + @Result(property = "lastHeartbeatTime", column = "last_heartbeat_time", javaType = Date.class, jdbcType = JdbcType.TIMESTAMP) + }) + @SelectProvider(type = WorkerServerMapperProvider.class, method = "queryAllWorker") + List queryAllWorker(); + + /** + * insert worker server + * + * @param workerServer + * @return + */ + @InsertProvider(type = WorkerServerMapperProvider.class, method = "insert") + int insert(@Param("workerServer") WorkerServer workerServer); + + /** + * update worker + * + * @param workerServer + * @return + */ + @UpdateProvider(type = WorkerServerMapperProvider.class, method = "update") + int update(@Param("workerServer") WorkerServer workerServer); + + /** + * delete work by host + * @param host + * @return + */ + @DeleteProvider(type = WorkerServerMapperProvider.class, method = "deleteWorkerByHost") + int deleteWorkerByHost(@Param("host") String host); + + + + +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/WorkerServerMapperProvider.java b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/WorkerServerMapperProvider.java new file mode 100644 index 0000000000..bd5af7deda --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/mapper/WorkerServerMapperProvider.java @@ -0,0 +1,90 @@ +/* + * 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.dao.mapper; + + +import org.apache.ibatis.jdbc.SQL; + +import java.util.Map; + +public class WorkerServerMapperProvider { + + private static final String TABLE_NAME = "t_escheduler_worker_server"; + + /** + * query worker list + * @return + */ + public String queryAllWorker() { + return new SQL() {{ + SELECT("*"); + + FROM(TABLE_NAME); + }}.toString(); + } + + /** + * insert worker server + * @param parameter + * @return + */ + public String insert(Map parameter) { + return new SQL() {{ + INSERT_INTO(TABLE_NAME); + + VALUES("host", "#{workerServer.host}"); + VALUES("port", "#{workerServer.port}"); + VALUES("zk_directory", "#{workerServer.zkDirectory}"); + VALUES("res_info", "#{workerServer.resInfo}"); + VALUES("create_time", "#{workerServer.createTime}"); + VALUES("last_heartbeat_time", "#{workerServer.lastHeartbeatTime}"); + }}.toString(); + } + + /** + * update worker + * + * @param parameter + * @return + */ + public String update(Map parameter) { + return new SQL() {{ + UPDATE(TABLE_NAME); + + SET("last_heartbeat_time = #{workerServer.lastHeartbeatTime}"); + SET("port = #{workerServer.port}"); + SET("res_info = #{workerServer.resInfo}"); + + WHERE("host = #{workerServer.host}"); + }}.toString(); + } + + /** + * delete work by host + * @param parameter + * @return + */ + public String deleteWorkerByHost(Map parameter) { + return new SQL() {{ + DELETE_FROM(TABLE_NAME); + + WHERE("host = #{host}"); + }}.toString(); + } + + +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/model/Alert.java b/escheduler-dao/src/main/java/cn/escheduler/dao/model/Alert.java new file mode 100644 index 0000000000..57bcf60ecd --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/model/Alert.java @@ -0,0 +1,228 @@ +/* + * 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.dao.model; + +import cn.escheduler.common.enums.AlertStatus; +import cn.escheduler.common.enums.AlertType; +import cn.escheduler.common.enums.ShowType; + +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +/** + * alert + */ +public class Alert { + + /** + * id + */ + private int id; + + /** + * title + */ + private String title; + + /** + * show type + */ + private ShowType showType; + /** + * content + */ + private String content; + + /** + * alert type + */ + private AlertType alertType; + + + + /** + * alert status + */ + private AlertStatus alertStatus; + + /** + * log + */ + private String log; + + /** + * alert group id + */ + private int alertGroupId; + + + /** + * receivers + */ + private String receivers; + + /** + * receivers cc + */ + private String receiversCc; + + /** + * create time + */ + private Date createTime; + + /** + * update time + */ + private Date updateTime; + + + private Map info = new HashMap<>(); + + public Map getInfo() { + return info; + } + + public void setInfo(Map info) { + this.info = info; + } + + public Alert() { + } + + public Alert(int id,String title) { + this.id = id; + this.title = title; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public ShowType getShowType() { + return showType; + } + + public void setShowType(ShowType showType) { + this.showType = showType; + } + + public String getContent() { + return content; + } + + public void setContent(String content) { + this.content = content; + } + + public AlertType getAlertType() { + return alertType; + } + + public void setAlertType(AlertType alertType) { + this.alertType = alertType; + } + + + public AlertStatus getAlertStatus() { + return alertStatus; + } + + public void setAlertStatus(AlertStatus alertStatus) { + this.alertStatus = alertStatus; + } + + public String getLog() { + return log; + } + + public void setLog(String log) { + this.log = log; + } + + public int getAlertGroupId() { + return alertGroupId; + } + + public void setAlertGroupId(int alertGroupId) { + this.alertGroupId = alertGroupId; + } + + public Date getCreateTime() { + return createTime; + } + + public String getReceivers() { + return receivers; + } + + public void setReceivers(String receivers) { + this.receivers = receivers; + } + + public String getReceiversCc() { + return receiversCc; + } + + public void setReceiversCc(String receiversCc) { + this.receiversCc = receiversCc; + } + + public void setCreateTime(Date createTime) { + this.createTime = createTime; + } + + public Date getUpdateTime() { + return updateTime; + } + + public void setUpdateTime(Date updateTime) { + this.updateTime = updateTime; + } + + @Override + public String toString() { + return "Alert{" + + "id=" + id + + ", title='" + title + '\'' + + ", showType=" + showType + + ", content='" + content + '\'' + + ", alertType=" + alertType + + ", alertStatus=" + alertStatus + + ", log='" + log + '\'' + + ", alertGroupId=" + alertGroupId + + ", createTime=" + createTime + + ", updateTime=" + updateTime + + ", receivers='" + receivers + '\'' + + ", receiversCc='" + receiversCc + '\'' + + ", info=" + info + + '}'; + } +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/model/AlertGroup.java b/escheduler-dao/src/main/java/cn/escheduler/dao/model/AlertGroup.java new file mode 100644 index 0000000000..21b24843cb --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/model/AlertGroup.java @@ -0,0 +1,115 @@ +/* + * 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.dao.model; + +import cn.escheduler.common.enums.AlertType; + +import java.util.Date; + +/** + * alert group + */ +public class AlertGroup { + /** + * primary key + */ + private int id; + + /** + * alert group name + */ + private String groupName; + /** + * alert group type + */ + private AlertType groupType; + + /** + * alert group description + */ + private String desc; + + /** + * create time + */ + private Date createTime; + + /** + * update time + */ + private Date updateTime; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getGroupName() { + return groupName; + } + + public void setGroupName(String groupName) { + this.groupName = groupName; + } + + public AlertType getGroupType() { + return groupType; + } + + public void setGroupType(AlertType groupType) { + this.groupType = groupType; + } + + public String getDesc() { + return desc; + } + + public void setDesc(String desc) { + this.desc = desc; + } + + public Date getCreateTime() { + return createTime; + } + + public void setCreateTime(Date createTime) { + this.createTime = createTime; + } + + public Date getUpdateTime() { + return updateTime; + } + + public void setUpdateTime(Date updateTime) { + this.updateTime = updateTime; + } + + @Override + public String toString() { + return "AlertGroup{" + + "id=" + id + + ", groupName='" + groupName + '\'' + + ", groupType=" + groupType + + ", desc='" + desc + '\'' + + ", createTime=" + createTime + + ", updateTime=" + updateTime + + '}'; + } +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/model/Command.java b/escheduler-dao/src/main/java/cn/escheduler/dao/model/Command.java new file mode 100644 index 0000000000..399e378ae8 --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/model/Command.java @@ -0,0 +1,250 @@ +/* + * 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.dao.model; + +import cn.escheduler.common.enums.*; + +import java.util.Date; + +/** + * command + */ +public class Command { + + /** + * id + */ + private int id; + + /** + * command type + */ + private CommandType commandType; + + /** + * process definition id + */ + private int processDefinitionId; + + /** + * executor id + */ + private int executorId; + + /** + * command parameter, format json + */ + private String commandParam; + + /** + * task depend type + */ + private TaskDependType taskDependType; + + /** + * failure strategy + */ + private FailureStrategy failureStrategy; + + /** + * warning type + */ + private WarningType warningType; + + /** + * warning group id + */ + private Integer warningGroupId; + + /** + * schedule time + */ + private Date scheduleTime; + + /** + * start time + */ + private Date startTime; + + /** + * process instance priority + */ + private Priority processInstancePriority; + + /** + * update time + */ + private Date updateTime; + + + public Command(){ + this.taskDependType = TaskDependType.TASK_POST; + this.failureStrategy = FailureStrategy.CONTINUE; + this.startTime = new Date(); + this.updateTime = new Date(); + } + + public Command( + CommandType commandType, + TaskDependType taskDependType, + FailureStrategy failureStrategy, + int executorId, + int processDefinitionId, + String commandParam, + WarningType warningType, + int warningGroupId, + Date scheduleTime, + Priority processInstancePriority){ + this.commandType = commandType; + this.executorId = executorId; + this.processDefinitionId = processDefinitionId; + this.commandParam = commandParam; + this.warningType = warningType; + this.warningGroupId = warningGroupId; + this.scheduleTime = scheduleTime; + this.taskDependType = taskDependType; + this.failureStrategy = failureStrategy; + this.startTime = new Date(); + this.updateTime = new Date(); + this.processInstancePriority = processInstancePriority; + } + + + public TaskDependType getTaskDependType() { + return taskDependType; + } + + public void setTaskDependType(TaskDependType taskDependType) { + this.taskDependType = taskDependType; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public CommandType getCommandType() { + return commandType; + } + + public void setCommandType(CommandType commandType) { + this.commandType = commandType; + } + + public int getProcessDefinitionId() { + return processDefinitionId; + } + + public void setProcessDefinitionId(int processDefinitionId) { + this.processDefinitionId = processDefinitionId; + } + + + public FailureStrategy getFailureStrategy() { + return failureStrategy; + } + + public void setFailureStrategy(FailureStrategy failureStrategy) { + this.failureStrategy = failureStrategy; + } + + public void setCommandParam(String commandParam) { + this.commandParam = commandParam; + } + + public String getCommandParam() { + return commandParam; + } + + public WarningType getWarningType() { + return warningType; + } + + public void setWarningType(WarningType warningType) { + this.warningType = warningType; + } + + public Integer getWarningGroupId() { + return warningGroupId; + } + + public void setWarningGroupId(Integer warningGroupId) { + this.warningGroupId = warningGroupId; + } + + public Date getScheduleTime() { + return scheduleTime; + } + + public void setScheduleTime(Date scheduleTime) { + this.scheduleTime = scheduleTime; + } + + public Date getStartTime() { + return startTime; + } + + public void setStartTime(Date startTime) { + this.startTime = startTime; + } + + public int getExecutorId() { + return executorId; + } + + public void setExecutorId(int executorId) { + this.executorId = executorId; + } + + public Priority getProcessInstancePriority() { + return processInstancePriority; + } + + public void setProcessInstancePriority(Priority processInstancePriority) { + this.processInstancePriority = processInstancePriority; + } + + public Date getUpdateTime() { + return updateTime; + } + + public void setUpdateTime(Date updateTime) { + this.updateTime = updateTime; + } + + @Override + public String toString() { + return "Command{" + + "id=" + id + + ", commandType=" + commandType + + ", processDefinitionId=" + processDefinitionId + + ", executorId=" + executorId + + ", commandParam='" + commandParam + '\'' + + ", taskDependType=" + taskDependType + + ", failureStrategy=" + failureStrategy + + ", warningType=" + warningType + + ", warningGroupId=" + warningGroupId + + ", scheduleTime=" + scheduleTime + + ", startTime=" + startTime + + ", processInstancePriority=" + processInstancePriority + + ", updateTime=" + updateTime + + '}'; + } +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/model/CycleDependency.java b/escheduler-dao/src/main/java/cn/escheduler/dao/model/CycleDependency.java new file mode 100644 index 0000000000..97b1297af3 --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/model/CycleDependency.java @@ -0,0 +1,93 @@ +/* + * 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.dao.model; + +import cn.escheduler.common.enums.CycleEnum; + +import java.util.Date; + +/** + * cycle dependency + */ +public class CycleDependency { + /** + * process define id + */ + private int processDefineId; + /** + * last schedule time + */ + private Date lastScheduleTime; + /** + * expiration time + */ + private Date expirationTime; + /** + * cycle enum + */ + private CycleEnum cycleEnum; + + + public CycleDependency(int processDefineId, Date lastScheduleTime, Date expirationTime, CycleEnum cycleEnum) { + this.processDefineId = processDefineId; + this.lastScheduleTime = lastScheduleTime; + this.expirationTime = expirationTime; + this.cycleEnum = cycleEnum; + } + + public int getProcessDefineId() { + return processDefineId; + } + + public void setProcessDefineId(int processDefineId) { + this.processDefineId = processDefineId; + } + + public Date getLastScheduleTime() { + return lastScheduleTime; + } + + public void setLastScheduleTime(Date lastScheduleTime) { + this.lastScheduleTime = lastScheduleTime; + } + + public Date getExpirationTime() { + return expirationTime; + } + + public void setExpirationTime(Date expirationTime) { + this.expirationTime = expirationTime; + } + + public CycleEnum getCycleEnum() { + return cycleEnum; + } + + public void setCycleEnum(CycleEnum cycleEnum) { + this.cycleEnum = cycleEnum; + } + + @Override + public String toString() { + return "CycleDependency{" + + "processDefineId=" + processDefineId + + ", lastScheduleTime=" + lastScheduleTime + + ", expirationTime=" + expirationTime + + ", cycleEnum=" + cycleEnum + + '}'; + } +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/model/DataSource.java b/escheduler-dao/src/main/java/cn/escheduler/dao/model/DataSource.java new file mode 100644 index 0000000000..9506cd2f70 --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/model/DataSource.java @@ -0,0 +1,186 @@ +/* + * 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.dao.model; + + +import cn.escheduler.common.enums.DbType; + +import java.util.Date; + +public class DataSource { + /** + * id + */ + private int id; + + /** + * user id + */ + private int userId; + + /** + * user name + */ + private String userName; + + /** + * data source name + */ + private String name; + + /** + * note + */ + private String note; + + /** + * data source type + */ + private DbType type; + + /** + * connection parameters + */ + private String connectionParams; + + /** + * create time + */ + private Date createTime; + + /** + * update time + */ + private Date updateTime; + + public DataSource() { + } + + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public int getUserId() { + return userId; + } + + public void setUserId(int userId) { + this.userId = userId; + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getNote() { + return note; + } + + public void setNote(String note) { + this.note = note; + } + + public DbType getType() { + return type; + } + + public void setType(DbType type) { + this.type = type; + } + + public String getConnectionParams() { + return connectionParams; + } + + public void setConnectionParams(String connectionParams) { + this.connectionParams = connectionParams; + } + + public Date getCreateTime() { + return createTime; + } + + public void setCreateTime(Date createTime) { + this.createTime = createTime; + } + + public Date getUpdateTime() { + return updateTime; + } + + public void setUpdateTime(Date updateTime) { + this.updateTime = updateTime; + } + + + @Override + public String toString() { + return "DataSource{" + + "id=" + id + + ", userId=" + userId + + ", userName='" + userName + '\'' + + ", name='" + name + '\'' + + ", note='" + note + '\'' + + ", type=" + type + + ", connectionParams='" + connectionParams + '\'' + + ", createTime=" + createTime + + ", updateTime=" + updateTime + + '}'; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + DataSource that = (DataSource) o; + + if (id != that.id) { + return false; + } + return name.equals(that.name); + + } + + @Override + public int hashCode() { + int result = id; + result = 31 * result + name.hashCode(); + return result; + } +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/model/DatasourceUser.java b/escheduler-dao/src/main/java/cn/escheduler/dao/model/DatasourceUser.java new file mode 100644 index 0000000000..58d936f02f --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/model/DatasourceUser.java @@ -0,0 +1,115 @@ +/* + * 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.dao.model; + +import java.util.Date; + +/** + * data source user relation + */ +public class DatasourceUser { + + /** + * id + */ + private int id; + + /** + * user id + */ + private int userId; + + /** + * data source id + */ + private int datasourceId; + + /** + * permission + */ + private int perm; + /** + * create time + */ + private Date createTime; + + /** + * update time + */ + private Date updateTime; + + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public int getUserId() { + return userId; + } + + public void setUserId(int userId) { + this.userId = userId; + } + + public int getDatasourceId() { + return datasourceId; + } + + public void setDatasourceId(int datasourceId) { + this.datasourceId = datasourceId; + } + + public int getPerm() { + return perm; + } + + public void setPerm(int perm) { + this.perm = perm; + } + + public Date getCreateTime() { + return createTime; + } + + public void setCreateTime(Date createTime) { + this.createTime = createTime; + } + + public Date getUpdateTime() { + return updateTime; + } + + public void setUpdateTime(Date updateTime) { + this.updateTime = updateTime; + } + + @Override + public String toString() { + return "DatasourceUser{" + + "id=" + id + + ", userId=" + userId + + ", datasourceId=" + datasourceId + + ", perm=" + perm + + ", createTime=" + createTime + + ", updateTime=" + updateTime + + '}'; + } +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/model/DefinitionGroupByUser.java b/escheduler-dao/src/main/java/cn/escheduler/dao/model/DefinitionGroupByUser.java new file mode 100644 index 0000000000..b53462e27d --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/model/DefinitionGroupByUser.java @@ -0,0 +1,62 @@ +/* + * 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.dao.model; + +/** + * count definition number group by user + */ +public class DefinitionGroupByUser { + + /** + * user name + */ + private String userName; + + /** + * user id + */ + private Integer userId; + + /** + * count number + */ + private int count; + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public int getCount() { + return count; + } + + public void setCount(int count) { + this.count = count; + } + + public Integer getUserId() { + return userId; + } + + public void setUserId(Integer userId) { + this.userId = userId; + } +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/model/Dependency.java b/escheduler-dao/src/main/java/cn/escheduler/dao/model/Dependency.java new file mode 100644 index 0000000000..30b1a9f79d --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/model/Dependency.java @@ -0,0 +1,62 @@ +/* + * 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.dao.model; + +import cn.escheduler.common.enums.SelfDependStrategy; + +/** + * dependency + */ +public class Dependency { + + /** + * self depend strategy + */ + private SelfDependStrategy self; + + /** + * outer dependency string + */ + private String outer; + + + public Dependency(){} + + public Dependency(String outer, SelfDependStrategy self){ + + this.outer = outer; + this.self = self; + + } + + + public SelfDependStrategy getSelf() { + return self; + } + + public void setSelf(SelfDependStrategy self) { + this.self = self; + } + + public String getOuter() { + return outer; + } + + public void setOuter(String outer) { + this.outer = outer; + } +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/model/ExecuteStatusCount.java b/escheduler-dao/src/main/java/cn/escheduler/dao/model/ExecuteStatusCount.java new file mode 100644 index 0000000000..e85af98bbb --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/model/ExecuteStatusCount.java @@ -0,0 +1,53 @@ +/* + * 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.dao.model; + + +import cn.escheduler.common.enums.ExecutionStatus; + +/** + * count execute state + * + */ +public class ExecuteStatusCount { + + /** + * execution state + */ + private ExecutionStatus state; + + /** + * count for state + */ + private int count; + + public ExecutionStatus getExecutionStatus() { + return state; + } + + public void setExecutionStatus(ExecutionStatus executionStatus) { + this.state = executionStatus; + } + + public int getCount() { + return count; + } + + public void setCount(int count) { + this.count = count; + } +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/model/MasterServer.java b/escheduler-dao/src/main/java/cn/escheduler/dao/model/MasterServer.java new file mode 100644 index 0000000000..1ccb15b5cc --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/model/MasterServer.java @@ -0,0 +1,130 @@ +/* + * 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.dao.model; + + +import java.util.Date; + +/** + * master server + */ +public class MasterServer { + + /** + * id + */ + private int id; + + /** + * host + */ + private String host; + + /** + * port + */ + private int port; + + /** + * master direcotry in zookeeper + */ + private String zkDirectory; + + /** + * resource info: CPU and memory + */ + private String resInfo; + + /** + * create time + */ + private Date createTime; + + /** + * laster heart beat time + */ + private Date lastHeartbeatTime; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getHost() { + return host; + } + + public void setHost(String host) { + this.host = host; + } + + public int getPort() { + return port; + } + + public void setPort(int port) { + this.port = port; + } + + public Date getCreateTime() { + return createTime; + } + + public void setCreateTime(Date createTime) { + this.createTime = createTime; + } + + public String getZkDirectory() { + return zkDirectory; + } + + public void setZkDirectory(String zkDirectory) { + this.zkDirectory = zkDirectory; + } + + public Date getLastHeartbeatTime() { + return lastHeartbeatTime; + } + + public void setLastHeartbeatTime(Date lastHeartbeatTime) { + this.lastHeartbeatTime = lastHeartbeatTime; + } + + public String getResInfo() { + return resInfo; + } + + public void setResInfo(String resInfo) { + this.resInfo = resInfo; + } + + @Override + public String toString() { + return "MasterServer{" + + "id=" + id + + ", host='" + host + '\'' + + ", port=" + port + + ", zkDirectory='" + zkDirectory + '\'' + + ", resInfo='" + resInfo + '\'' + + ", createTime=" + createTime + + ", lastHeartbeatTime=" + lastHeartbeatTime + + '}'; + } +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/model/ProcessData.java b/escheduler-dao/src/main/java/cn/escheduler/dao/model/ProcessData.java new file mode 100644 index 0000000000..ba967f8be4 --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/model/ProcessData.java @@ -0,0 +1,85 @@ +/* + * 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.dao.model; + +import cn.escheduler.common.model.TaskNode; +import cn.escheduler.common.process.Property; +import cn.escheduler.common.utils.CollectionUtils; + +import java.util.List; + +/** + * definition json data structure + */ +public class ProcessData { + /** + * task list + */ + private List tasks; + + /** + * global parameters + */ + private List globalParams; + + + public ProcessData() { + } + + /** + * + * @param tasks + * @param globalParams + */ + public ProcessData(List tasks, List globalParams) { + this.tasks = tasks; + this.globalParams = globalParams; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + + if (o == null || getClass() != o.getClass()) { + return false; + } + + ProcessData that = (ProcessData) o; + + return CollectionUtils.equalLists(tasks, that.tasks) && + CollectionUtils.equalLists(globalParams, that.globalParams); + } + + public List getTasks() { + return tasks; + } + + public void setTasks(List tasks) { + this.tasks = tasks; + } + + public List getGlobalParams() { + return globalParams; + } + + public void setGlobalParams(List globalParams) { + this.globalParams = globalParams; + } + +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/model/ProcessDefinition.java b/escheduler-dao/src/main/java/cn/escheduler/dao/model/ProcessDefinition.java new file mode 100644 index 0000000000..51498f5ddf --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/model/ProcessDefinition.java @@ -0,0 +1,345 @@ +/* + * 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.dao.model; + +import cn.escheduler.common.enums.Flag; +import cn.escheduler.common.enums.ReleaseState; +import cn.escheduler.common.process.Property; +import com.alibaba.fastjson.JSONObject; +import org.apache.commons.lang3.StringUtils; + +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * process definition + */ +public class ProcessDefinition { + /** + * id + */ + private int id; + + /** + * name + */ + private String name; + + /** + * version + */ + private int version; + + /** + * release state : online/offline + */ + private ReleaseState releaseState; + + /** + * project id + */ + private int projectId; + + /** + * definition json string + */ + private String processDefinitionJson; + + /** + * description + */ + private String desc; + + /** + * user defined parameters + */ + private String globalParams; + + /** + * user defined parameter list + */ + private List globalParamList; + + /** + * user define parameter map + */ + private Map globalParamMap; + + /** + * create time + */ + private Date createTime; + + /** + * update time + */ + private Date updateTime; + + /** + * process is valid: yes/no + */ + private Flag flag; + + /** + * process user id + */ + private int userId; + + /** + * user name + */ + private String userName; + + /** + * project name + */ + private String projectName; + + /** + * locations array for web + */ + private String locations; + + /** + * connects array for web + */ + private String connects; + + /** + * receivers + */ + private String receivers; + + /** + * receivers cc + */ + private String receiversCc; + + /** + * schedule release state : online/offline + */ + private ReleaseState scheduleReleaseState; + + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getVersion() { + return version; + } + + public void setVersion(int version) { + this.version = version; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public ReleaseState getReleaseState() { + return releaseState; + } + + public void setReleaseState(ReleaseState releaseState) { + this.releaseState = releaseState; + } + + public String getProcessDefinitionJson() { + return processDefinitionJson; + } + + public void setProcessDefinitionJson(String processDefinitionJson) { + this.processDefinitionJson = processDefinitionJson; + } + + public Date getCreateTime() { + return createTime; + } + + public void setCreateTime(Date createTime) { + this.createTime = createTime; + } + + public int getProjectId() { + return projectId; + } + + public void setProjectId(int projectId) { + this.projectId = projectId; + } + + public Date getUpdateTime() { + return updateTime; + } + + public void setUpdateTime(Date updateTime) { + this.updateTime = updateTime; + } + + public Flag getFlag() { + return flag; + } + + public void setFlag(Flag flag) { + this.flag = flag; + } + + public int getUserId() { + return userId; + } + + public void setUserId(int userId) { + this.userId = userId; + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public String getProjectName() { + return projectName; + } + + public void setProjectName(String projectName) { + this.projectName = projectName; + } + + + public String getGlobalParams() { + return globalParams; + } + + public void setGlobalParams(String globalParams) { + this.globalParamList = JSONObject.parseArray(globalParams, Property.class); + this.globalParams = globalParams; + } + + public List getGlobalParamList() { + return globalParamList; + } + + public void setGlobalParamList(List globalParamList) { + this.globalParams = JSONObject.toJSONString(globalParamList); + this.globalParamList = globalParamList; + } + + public Map getGlobalParamMap() { + List propList; + + if (globalParamMap == null && StringUtils.isNotEmpty(globalParams)) { + propList = JSONObject.parseArray(globalParams, Property.class); + globalParamMap = propList.stream().collect(Collectors.toMap(Property::getProp, Property::getValue)); + } + + return globalParamMap; + } + + public void setGlobalParamMap(Map globalParamMap) { + this.globalParamMap = globalParamMap; + } + + + public String getDesc() { + return desc; + } + + public void setDesc(String desc) { + this.desc = desc; + } + + public String getLocations() { + return locations; + } + + public void setLocations(String locations) { + this.locations = locations; + } + + public String getConnects() { + return connects; + } + + public void setConnects(String connects) { + this.connects = connects; + } + + public String getReceivers() { + return receivers; + } + + public void setReceivers(String receivers) { + this.receivers = receivers; + } + + public String getReceiversCc() { + return receiversCc; + } + + public void setReceiversCc(String receiversCc) { + this.receiversCc = receiversCc; + } + + public ReleaseState getScheduleReleaseState() { + return scheduleReleaseState; + } + + public void setScheduleReleaseState(ReleaseState scheduleReleaseState) { + this.scheduleReleaseState = scheduleReleaseState; + } + + @Override + public String toString() { + return "ProcessDefinition{" + + "id=" + id + + ", name='" + name + '\'' + + ", version=" + version + + ", releaseState=" + releaseState + + ", projectId=" + projectId + + ", processDefinitionJson='" + processDefinitionJson + '\'' + + ", desc='" + desc + '\'' + + ", globalParams='" + globalParams + '\'' + + ", globalParamList=" + globalParamList + + ", globalParamMap=" + globalParamMap + + ", createTime=" + createTime + + ", updateTime=" + updateTime + + ", flag=" + flag + + ", userId=" + userId + + ", userName='" + userName + '\'' + + ", projectName='" + projectName + '\'' + + ", locations='" + locations + '\'' + + ", connects='" + connects + '\'' + + ", receivers='" + receivers + '\'' + + ", receiversCc='" + receiversCc + '\'' + + ", scheduleReleaseState=" + scheduleReleaseState + + '}'; + } +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/model/ProcessInstance.java b/escheduler-dao/src/main/java/cn/escheduler/dao/model/ProcessInstance.java new file mode 100644 index 0000000000..06656ebeba --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/model/ProcessInstance.java @@ -0,0 +1,521 @@ +/* + * 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.dao.model; + +import cn.escheduler.common.enums.*; +import org.apache.commons.lang3.StringUtils; + +import java.util.Date; + +/** + * process instance + */ +public class ProcessInstance { + + /** + * id + */ + private int id; + /** + * process definition id + */ + private int processDefinitionId; + /** + * process state + */ + private ExecutionStatus state; + /** + * recovery flag for failover + */ + private Flag recovery; + /** + * start time + */ + private Date startTime; + + /** + * end time + */ + private Date endTime; + + /** + * run time + */ + private int runTimes; + + /** + * name + */ + private String name; + + /** + * host + */ + private String host; + + /** + * process definition structure + */ + private ProcessDefinition processDefinition; + /** + * process command type + */ + private CommandType commandType; + + /** + * command parameters + */ + private String commandParam; + + /** + * node depend type + */ + private TaskDependType taskDependType; + + /** + * task max try times + */ + private int maxTryTimes; + + /** + * failure strategy when task failed. + */ + private FailureStrategy failureStrategy; + + /** + * warning type + */ + private WarningType warningType; + + /** + * warning group + */ + private Integer warningGroupId; + + /** + * schedule time + */ + private Date scheduleTime; + + /** + * command start time + */ + private Date commandStartTime; + + /** + * user define parameters string + */ + private String globalParams; + + /** + * process instance json + */ + private String processInstanceJson; + + /** + * executor id + */ + private int executorId; + + /** + * tenant code + */ + private String tenantCode; + + /** + * queue + */ + private String queue; + + /** + * process is sub process + */ + private Flag isSubProcess; + + /** + * task locations for web + */ + private String locations; + + /** + * task connects for web + */ + private String connects; + + /** + * history command + */ + private String historyCmd; + + /** + * depend processes schedule time + */ + private String dependenceScheduleTimes; + + /** + * process duration + * @return + */ + private Long duration; + + /** + * process instance priority + */ + private Priority processInstancePriority; + + public ProcessInstance(){ + + } + + /** + * set the process name with process define version and timestamp + * @param processDefinition + */ + public ProcessInstance(ProcessDefinition processDefinition){ + this.processDefinition = processDefinition; + this.name = processDefinition.getName() + "-" + + processDefinition.getVersion() + "-" + + System.currentTimeMillis(); + } + + public ProcessDefinition getProcessDefinition() { + return processDefinition; + } + + public void setProcessDefinition(ProcessDefinition processDefinition) { + this.processDefinition = processDefinition; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public int getProcessDefinitionId() { + return processDefinitionId; + } + + public void setProcessDefinitionId(int processDefinitionId) { + this.processDefinitionId = processDefinitionId; + } + + public ExecutionStatus getState() { + return state; + } + + public void setState(ExecutionStatus state) { + this.state = state; + } + + public Flag getRecovery() { + return recovery; + } + + public void setRecovery(Flag recovery) { + this.recovery = recovery; + } + + public Date getStartTime() { + return startTime; + } + + public void setStartTime(Date startTime) { + this.startTime = startTime; + } + + public Date getEndTime() { + return endTime; + } + + public void setEndTime(Date endTime) { + this.endTime = endTime; + } + + public int getRunTimes() { + return runTimes; + } + + public void setRunTimes(int runTimes) { + this.runTimes = runTimes; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + + public String getHost() { + return host; + } + + public void setHost(String host) { + this.host = host; + } + + + public CommandType getCommandType() { + return commandType; + } + + public void setCommandType(CommandType commandType) { + this.commandType = commandType; + } + + public String getCommandParam() { + return commandParam; + } + + public void setCommandParam(String commandParam) { + this.commandParam = commandParam; + } + + public TaskDependType getTaskDependType() { + return taskDependType; + } + + public void setTaskDependType(TaskDependType taskDependType) { + this.taskDependType = taskDependType; + } + + + public int getMaxTryTimes() { + return maxTryTimes; + } + + public void setMaxTryTimes(int maxTryTimes) { + this.maxTryTimes = maxTryTimes; + } + + public FailureStrategy getFailureStrategy() { + return failureStrategy; + } + + public void setFailureStrategy(FailureStrategy failureStrategy) { + this.failureStrategy = failureStrategy; + } + + + public boolean IsProcessInstanceStop(){ + return this.state.typeIsFinished(); + } + + public WarningType getWarningType() { + return warningType; + } + + public void setWarningType(WarningType warningType) { + this.warningType = warningType; + } + + public Integer getWarningGroupId() { + return warningGroupId; + } + + public void setWarningGroupId(Integer warningGroupId) { + this.warningGroupId = warningGroupId; + } + + public Date getScheduleTime() { + return scheduleTime; + } + + public void setScheduleTime(Date scheduleTime) { + this.scheduleTime = scheduleTime; + } + + public Date getCommandStartTime() { + return commandStartTime; + } + + public void setCommandStartTime(Date commandStartTime) { + this.commandStartTime = commandStartTime; + } + + public String getGlobalParams() { + return globalParams; + } + + public void setGlobalParams(String globalParams) { + this.globalParams = globalParams; + } + + public String getProcessInstanceJson() { + return processInstanceJson; + } + + public void setProcessInstanceJson(String processInstanceJson) { + this.processInstanceJson = processInstanceJson; + } + + public String getTenantCode() { + return tenantCode; + } + + public void setTenantCode(String tenantCode) { + this.tenantCode = tenantCode; + } + + public String getQueue() { + return queue; + } + + public void setQueue(String queue) { + this.queue = queue; + } + + public int getExecutorId() { + return executorId; + } + + public void setExecutorId(int executorId) { + this.executorId = executorId; + } + + + public Flag getIsSubProcess() { + return isSubProcess; + } + + public void setIsSubProcess(Flag isSubProcess) { + this.isSubProcess = isSubProcess; + } + + public Priority getProcessInstancePriority() { + return processInstancePriority; + } + + public void setProcessInstancePriority(Priority processInstancePriority) { + this.processInstancePriority = processInstancePriority; + } + public String getLocations() { + return locations; + } + + public void setLocations(String locations) { + this.locations = locations; + } + + public String getConnects() { + return connects; + } + + public void setConnects(String connects) { + this.connects = connects; + } + + public String getHistoryCmd() { + return historyCmd; + } + + public void setHistoryCmd(String historyCmd) { + this.historyCmd = historyCmd; + } + + /** + * add command to history + * @param cmd + */ + public void addHistoryCmd(CommandType cmd){ + if(StringUtils.isNotEmpty(this.historyCmd)){ + this.historyCmd = String.format("%s,%s", this.historyCmd, cmd.toString()); + }else{ + this.historyCmd = cmd.toString(); + } + } + + /** + * check this process is start complement data + */ + public Boolean isComplementData(){ + if(!StringUtils.isNotEmpty(this.historyCmd)){ + return false; + } + return historyCmd.startsWith(CommandType.COMPLEMENT_DATA.toString()); + } + + /** + * get current command type, + * if start with complement data,return complement + */ + public CommandType getCmdTypeIfComplement(){ + if(isComplementData()){ + return CommandType.COMPLEMENT_DATA; + } + return commandType; + } + + public String getDependenceScheduleTimes() { + return dependenceScheduleTimes; + } + + public void setDependenceScheduleTimes(String dependenceScheduleTimes) { + this.dependenceScheduleTimes = dependenceScheduleTimes; + } + + public Long getDuration() { + return duration; + } + + public void setDuration(Long duration) { + this.duration = duration; + } + + + @Override + public String toString() { + return "ProcessInstance{" + + "id=" + id + + ", processDefinitionId=" + processDefinitionId + + ", state=" + state + + ", recovery=" + recovery + + ", startTime=" + startTime + + ", endTime=" + endTime + + ", runTimes=" + runTimes + + ", name='" + name + '\'' + + ", host='" + host + '\'' + + ", processDefinition=" + processDefinition + + ", commandType=" + commandType + + ", commandParam='" + commandParam + '\'' + + ", taskDependType=" + taskDependType + + ", maxTryTimes=" + maxTryTimes + + ", failureStrategy=" + failureStrategy + + ", warningType=" + warningType + + ", warningGroupId=" + warningGroupId + + ", scheduleTime=" + scheduleTime + + ", commandStartTime=" + commandStartTime + + ", globalParams='" + globalParams + '\'' + + ", processInstanceJson='" + processInstanceJson + '\'' + + ", executorId=" + executorId + + ", tenantCode='" + tenantCode + '\'' + + ", queue='" + queue + '\'' + + ", isSubProcess=" + isSubProcess + + ", locations='" + locations + '\'' + + ", connects='" + connects + '\'' + + ", historyCmd='" + historyCmd + '\'' + + ", dependenceScheduleTimes='" + dependenceScheduleTimes + '\'' + + ", duration=" + duration + + ", processInstancePriority=" + processInstancePriority + + '}'; + } +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/model/ProcessInstanceMap.java b/escheduler-dao/src/main/java/cn/escheduler/dao/model/ProcessInstanceMap.java new file mode 100644 index 0000000000..863144eab2 --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/model/ProcessInstanceMap.java @@ -0,0 +1,85 @@ +/* + * 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.dao.model; + +/** + * process instance map + */ +public class ProcessInstanceMap { + + /** + * id + */ + private int id; + + /** + * parent process instance id + */ + private int parentProcessInstanceId; + + /** + * parent task instance id + */ + private int parentTaskInstanceId; + + /** + * process instance id + */ + private int processInstanceId; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public int getParentProcessInstanceId() { + return parentProcessInstanceId; + } + + public void setParentProcessInstanceId(int parentProcessInstanceId) { + this.parentProcessInstanceId = parentProcessInstanceId; + } + + public int getParentTaskInstanceId() { + return parentTaskInstanceId; + } + + public void setParentTaskInstanceId(int parentTaskInstanceId) { + this.parentTaskInstanceId = parentTaskInstanceId; + } + + public int getProcessInstanceId() { + return processInstanceId; + } + + public void setProcessInstanceId(int processInstanceId) { + this.processInstanceId = processInstanceId; + } + + @Override + public String toString() { + return "ProcessInstanceMap{" + + "id=" + id + + ", parentProcessInstanceId=" + parentProcessInstanceId + + ", parentTaskInstanceId=" + parentTaskInstanceId + + ", processInstanceId=" + processInstanceId + + '}'; + } +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/model/Project.java b/escheduler-dao/src/main/java/cn/escheduler/dao/model/Project.java new file mode 100644 index 0000000000..6d0a9bbdb7 --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/model/Project.java @@ -0,0 +1,167 @@ +/* + * 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.dao.model; + +import java.util.Date; + +/** + * project + */ +public class Project { + + /** + * id + */ + private int id; + + /** + * user id + */ + private int userId; + + /** + * user name + */ + private String userName; + + /** + * project name + */ + private String name; + + /** + * project description + */ + private String desc; + + /** + * create time + */ + private Date createTime; + + /** + * update time + */ + private Date updateTime; + + /** + * permission + */ + private int perm; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDesc() { + return desc; + } + + public void setDesc(String desc) { + this.desc = desc; + } + + public Date getCreateTime() { + return createTime; + } + + public void setCreateTime(Date createTime) { + this.createTime = createTime; + } + + public Date getUpdateTime() { + return updateTime; + } + + public void setUpdateTime(Date updateTime) { + this.updateTime = updateTime; + } + + public int getUserId() { + return userId; + } + + public void setUserId(int userId) { + this.userId = userId; + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public int getPerm() { + return perm; + } + + public void setPerm(int perm) { + this.perm = perm; + } + @Override + public String toString() { + return "Project{" + + "id=" + id + + ", userId=" + userId + + ", userName='" + userName + '\'' + + ", name='" + name + '\'' + + ", desc='" + desc + '\'' + + ", createTime=" + createTime + + ", updateTime=" + updateTime + + '}'; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + Project project = (Project) o; + + if (id != project.id) { + return false; + } + return name.equals(project.name); + + } + + @Override + public int hashCode() { + int result = id; + result = 31 * result + name.hashCode(); + return result; + } +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/model/ProjectUser.java b/escheduler-dao/src/main/java/cn/escheduler/dao/model/ProjectUser.java new file mode 100644 index 0000000000..f8d67ebf50 --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/model/ProjectUser.java @@ -0,0 +1,143 @@ +/* + * 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.dao.model; + +import java.util.Date; + +/** + * project user relation + */ +public class ProjectUser { + + /** + * id + */ + private int id; + /** + * project id + */ + private int projectId; + + /** + * project name + */ + private String projectName; + + /** + * user id + */ + private int userId; + + /** + * user name + */ + private String userName; + + /** + * permission + */ + private int perm; + + /** + * create time + */ + private Date createTime; + + /** + * update time + */ + private Date updateTime; + + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public int getProjectId() { + return projectId; + } + + public void setProjectId(int projectId) { + this.projectId = projectId; + } + + public String getProjectName() { + return projectName; + } + + public void setProjectName(String projectName) { + this.projectName = projectName; + } + + public int getUserId() { + return userId; + } + + public void setUserId(int userId) { + this.userId = userId; + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public int getPerm() { + return perm; + } + + public void setPerm(int perm) { + this.perm = perm; + } + + public Date getCreateTime() { + return createTime; + } + + public void setCreateTime(Date createTime) { + this.createTime = createTime; + } + + public Date getUpdateTime() { + return updateTime; + } + + public void setUpdateTime(Date updateTime) { + this.updateTime = updateTime; + } + + @Override + public String toString() { + return "ProjectUser{" + + "id=" + id + + ", projectId=" + projectId + + ", projectName='" + projectName + '\'' + + ", userId=" + userId + + ", userName='" + userName + '\'' + + ", perm=" + perm + + ", createTime=" + createTime + + ", updateTime=" + updateTime + + '}'; + } +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/model/Queue.java b/escheduler-dao/src/main/java/cn/escheduler/dao/model/Queue.java new file mode 100644 index 0000000000..d9a6f37b98 --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/model/Queue.java @@ -0,0 +1,69 @@ +/* + * 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.dao.model; + +/** + * queue + */ +public class Queue { + + /** + * id + */ + private int id; + /** + * queue name + */ + private String queueName; + /** + * yarn queue name + */ + private String queue; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getQueueName() { + return queueName; + } + + public void setQueueName(String queueName) { + this.queueName = queueName; + } + + public String getQueue() { + return queue; + } + + public void setQueue(String queue) { + this.queue = queue; + } + + @Override + public String toString() { + return "Queue{" + + "id=" + id + + ", queueName='" + queueName + '\'' + + ", queue='" + queue + '\'' + + '}'; + } +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/model/Resource.java b/escheduler-dao/src/main/java/cn/escheduler/dao/model/Resource.java new file mode 100644 index 0000000000..5fbd098efd --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/model/Resource.java @@ -0,0 +1,209 @@ +/* + * 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.dao.model; + +import cn.escheduler.common.enums.ResourceType; + +import java.util.Date; + +public class Resource { + /** + * id + */ + private int id; + + /** + * resource alias + */ + private String alias; + + /** + * description + */ + private String desc; + + /** + * file alias + */ + private String fileName; + + /** + * user id + */ + private int userId; + + /** + * resource type + */ + private ResourceType type; + + /** + * resource size + */ + private long size; + + /** + * create time + */ + private Date createTime; + + /** + * update time + */ + private Date updateTime; + + public Resource() { + } + + public Resource(int id, String alias, String fileName, String desc, int userId, + ResourceType type, long size, + Date createTime, Date updateTime) { + this.id = id; + this.alias = alias; + this.fileName = fileName; + this.desc = desc; + this.userId = userId; + this.type = type; + this.size = size; + this.createTime = createTime; + this.updateTime = updateTime; + } + + public Resource(String alias, String fileName, String desc, int userId, ResourceType type, long size, Date createTime, Date updateTime) { + this.alias = alias; + this.fileName = fileName; + this.desc = desc; + this.userId = userId; + this.type = type; + this.size = size; + this.createTime = createTime; + this.updateTime = updateTime; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getAlias() { + return alias; + } + + public void setAlias(String alias) { + this.alias = alias; + } + + public String getFileName() { + return fileName; + } + + public void setFileName(String fileName) { + this.fileName = fileName; + } + + public String getDesc() { + return desc; + } + + public void setDesc(String desc) { + this.desc = desc; + } + + public int getUserId() { + return userId; + } + + public void setUserId(int userId) { + this.userId = userId; + } + + + public ResourceType getType() { + return type; + } + + public void setType(ResourceType type) { + this.type = type; + } + + public long getSize() { + return size; + } + + public void setSize(long size) { + this.size = size; + } + + public Date getCreateTime() { + return createTime; + } + + public void setCreateTime(Date createTime) { + this.createTime = createTime; + } + + public Date getUpdateTime() { + return updateTime; + } + + public void setUpdateTime(Date updateTime) { + this.updateTime = updateTime; + } + + @Override + public String toString() { + return "Resource{" + + "id=" + id + + ", alias='" + alias + '\'' + + ", fileName='" + fileName + '\'' + + ", desc='" + desc + '\'' + + ", userId=" + userId + + ", type=" + type + + ", size=" + size + + ", createTime=" + createTime + + ", updateTime=" + updateTime + + '}'; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + Resource resource = (Resource) o; + + if (id != resource.id) { + return false; + } + return alias.equals(resource.alias); + + } + + @Override + public int hashCode() { + int result = id; + result = 31 * result + alias.hashCode(); + return result; + } +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/model/ResourcesUser.java b/escheduler-dao/src/main/java/cn/escheduler/dao/model/ResourcesUser.java new file mode 100644 index 0000000000..14505ead5a --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/model/ResourcesUser.java @@ -0,0 +1,115 @@ +/* + * 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.dao.model; + +import java.util.Date; + +/** + * resource user relation + */ +public class ResourcesUser { + + /** + * id + */ + private int id; + + /** + * user id + */ + private int userId; + + /** + * resource id + */ + private int resourcesId; + + /** + * permission + */ + private int perm; + + /** + * create time + */ + private Date createTime; + + /** + * update time + */ + private Date updateTime; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public int getUserId() { + return userId; + } + + public void setUserId(int userId) { + this.userId = userId; + } + + public int getResourcesId() { + return resourcesId; + } + + public void setResourcesId(int resourcesId) { + this.resourcesId = resourcesId; + } + + public int getPerm() { + return perm; + } + + public void setPerm(int perm) { + this.perm = perm; + } + + public Date getCreateTime() { + return createTime; + } + + public void setCreateTime(Date createTime) { + this.createTime = createTime; + } + + public Date getUpdateTime() { + return updateTime; + } + + public void setUpdateTime(Date updateTime) { + this.updateTime = updateTime; + } + + @Override + public String toString() { + return "ResourcesUser{" + + "id=" + id + + ", userId=" + userId + + ", resourcesId=" + resourcesId + + ", perm=" + perm + + ", createTime=" + createTime + + ", updateTime=" + updateTime + + '}'; + } +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/model/Schedule.java b/escheduler-dao/src/main/java/cn/escheduler/dao/model/Schedule.java new file mode 100644 index 0000000000..40579a53ac --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/model/Schedule.java @@ -0,0 +1,281 @@ +/* + * 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.dao.model; + +import cn.escheduler.common.enums.FailureStrategy; +import cn.escheduler.common.enums.Priority; +import cn.escheduler.common.enums.ReleaseState; +import cn.escheduler.common.enums.WarningType; + +import java.util.Date; + +/** + * schedule + * + */ +public class Schedule { + + private int id; + /** + * process definition id + */ + private int processDefinitionId; + + /** + * process definition name + */ + private String processDefinitionName; + + /** + * project name + */ + private String projectName; + + /** + * schedule description + */ + private String desc; + + /** + * schedule start time + */ + private Date startTime; + + /** + * schedule end time + */ + private Date endTime; + + /** + * crontab expression + */ + private String crontab; + + /** + * failure strategy + */ + private FailureStrategy failureStrategy; + + /** + * warning type + */ + private WarningType warningType; + + /** + * create time + */ + private Date createTime; + + /** + * update time + */ + private Date updateTime; + + /** + * created user id + */ + private int userId; + + /** + * created user name + */ + private String userName; + + /** + * release state + */ + private ReleaseState releaseState; + + /** + * warning group id + */ + private int warningGroupId; + + + /** + * process instance priority + */ + private Priority processInstancePriority; + + public int getWarningGroupId() { + return warningGroupId; + } + + public void setWarningGroupId(int warningGroupId) { + this.warningGroupId = warningGroupId; + } + + + + public Schedule() { + } + + public String getProjectName() { + return projectName; + } + + public void setProjectName(String projectName) { + this.projectName = projectName; + } + + + + public Date getStartTime() { + + return startTime; + } + + public void setStartTime(Date startTime) { + this.startTime = startTime; + } + + public Date getEndTime() { + return endTime; + } + + public void setEndTime(Date endTime) { + this.endTime = endTime; + } + + public String getCrontab() { + return crontab; + } + + public void setCrontab(String crontab) { + this.crontab = crontab; + } + + public FailureStrategy getFailureStrategy() { + return failureStrategy; + } + + public void setFailureStrategy(FailureStrategy failureStrategy) { + this.failureStrategy = failureStrategy; + } + + public WarningType getWarningType() { + return warningType; + } + + public void setWarningType(WarningType warningType) { + this.warningType = warningType; + } + + public Date getCreateTime() { + return createTime; + } + + public void setCreateTime(Date createTime) { + this.createTime = createTime; + } + + + public ReleaseState getReleaseState() { + return releaseState; + } + + public void setReleaseState(ReleaseState releaseState) { + this.releaseState = releaseState; + } + + public String getDesc() { + return desc; + } + + public void setDesc(String desc) { + this.desc = desc; + } + + public int getProcessDefinitionId() { + return processDefinitionId; + } + + public void setProcessDefinitionId(int processDefinitionId) { + this.processDefinitionId = processDefinitionId; + } + + public String getProcessDefinitionName() { + return processDefinitionName; + } + + public void setProcessDefinitionName(String processDefinitionName) { + this.processDefinitionName = processDefinitionName; + } + + public Date getUpdateTime() { + return updateTime; + } + + public void setUpdateTime(Date updateTime) { + this.updateTime = updateTime; + } + + public int getUserId() { + return userId; + } + + public void setUserId(int userId) { + this.userId = userId; + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public Priority getProcessInstancePriority() { + return processInstancePriority; + } + + public void setProcessInstancePriority(Priority processInstancePriority) { + this.processInstancePriority = processInstancePriority; + } + + @Override + public String toString() { + return "Schedule{" + + "id=" + id + + ", processDefinitionId=" + processDefinitionId + + ", processDefinitionName='" + processDefinitionName + '\'' + + ", projectName='" + projectName + '\'' + + ", desc='" + desc + '\'' + + ", startTime=" + startTime + + ", endTime=" + endTime + + ", crontab='" + crontab + '\'' + + ", failureStrategy=" + failureStrategy + + ", warningType=" + warningType + + ", createTime=" + createTime + + ", updateTime=" + updateTime + + ", userId=" + userId + + ", userName='" + userName + '\'' + + ", releaseState=" + releaseState + + ", warningGroupId=" + warningGroupId + + ", processInstancePriority=" + processInstancePriority + + '}'; + } +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/model/Session.java b/escheduler-dao/src/main/java/cn/escheduler/dao/model/Session.java new file mode 100644 index 0000000000..b52eb494ee --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/model/Session.java @@ -0,0 +1,87 @@ +/* + * 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.dao.model; + +import java.util.Date; + +/** + * session + */ +public class Session { + + /** + * id + */ + private String id; + + /** + * user id + */ + private int userId; + + /** + * last login time + */ + private Date lastLoginTime; + + /** + * user login ip + */ + private String ip; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public int getUserId() { + return userId; + } + + public void setUserId(int userId) { + this.userId = userId; + } + + public String getIp() { + return ip; + } + + public void setIp(String ip) { + this.ip = ip; + } + + public Date getLastLoginTime() { + return lastLoginTime; + } + + public void setLastLoginTime(Date lastLoginTime) { + this.lastLoginTime = lastLoginTime; + } + + @Override + public String toString() { + return "Session{" + + "id=" + id + + ", userId=" + userId + + ", ip='" + ip + '\'' + + ", lastLoginTime=" + lastLoginTime + + '}'; + } +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/model/TaskInstance.java b/escheduler-dao/src/main/java/cn/escheduler/dao/model/TaskInstance.java new file mode 100644 index 0000000000..9d63f7cc7e --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/model/TaskInstance.java @@ -0,0 +1,483 @@ +/* + * 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.dao.model; + +import cn.escheduler.common.enums.ExecutionStatus; +import cn.escheduler.common.enums.Flag; +import cn.escheduler.common.enums.Priority; +import cn.escheduler.common.enums.TaskType; +import cn.escheduler.common.model.TaskNode; +import cn.escheduler.common.utils.JSONUtils; + +import java.util.Date; + +/** + * task instance + */ +public class TaskInstance { + + /** + * id + */ + private int id; + + /** + * task name + */ + private String name; + + /** + * task type + */ + private String taskType; + + /** + * process definition id + */ + private int processDefinitionId; + + /** + * process instance id + */ + private int processInstanceId; + + /** + * process instance name + */ + private String processInstanceName; + + /** + * task json + */ + private String taskJson; + + /** + * state + */ + private ExecutionStatus state; + + /** + * task submit time + */ + private Date submitTime; + + /** + * task start time + */ + private Date startTime; + + /** + * task end time + */ + private Date endTime; + + /** + * task host + */ + private String host; + + /** + * task shell execute path and the resource down from hdfs + * default path: $base_run_dir/processInstanceId/taskInstanceId/retryTimes + */ + private String executePath; + + /** + * task log path + * default path: $base_run_dir/processInstanceId/taskInstanceId/retryTimes + */ + private String logPath; + + /** + * retry times + */ + private int retryTimes; + + /** + * alert flag + */ + private Flag alertFlag; + + /** + * run flag + */ + private Flag runFlag; + + /** + * process instance + */ + private ProcessInstance processInstance; + + /** + * process definition + */ + private ProcessDefinition processDefine; + + /** + * process id + */ + private int pid; + + /** + * appLink + */ + private String appLink; + + /** + * flag + */ + private Flag flag; + + /** + * dependency + */ + private String dependency; + + /** + * duration + * @return + */ + private Long duration; + + /** + * max retry times + * @return + */ + private int maxRetryTimes; + + /** + * task retry interval, unit: minute + * @return + */ + private int retryInterval; + + /** + * task intance priority + */ + private Priority taskInstancePriority; + + /** + * process intance priority + */ + private Priority processInstancePriority; + + /** + * dependent state + * @return + */ + private String dependentResult; + + + public ProcessInstance getProcessInstance() { + return processInstance; + } + + public void setProcessInstance(ProcessInstance processInstance) { + this.processInstance = processInstance; + } + + public ProcessDefinition getProcessDefine() { + return processDefine; + } + + public void setProcessDefine(ProcessDefinition processDefine) { + this.processDefine = processDefine; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getTaskType() { + return taskType; + } + + public void setTaskType(String taskType) { + this.taskType = taskType; + } + + public int getProcessDefinitionId() { + return processDefinitionId; + } + + public void setProcessDefinitionId(int processDefinitionId) { + this.processDefinitionId = processDefinitionId; + } + + public int getProcessInstanceId() { + return processInstanceId; + } + + public void setProcessInstanceId(int processInstanceId) { + this.processInstanceId = processInstanceId; + } + + public String getTaskJson() { + return taskJson; + } + + public void setTaskJson(String taskJson) { + this.taskJson = taskJson; + } + + public ExecutionStatus getState() { + return state; + } + + public void setState(ExecutionStatus state) { + this.state = state; + } + + public Date getSubmitTime() { + return submitTime; + } + + public void setSubmitTime(Date submitTime) { + this.submitTime = submitTime; + } + + public Date getStartTime() { + return startTime; + } + + public void setStartTime(Date startTime) { + this.startTime = startTime; + } + + public Date getEndTime() { + return endTime; + } + + public void setEndTime(Date endTime) { + this.endTime = endTime; + } + + public String getHost() { + return host; + } + + public void setHost(String host) { + this.host = host; + } + + public String getExecutePath() { + return executePath; + } + + public void setExecutePath(String executePath) { + this.executePath = executePath; + } + + public String getLogPath() { + return logPath; + } + + public void setLogPath(String logPath) { + this.logPath = logPath; + } + + public Flag getAlertFlag() { + return alertFlag; + } + + public void setAlertFlag(Flag alertFlag) { + this.alertFlag = alertFlag; + } + + public int getRetryTimes() { + return retryTimes; + } + + public void setRetryTimes(int retryTimes) { + this.retryTimes = retryTimes; + } + + public Boolean isTaskSuccess(){ + return this.state == ExecutionStatus.SUCCESS; + } + + public int getPid() { + return pid; + } + + public void setPid(int pid) { + this.pid = pid; + } + + public String getAppLink() { + return appLink; + } + + public void setAppLink(String appLink) { + this.appLink = appLink; + } + + + public Boolean isSubProcess(){ + return TaskType.SUB_PROCESS.toString().equals(this.taskType.toUpperCase()); + } + + public String getDependency(){ + + if(this.dependency != null){ + return this.dependency; + } + TaskNode taskNode = JSONUtils.parseObject(taskJson, TaskNode.class); + + return taskNode.getDependence(); + } + + public Flag getFlag() { + return flag; + } + + public void setFlag(Flag flag) { + this.flag = flag; + } + public String getProcessInstanceName() { + return processInstanceName; + } + + public void setProcessInstanceName(String processInstanceName) { + this.processInstanceName = processInstanceName; + } + + public Flag getRunFlag() { + return runFlag; + } + + public void setRunFlag(Flag runFlag) { + this.runFlag = runFlag; + } + + public Long getDuration() { + return duration; + } + + public void setDuration(Long duration) { + this.duration = duration; + } + + public int getMaxRetryTimes() { + return maxRetryTimes; + } + + public void setMaxRetryTimes(int maxRetryTimes) { + this.maxRetryTimes = maxRetryTimes; + } + + public int getRetryInterval() { + return retryInterval; + } + + public void setRetryInterval(int retryInterval) { + this.retryInterval = retryInterval; + } + + public Boolean isTaskComplete() { + + return this.getState().typeIsPause() + || this.getState().typeIsSuccess() + || this.getState().typeIsCancel() + || (this.getState().typeIsFailure() && !taskCanRetry()); + } + /** + * 判断是否可以重试 + * @return + */ + public boolean taskCanRetry() { + if(this.isSubProcess()){ + return false; + } + return (this.getState().typeIsFailure() + && this.getRetryTimes() < this.getMaxRetryTimes()); + } + + public void setDependency(String dependency) { + this.dependency = dependency; + } + + public Priority getTaskInstancePriority() { + return taskInstancePriority; + } + + public void setTaskInstancePriority(Priority taskInstancePriority) { + this.taskInstancePriority = taskInstancePriority; + } + + public Priority getProcessInstancePriority() { + return processInstancePriority; + } + + public void setProcessInstancePriority(Priority processInstancePriority) { + this.processInstancePriority = processInstancePriority; + } + + @Override + public String toString() { + return "TaskInstance{" + + "id=" + id + + ", name='" + name + '\'' + + ", taskType='" + taskType + '\'' + + ", processDefinitionId=" + processDefinitionId + + ", processInstanceId=" + processInstanceId + + ", processInstanceName='" + processInstanceName + '\'' + + ", taskJson='" + taskJson + '\'' + + ", state=" + state + + ", submitTime=" + submitTime + + ", startTime=" + startTime + + ", endTime=" + endTime + + ", host='" + host + '\'' + + ", executePath='" + executePath + '\'' + + ", logPath='" + logPath + '\'' + + ", retryTimes=" + retryTimes + + ", alertFlag=" + alertFlag + + ", runFlag=" + runFlag + + ", processInstance=" + processInstance + + ", processDefine=" + processDefine + + ", pid=" + pid + + ", appLink='" + appLink + '\'' + + ", flag=" + flag + + ", dependency=" + dependency + + ", duration=" + duration + + ", maxRetryTimes=" + maxRetryTimes + + ", retryInterval=" + retryInterval + + ", taskInstancePriority=" + taskInstancePriority + + ", processInstancePriority=" + processInstancePriority + + '}'; + } + + public String getDependentResult() { + return dependentResult; + } + + public void setDependentResult(String dependentResult) { + this.dependentResult = dependentResult; + } +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/model/TaskRecord.java b/escheduler-dao/src/main/java/cn/escheduler/dao/model/TaskRecord.java new file mode 100644 index 0000000000..17bd073366 --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/model/TaskRecord.java @@ -0,0 +1,256 @@ +/* + * 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.dao.model; + +import java.util.Date; + +/** + * task record for qianfan + */ +public class TaskRecord { + + /** + * id + */ + private int id; + + /** + * process id + */ + private int procId; + + /** + * procedure name + */ + private String procName; + + /** + * procedure date + */ + private String procDate; + + /** + * start date + */ + private Date startDate; + + /** + * end date + */ + private Date endDate; + + /** + * result + */ + private String result; + + /** + * duration unit: second + */ + private int duration; + + /** + * note + */ + private String note; + + /** + * schema + */ + private String schema; + + /** + * job id + */ + private String jobId; + + + /** + * source tab + */ + private String sourceTab; + + /** + * source row count + */ + private Long sourceRowCount; + + /** + * target tab + */ + private String targetTab; + + /** + * target row count + */ + private Long targetRowCount; + + /** + * error code + */ + private String errorCode; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public int getProcId() { + return procId; + } + + public void setProcId(int procId) { + this.procId = procId; + } + + public String getProcName() { + return procName; + } + + public void setProcName(String procName) { + this.procName = procName; + } + + public String getProcDate() { + return procDate; + } + + public void setProcDate(String procDate) { + this.procDate = procDate; + } + + public Date getStartDate() { + return startDate; + } + + public void setStartDate(Date startDate) { + this.startDate = startDate; + } + + public Date getEndDate() { + return endDate; + } + + public void setEndDate(Date endDate) { + this.endDate = endDate; + } + + public String getResult() { + return result; + } + + public void setResult(String result) { + this.result = result; + } + + public int getDuration() { + return duration; + } + + public void setDuration(int duration) { + this.duration = duration; + } + + public String getNote() { + return note; + } + + public void setNote(String note) { + this.note = note; + } + + public String getSchema() { + return schema; + } + + public void setSchema(String schema) { + this.schema = schema; + } + + public String getJobId() { + return jobId; + } + + public void setJobId(String jobId) { + this.jobId = jobId; + } + + public String getSourceTab() { + return sourceTab; + } + + public void setSourceTab(String sourceTab) { + this.sourceTab = sourceTab; + } + + public Long getSourceRowCount() { + return sourceRowCount; + } + + public void setSourceRowCount(Long sourceRowCount) { + this.sourceRowCount = sourceRowCount; + } + + public String getTargetTab() { + return targetTab; + } + + public void setTargetTab(String targetTab) { + this.targetTab = targetTab; + } + + public Long getTargetRowCount() { + return targetRowCount; + } + + public void setTargetRowCount(Long targetRowCount) { + this.targetRowCount = targetRowCount; + } + + public String getErrorCode() { + return errorCode; + } + + public void setErrorCode(String errorCode) { + this.errorCode = errorCode; + } + + @Override + public String toString(){ + return "task record, id:" + id + +" proc id:" + procId + + " proc name:" + procName + + " proc date: " + procDate + + " start date:" + startDate + + " end date:" + endDate + + " result : " + result + + " duration : " + duration + + " note : " + note + + " schema : " + schema + + " job id : " + jobId + + " source table : " + sourceTab + + " source row count: " + sourceRowCount + + " target table : " + targetTab + + " target row count: " + targetRowCount + + " error code: " + errorCode + ; + } + +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/model/Tenant.java b/escheduler-dao/src/main/java/cn/escheduler/dao/model/Tenant.java new file mode 100644 index 0000000000..a8cc94e1ab --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/model/Tenant.java @@ -0,0 +1,142 @@ +/* + * 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.dao.model; + +import java.util.Date; + +/** + * tenant + */ +public class Tenant { + + /** + * id + */ + private int id; + + /** + * tenant code + */ + private String tenantCode; + + /** + * tenant name + */ + private String tenantName; + + /** + * description + */ + private String desc; + + /** + * queue id + */ + private int queueId; + + /** + * queue name + */ + private String queueName; + + /** + * create time + */ + private Date createTime; + /** + * update time + */ + private Date updateTime; + + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getTenantCode() { + return tenantCode; + } + + public void setTenantCode(String tenantCode) { + this.tenantCode = tenantCode; + } + + public String getTenantName() { + return tenantName; + } + + public void setTenantName(String tenantName) { + this.tenantName = tenantName; + } + + public String getDesc() { + return desc; + } + + public void setDesc(String desc) { + this.desc = desc; + } + + public int getQueueId() { + return queueId; + } + + public void setQueueId(int queueId) { + this.queueId = queueId; + } + + public Date getCreateTime() { + return createTime; + } + + public void setCreateTime(Date createTime) { + this.createTime = createTime; + } + + public Date getUpdateTime() { + return updateTime; + } + + public void setUpdateTime(Date updateTime) { + this.updateTime = updateTime; + } + + public String getQueueName() { + return queueName; + } + + public void setQueueName(String queueName) { + this.queueName = queueName; + } + @Override + public String toString() { + return "Tenant{" + + "id=" + id + + ", tenantCode='" + tenantCode + '\'' + + ", tenantName='" + tenantName + '\'' + + ", desc='" + desc + '\'' + + ", queueId=" + queueId + + ", queueName='" + queueName + '\'' + + ", createTime=" + createTime + + ", updateTime=" + updateTime + + '}'; + } +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/model/UDFUser.java b/escheduler-dao/src/main/java/cn/escheduler/dao/model/UDFUser.java new file mode 100644 index 0000000000..fe49adc08e --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/model/UDFUser.java @@ -0,0 +1,115 @@ +/* + * 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.dao.model; + +import java.util.Date; + +/** + * udf user relation + */ +public class UDFUser { + + /** + * id + */ + private int id; + + /** + * id + */ + private int userId; + + /** + * udf id + */ + private int udfId; + + /** + * permission + */ + private int perm; + + /** + * create time + */ + private Date createTime; + + /** + * update time + */ + private Date updateTime; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public int getUserId() { + return userId; + } + + public void setUserId(int userId) { + this.userId = userId; + } + + public int getUdfId() { + return udfId; + } + + public void setUdfId(int udfId) { + this.udfId = udfId; + } + + public int getPerm() { + return perm; + } + + public void setPerm(int perm) { + this.perm = perm; + } + + public Date getCreateTime() { + return createTime; + } + + public void setCreateTime(Date createTime) { + this.createTime = createTime; + } + + public Date getUpdateTime() { + return updateTime; + } + + public void setUpdateTime(Date updateTime) { + this.updateTime = updateTime; + } + + @Override + public String toString() { + return "UDFUser{" + + "id=" + id + + ", userId=" + userId + + ", udfId=" + udfId + + ", perm=" + perm + + ", createTime=" + createTime + + ", updateTime=" + updateTime + + '}'; + } +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/model/UdfFunc.java b/escheduler-dao/src/main/java/cn/escheduler/dao/model/UdfFunc.java new file mode 100644 index 0000000000..979b201ad3 --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/model/UdfFunc.java @@ -0,0 +1,225 @@ +/* + * 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.dao.model; + +import cn.escheduler.common.enums.UdfType; + +import java.util.Date; + +/** + * udf function + */ +public class UdfFunc { + /** + * id + */ + private int id; + /** + * user id + */ + private int userId; + + /** + * udf function name + */ + private String funcName; + + /** + * udf class name + */ + private String className; + + /** + * udf argument types + */ + private String argTypes; + + /** + * udf data base + */ + private String database; + + /** + * udf description + */ + private String desc; + + /** + * resource id + */ + private int resourceId; + + /** + * resource name + */ + private String resourceName; + + /** + * udf function type: hive / spark + */ + private UdfType type; + + /** + * create time + */ + private Date createTime; + + /** + * update time + */ + private Date updateTime; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public int getUserId() { + return userId; + } + + public void setUserId(int userId) { + this.userId = userId; + } + + public String getFuncName() { + return funcName; + } + + public void setFuncName(String funcName) { + this.funcName = funcName; + } + + public String getClassName() { + return className; + } + + public void setClassName(String className) { + this.className = className; + } + + public String getArgTypes() { + return argTypes; + } + + public void setArgTypes(String argTypes) { + this.argTypes = argTypes; + } + + public String getDatabase() { + return database; + } + + public void setDatabase(String database) { + this.database = database; + } + + public String getDesc() { + return desc; + } + + public void setDesc(String desc) { + this.desc = desc; + } + + public int getResourceId() { + return resourceId; + } + + public void setResourceId(int resourceId) { + this.resourceId = resourceId; + } + + public String getResourceName() { + return resourceName; + } + + public void setResourceName(String resourceName) { + this.resourceName = resourceName; + } + + public UdfType getType() { + return type; + } + + public void setType(UdfType type) { + this.type = type; + } + + public Date getCreateTime() { + return createTime; + } + + public void setCreateTime(Date createTime) { + this.createTime = createTime; + } + + + public Date getUpdateTime() { + return updateTime; + } + + public void setUpdateTime(Date updateTime) { + this.updateTime = updateTime; + } + + @Override + public String toString() { + return "UdfFunc{" + + "id=" + id + + ", userId=" + userId + + ", funcName='" + funcName + '\'' + + ", className='" + className + '\'' + + ", argTypes='" + argTypes + '\'' + + ", database='" + database + '\'' + + ", desc='" + desc + '\'' + + ", resourceId=" + resourceId + + ", resourceName='" + resourceName + '\'' + + ", type=" + type + + ", createTime=" + createTime + + ", updateTime=" + updateTime + + '}'; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + UdfFunc udfFunc = (UdfFunc) o; + + if (id != udfFunc.id) { + return false; + } + return !(funcName != null ? !funcName.equals(udfFunc.funcName) : udfFunc.funcName != null); + + } + + @Override + public int hashCode() { + int result = id; + result = 31 * result + (funcName != null ? funcName.hashCode() : 0); + return result; + } +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/model/User.java b/escheduler-dao/src/main/java/cn/escheduler/dao/model/User.java new file mode 100644 index 0000000000..7fda405ef2 --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/model/User.java @@ -0,0 +1,240 @@ +/* + * 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.dao.model; + +import cn.escheduler.common.enums.UserType; + +import java.util.Date; + +/** + * user + */ +public class User { + + /** + * id + */ + private int id; + + /** + * user name + */ + private String userName; + + /** + * user password + */ + private String userPassword; + + /** + * mail + */ + private String email; + + /** + * phone + */ + private String phone; + + /** + * user type + */ + private UserType userType; + + /** + * tenant id + */ + private int tenantId; + + /** + * tenant code + */ + private String tenantCode; + + /** + * tenant name + */ + private String tenantName; + + /** + * queue name + */ + private String queueName; + + /** + * alert group + */ + private String alertGroup; + /** + * create time + */ + private Date createTime; + + /** + * update time + */ + private Date updateTime; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public String getUserPassword() { + return userPassword; + } + + public void setUserPassword(String userPassword) { + this.userPassword = userPassword; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public UserType getUserType() { + return userType; + } + + public void setUserType(UserType userType) { + this.userType = userType; + } + + public int getTenantId() { + return tenantId; + } + + public void setTenantId(int tenantId) { + this.tenantId = tenantId; + } + + public Date getCreateTime() { + return createTime; + } + + public void setCreateTime(Date createTime) { + this.createTime = createTime; + } + + public Date getUpdateTime() { + return updateTime; + } + + public void setUpdateTime(Date updateTime) { + this.updateTime = updateTime; + } + + + public String getPhone() { + return phone; + } + + public void setPhone(String phone) { + this.phone = phone; + } + + public String getQueueName() { + return queueName; + } + + public void setQueueName(String queueName) { + this.queueName = queueName; + } + + public String getAlertGroup() { + return alertGroup; + } + + public void setAlertGroup(String alertGroup) { + this.alertGroup = alertGroup; + } + + public String getTenantName() { + return tenantName; + } + + public void setTenantName(String tenantName) { + this.tenantName = tenantName; + } + + public String getTenantCode() { + return tenantCode; + } + + public void setTenantCode(String tenantCode) { + this.tenantCode = tenantCode; + } + + @Override + public String toString() { + return "User{" + + "id=" + id + + ", userName='" + userName + '\'' + + ", userPassword='" + userPassword + '\'' + + ", email='" + email + '\'' + + ", phone='" + phone + '\'' + + ", userType=" + userType + + ", tenantId=" + tenantId + + ", tenantCode='" + tenantCode + '\'' + + ", tenantName='" + tenantName + '\'' + + ", queueName='" + queueName + '\'' + + ", alertGroup='" + alertGroup + '\'' + + ", createTime=" + createTime + + ", updateTime=" + updateTime + + '}'; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + User user = (User) o; + + if (id != user.id) { + return false; + } + return userName.equals(user.userName); + + } + + @Override + public int hashCode() { + int result = id; + result = 31 * result + userName.hashCode(); + return result; + } +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/model/UserAlertGroup.java b/escheduler-dao/src/main/java/cn/escheduler/dao/model/UserAlertGroup.java new file mode 100644 index 0000000000..ffd5a9715e --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/model/UserAlertGroup.java @@ -0,0 +1,129 @@ +/* + * 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.dao.model; + +import java.util.Date; + +/** + * user alert group + */ +public class UserAlertGroup { + + /** + * id + */ + private int id; + + /** + * id + */ + private int alertgroupId; + + /** + * alert group name + */ + private String alertgroupName; + + /** + * user id + */ + private int userId; + + /** + * user name + */ + private String userName; + + /** + * create time + */ + private Date createTime; + + /** + * update time + */ + private Date updateTime; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public int getAlertgroupId() { + return alertgroupId; + } + + public void setAlertgroupId(int alertgroupId) { + this.alertgroupId = alertgroupId; + } + + public int getUserId() { + return userId; + } + + public void setUserId(int userId) { + this.userId = userId; + } + + public Date getCreateTime() { + return createTime; + } + + public void setCreateTime(Date createTime) { + this.createTime = createTime; + } + + public Date getUpdateTime() { + return updateTime; + } + + public void setUpdateTime(Date updateTime) { + this.updateTime = updateTime; + } + + public String getAlertgroupName() { + return alertgroupName; + } + + public void setAlertgroupName(String alertgroupName) { + this.alertgroupName = alertgroupName; + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + @Override + public String toString() { + return "UserAlertGroup{" + + "id=" + id + + ", alertgroupId=" + alertgroupId + + ", alertgroupName='" + alertgroupName + '\'' + + ", userId=" + userId + + ", userName='" + userName + '\'' + + ", createTime=" + createTime + + ", updateTime=" + updateTime + + '}'; + } +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/model/WorkerServer.java b/escheduler-dao/src/main/java/cn/escheduler/dao/model/WorkerServer.java new file mode 100644 index 0000000000..4ee158b2e4 --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/model/WorkerServer.java @@ -0,0 +1,127 @@ +/* + * 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.dao.model; + +import java.util.Date; + +public class WorkerServer { + + /** + * id + */ + private int id; + + /** + * host + */ + private String host; + + /** + * port + */ + private int port; + + + /** + * zookeeper directory + */ + private String zkDirectory; + + /** + * resource info + */ + private String resInfo; + + /** + * create time + */ + private Date createTime; + + /** + * last heart beat time + */ + private Date lastHeartbeatTime; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getHost() { + return host; + } + + public void setHost(String host) { + this.host = host; + } + + public int getPort() { + return port; + } + + public void setPort(int port) { + this.port = port; + } + + public Date getCreateTime() { + return createTime; + } + + public void setCreateTime(Date createTime) { + this.createTime = createTime; + } + + public String getZkDirectory() { + return zkDirectory; + } + + public void setZkDirectory(String zkDirectory) { + this.zkDirectory = zkDirectory; + } + + public Date getLastHeartbeatTime() { + return lastHeartbeatTime; + } + + public void setLastHeartbeatTime(Date lastHeartbeatTime) { + this.lastHeartbeatTime = lastHeartbeatTime; + } + + public String getResInfo() { + return resInfo; + } + + public void setResInfo(String resInfo) { + this.resInfo = resInfo; + } + + @Override + public String toString() { + return "WorkerServer{" + + "id=" + id + + ", host='" + host + '\'' + + ", port=" + port + + ", zkDirectory='" + zkDirectory + '\'' + + ", resInfo='" + resInfo + '\'' + + ", createTime=" + createTime + + ", lastHeartbeatTime=" + lastHeartbeatTime + + '}'; + } +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/utils/DagHelper.java b/escheduler-dao/src/main/java/cn/escheduler/dao/utils/DagHelper.java new file mode 100644 index 0000000000..bc52e85062 --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/utils/DagHelper.java @@ -0,0 +1,213 @@ +/* + * 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.dao.utils; + + +import cn.escheduler.common.enums.TaskDependType; +import cn.escheduler.common.model.TaskNode; +import cn.escheduler.common.model.TaskNodeRelation; +import cn.escheduler.common.process.ProcessDag; +import cn.escheduler.common.utils.JSONUtils; +import cn.escheduler.dao.model.ProcessData; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.List; + +/** + * dag tools + */ +public class DagHelper { + + + private static final Logger logger = LoggerFactory.getLogger(DagHelper.class); + + /** + * generate flow node relation list by task node list; + * Edges that are not in the task Node List will not be added to the result + * 根据task Node List生成node关系列表,不在task Node List中的边不会被添加到结果中 + * + * @param taskNodeList + * @return + */ + private static List generateRelationListByFlowNodes(List taskNodeList) { + List nodeRelationList = new ArrayList<>(); + for (TaskNode taskNode : taskNodeList) { + String preTasks = taskNode.getPreTasks(); + List preTaskList = JSONUtils.toList(preTasks, String.class); + if (preTaskList != null) { + for (String depNodeName : preTaskList) { + if (null != findNodeByName(taskNodeList, depNodeName)) { + nodeRelationList.add(new TaskNodeRelation(depNodeName, taskNode.getName())); + } + } + } + } + return nodeRelationList; + } + + /** + * generate task nodes needed by dag + * 生成dag需要的task nodes + * + * @param taskNodeList + * @param taskDependType + * @return + */ + private static List generateFlowNodeListByStartNode(List taskNodeList, List startNodeNameList, + List recoveryNodeNameList, TaskDependType taskDependType) { + List destFlowNodeList = new ArrayList<>(); + List startNodeList = startNodeNameList; + + if(taskDependType != TaskDependType.TASK_POST + && startNodeList.size() == 0){ + logger.error("start node list is empty! cannot continue run the process "); + return destFlowNodeList; + } + List destTaskNodeList = new ArrayList<>(); + List tmpTaskNodeList = new ArrayList<>(); + if (taskDependType == TaskDependType.TASK_POST + && recoveryNodeNameList.size() > 0) { + startNodeList = recoveryNodeNameList; + } + if (startNodeList == null || startNodeList.size() == 0) { + // 没有特殊的指定start nodes + tmpTaskNodeList = taskNodeList; + } else { + // 指定了start nodes or 恢复执行 + for (String startNodeName : startNodeList) { + TaskNode startNode = findNodeByName(taskNodeList, startNodeName); + List childNodeList = new ArrayList<>(); + if (TaskDependType.TASK_POST == taskDependType) { + childNodeList = getFlowNodeListPost(startNode, taskNodeList); + } else if (TaskDependType.TASK_PRE == taskDependType) { + childNodeList = getFlowNodeListPre(startNode, recoveryNodeNameList, taskNodeList); + } else { + childNodeList.add(startNode); + } + tmpTaskNodeList.addAll(childNodeList); + } + } + + for (TaskNode taskNode : tmpTaskNodeList) { + if ( !taskNode.isForbidden() + && null == findNodeByName(destTaskNodeList, taskNode.getName())) { + destTaskNodeList.add(taskNode); + } + } + return destTaskNodeList; + } + + + /** + * find all the nodes that depended on the start node + * 找到所有依赖start node的node + * + * @param startNode + * @param taskNodeList + * @return + */ + private static List getFlowNodeListPost(TaskNode startNode, List taskNodeList) { + List resultList = new ArrayList<>(); + for (TaskNode taskNode : taskNodeList) { + List depList = taskNode.getDepList(); + if (depList != null) { + if (depList.contains(startNode.getName())) { + resultList.addAll(getFlowNodeListPost(taskNode, taskNodeList)); + } + } + + } + resultList.add(startNode); + return resultList; + } + + /** + * find all nodes that start nodes depend on. + * 找到所有start node依赖的node + * + * @param startNode + * @param taskNodeList + * @return + */ + private static List getFlowNodeListPre(TaskNode startNode, List recoveryNodeNameList, List taskNodeList) { + + List resultList = new ArrayList<>(); + + List depList = startNode.getDepList(); + resultList.add(startNode); + if (depList == null || depList.size() == 0) { + return resultList; + } + for (String depNodeName : depList) { + TaskNode start = findNodeByName(taskNodeList, depNodeName); + if (recoveryNodeNameList.contains(depNodeName)) { + resultList.add(start); + } else { + resultList.addAll(getFlowNodeListPre(start, recoveryNodeNameList, taskNodeList)); + } + } + return resultList; + } + + /** + * generate dag by start nodes and recovery nodes + * 根据start nodes 和 recovery nodes 生成dag + * @param processDefinitionJson + * @param startNodeNameList + * @param recoveryNodeNameList + * @param depNodeType + * @return + * @throws Exception + */ + public static ProcessDag generateFlowDag(String processDefinitionJson, + List startNodeNameList, + List recoveryNodeNameList, + TaskDependType depNodeType) throws Exception { + ProcessData processData = JSONUtils.parseObject(processDefinitionJson, ProcessData.class); + + List taskNodeList = processData.getTasks(); + List destTaskNodeList = generateFlowNodeListByStartNode(taskNodeList, startNodeNameList, recoveryNodeNameList, depNodeType); + if (destTaskNodeList.isEmpty()) { + return null; + } + List taskNodeRelations = generateRelationListByFlowNodes(destTaskNodeList); + ProcessDag processDag = new ProcessDag(); + processDag.setEdges(taskNodeRelations); + processDag.setNodes(destTaskNodeList); + return processDag; + } + + + /** + * find node by node name + * 通过 name 获取节点 + * @param nodeDetails + * @param nodeName + * @return + * @see TaskNode + */ + public static TaskNode findNodeByName(List nodeDetails, String nodeName) { + for (TaskNode taskNode : nodeDetails) { + if (taskNode.getName().equals(nodeName)) { + return taskNode; + } + } + return null; + } +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/utils/PropertyUtils.java b/escheduler-dao/src/main/java/cn/escheduler/dao/utils/PropertyUtils.java new file mode 100644 index 0000000000..0b17fe9b2f --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/utils/PropertyUtils.java @@ -0,0 +1,192 @@ +/* + * 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.dao.utils; + +import cn.escheduler.common.Constants; +import org.apache.commons.io.IOUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; + + +/** + * property utils + * single instance + */ +public class PropertyUtils { + + /** + * logger + */ + private static final Logger logger = LoggerFactory.getLogger(PropertyUtils.class); + + private static final Properties properties = new Properties(); + + private static final PropertyUtils propertyUtils = new PropertyUtils(); + + private PropertyUtils(){ + init(); + } + + private void init(){ + String[] propertyFiles = new String[]{Constants.DAO_PROPERTIES_PATH}; + for (String fileName : propertyFiles) { + InputStream fis = null; + try { + fis = PropertyUtils.class.getResourceAsStream(fileName); + properties.load(fis); + + } catch (IOException e) { + logger.error(e.getMessage(), e); + System.exit(1); + } finally { + IOUtils.closeQuietly(fis); + } + } + } + +/* + public static PropertyUtils getInstance(){ + return propertyUtils; + } +*/ + + /** + * get property value + * + * @param key property name + * @return + */ + public static String getString(String key) { + return properties.getProperty(key); + } + + /** + * get property value + * + * @param key property name + * @return get property int value , if key == null, then return -1 + */ + public static int getInt(String key) { + return getInt(key, -1); + } + + /** + * + * @param key + * @param defaultValue + * @return + */ + public static int getInt(String key, int defaultValue) { + String value = getString(key); + if (value == null) { + return defaultValue; + } + + try { + return Integer.parseInt(value); + } catch (NumberFormatException e) { + logger.info(e.getMessage(),e); + } + return defaultValue; + } + + /** + * get property value + * + * @param key property name + * @return + */ + public static Boolean getBoolean(String key) { + String value = properties.getProperty(key.trim()); + if(null != value){ + return Boolean.parseBoolean(value); + } + + return null; + } + + /** + * + * @param key + * @return + */ + public static long getLong(String key) { + return getLong(key,-1); + } + + /** + * + * @param key + * @param defaultVal + * @return + */ + public static long getLong(String key, long defaultVal) { + String val = getString(key); + return val == null ? defaultVal : Long.parseLong(val); + } + + + /** + * + * @param key + * @param defaultVal + * @return + */ + public double getDouble(String key, double defaultVal) { + String val = getString(key); + return val == null ? defaultVal : Double.parseDouble(val); + } + + + /** + * get array + * @param key property name + * @param splitStr separator + * @return + */ + public static String[] getArray(String key, String splitStr) { + String value = getString(key); + if (value == null) { + return null; + } + try { + String[] propertyArray = value.split(splitStr); + return propertyArray; + } catch (NumberFormatException e) { + logger.info(e.getMessage(),e); + } + return null; + } + + /** + * + * @param key + * @param type + * @param defaultValue + * @param + * @return get enum value + */ + public > T getEnum(String key, Class type, + T defaultValue) { + String val = getString(key); + return val == null ? defaultValue : Enum.valueOf(type, val); + } +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/utils/cron/AbstractCycle.java b/escheduler-dao/src/main/java/cn/escheduler/dao/utils/cron/AbstractCycle.java new file mode 100644 index 0000000000..3d75256737 --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/utils/cron/AbstractCycle.java @@ -0,0 +1,169 @@ +/* + * 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.dao.utils.cron; + +import cn.escheduler.common.enums.CycleEnum; +import com.cronutils.model.Cron; +import com.cronutils.model.field.CronField; +import com.cronutils.model.field.CronFieldName; +import com.cronutils.model.field.expression.*; + +/** + * Cycle + */ +public abstract class AbstractCycle { + + protected Cron cron; + + protected CronField minField; + protected CronField hourField; + protected CronField dayOfMonthField; + protected CronField dayOfWeekField; + protected CronField monthField; + protected CronField yearField; + + public CycleLinks addCycle(AbstractCycle cycle) { + return new CycleLinks(this.cron).addCycle(this).addCycle(cycle); + } + + public AbstractCycle(Cron cron) { + if (cron == null) { + throw new IllegalArgumentException("cron must not be null!"); + } + + this.cron = cron; + this.minField = cron.retrieve(CronFieldName.MINUTE); + this.hourField = cron.retrieve(CronFieldName.HOUR); + this.dayOfMonthField = cron.retrieve(CronFieldName.DAY_OF_MONTH); + this.dayOfWeekField = cron.retrieve(CronFieldName.DAY_OF_WEEK); + this.monthField = cron.retrieve(CronFieldName.MONTH); + this.yearField = cron.retrieve(CronFieldName.YEAR); + } + + /** + * Whether the minute field has a value + * @return + */ + protected boolean minFiledIsSetAll(){ + FieldExpression minFieldExpression = minField.getExpression(); + return (minFieldExpression instanceof Every || minFieldExpression instanceof Always + || minFieldExpression instanceof Between || minFieldExpression instanceof And + || minFieldExpression instanceof On); + } + + + /** + * Whether the minute field has a value of every or always + * @return + */ + protected boolean minFiledIsEvery(){ + FieldExpression minFieldExpression = minField.getExpression(); + return (minFieldExpression instanceof Every || minFieldExpression instanceof Always); + } + + /** + * Whether the hour field has a value + * @return + */ + protected boolean hourFiledIsSetAll(){ + FieldExpression hourFieldExpression = hourField.getExpression(); + return (hourFieldExpression instanceof Every || hourFieldExpression instanceof Always + || hourFieldExpression instanceof Between || hourFieldExpression instanceof And + || hourFieldExpression instanceof On); + } + + /** + * Whether the hour field has a value of every or always + * @return + */ + protected boolean hourFiledIsEvery(){ + FieldExpression hourFieldExpression = hourField.getExpression(); + return (hourFieldExpression instanceof Every || hourFieldExpression instanceof Always); + } + + /** + * Whether the day Of month field has a value + * @return + */ + protected boolean dayOfMonthFieldIsSetAll(){ + return (dayOfMonthField.getExpression() instanceof Every || dayOfMonthField.getExpression() instanceof Always + || dayOfMonthField.getExpression() instanceof Between || dayOfMonthField.getExpression() instanceof And + || dayOfMonthField.getExpression() instanceof On); + } + + + /** + * Whether the day Of Month field has a value of every or always + * @return + */ + protected boolean dayOfMonthFieldIsEvery(){ + return (dayOfMonthField.getExpression() instanceof Every || dayOfMonthField.getExpression() instanceof Always); + } + + /** + * Whether month field has a value + * @return + */ + protected boolean monthFieldIsSetAll(){ + FieldExpression monthFieldExpression = monthField.getExpression(); + return (monthFieldExpression instanceof Every || monthFieldExpression instanceof Always + || monthFieldExpression instanceof Between || monthFieldExpression instanceof And + || monthFieldExpression instanceof On); + } + + /** + * Whether the month field has a value of every or always + * @return + */ + protected boolean monthFieldIsEvery(){ + FieldExpression monthFieldExpression = monthField.getExpression(); + return (monthFieldExpression instanceof Every || monthFieldExpression instanceof Always); + } + + /** + * Whether the day Of week field has a value + * @return + */ + protected boolean dayofWeekFieldIsSetAll(){ + FieldExpression dayOfWeekFieldExpression = dayOfWeekField.getExpression(); + return (dayOfWeekFieldExpression instanceof Every || dayOfWeekFieldExpression instanceof Always + || dayOfWeekFieldExpression instanceof Between || dayOfWeekFieldExpression instanceof And + || dayOfWeekFieldExpression instanceof On); + } + + /** + * Whether the day Of week field has a value of every or always + * @return + */ + protected boolean dayofWeekFieldIsEvery(){ + FieldExpression dayOfWeekFieldExpression = dayOfWeekField.getExpression(); + return (dayOfWeekFieldExpression instanceof Every || dayOfWeekFieldExpression instanceof Always); + } + /** + * get cycle enum + * + * @return + */ + protected abstract CycleEnum getCycle(); + + /** + * get mini level cycle enum + * + * @return + */ + protected abstract CycleEnum getMiniCycle(); +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/utils/cron/CronUtils.java b/escheduler-dao/src/main/java/cn/escheduler/dao/utils/cron/CronUtils.java new file mode 100644 index 0000000000..7579ac15a0 --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/utils/cron/CronUtils.java @@ -0,0 +1,207 @@ +/* + * 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.dao.utils.cron; + + +import cn.escheduler.common.enums.CycleEnum; +import cn.escheduler.common.thread.Stopper; +import cn.escheduler.common.utils.DateUtils; +import com.cronutils.model.Cron; +import com.cronutils.model.definition.CronDefinitionBuilder; +import com.cronutils.parser.CronParser; +import org.quartz.CronExpression; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.text.ParseException; +import java.util.*; + +import static cn.escheduler.dao.utils.cron.CycleFactory.*; +import static com.cronutils.model.CronType.QUARTZ; + + +/** + * cron utils + */ +public class CronUtils { + + private static final Logger logger = LoggerFactory.getLogger(CronUtils.class); + + + private static final CronParser QUARTZ_CRON_PARSER = new CronParser(CronDefinitionBuilder.instanceDefinitionFor(QUARTZ)); + + /** + * Parse string with cron expression to Cron + * + * @param cronExpression + * - cron expression, never null + * @return Cron instance, corresponding to cron expression received + * @throws java.lang.IllegalArgumentException + * if expression does not match cron definition + */ + public static Cron parse2Cron(String cronExpression) { + return QUARTZ_CRON_PARSER.parse(cronExpression); + } + + /** + * build a new CronExpression based on the string cronExpression. + * + * @param cronExpression String representation of the cron expression the + * new object should represent + * @throws java.text.ParseException + * if the string expression cannot be parsed into a valid + * CronExpression + */ + public static CronExpression parse2CronExpression(String cronExpression) throws ParseException { + return new CronExpression(cronExpression); + } + + /** + * get cycle enum + * @param cron + * @return + */ + public static CycleEnum getMaxCycle(Cron cron) { + return min(cron).addCycle(hour(cron)).addCycle(day(cron)).addCycle(week(cron)).addCycle(month(cron)).getCycle(); + } + + /** + * get cycle enum + * @param cron + * @return + */ + public static CycleEnum getMiniCycle(Cron cron) { + return min(cron).addCycle(hour(cron)).addCycle(day(cron)).addCycle(week(cron)).addCycle(month(cron)).getMiniCycle(); + } + + /** + * get mini level of cycle enum + * + * @param crontab + * @return + */ + public static CycleEnum getMiniCycle(String crontab) { + return getMiniCycle(parse2Cron(crontab)); + } + + /** + * get cycle enum + * + * @param crontab + * @return + */ + public static CycleEnum getMaxCycle(String crontab) { + return getMaxCycle(parse2Cron(crontab)); + } + + /** + * gets all scheduled times for a period of time based on not self dependency + * @param startTime + * @param endTime + * @param cronExpression + * @return + */ + public static List getFireDateList(Date startTime, Date endTime, CronExpression cronExpression) { + List dateList = new ArrayList<>(); + + while (Stopper.isRunning()) { + startTime = cronExpression.getNextValidTimeAfter(startTime); + if (startTime.after(endTime)) { + break; + } + dateList.add(startTime); + } + + return dateList; + } + + /** + * gets all scheduled times for a period of time based on self dependency + * @param startTime + * @param endTime + * @param cronExpression + * @return + */ + public static List getSelfFireDateList(Date startTime, Date endTime, CronExpression cronExpression) { + List dateList = new ArrayList<>(); + + while (Stopper.isRunning()) { + startTime = cronExpression.getNextValidTimeAfter(startTime); + if (startTime.after(endTime) || startTime.equals(endTime)) { + break; + } + dateList.add(startTime); + } + + return dateList; + } + + + /** + * get expiration time + * @param startTime + * @param cycleEnum + * @return + */ + public static Date getExpirationTime(Date startTime, CycleEnum cycleEnum) { + Date maxExpirationTime = null; + Date startTimeMax = null; + try { + startTimeMax = getEndTime(startTime); + + Calendar calendar = Calendar.getInstance(); + calendar.setTime(startTime); + switch (cycleEnum) { + case HOUR: + calendar.add(Calendar.HOUR, 1); + break; + case DAY: + calendar.add(Calendar.DATE, 1); + break; + case WEEK: + calendar.add(Calendar.DATE, 1); + break; + case MONTH: + calendar.add(Calendar.DATE, 1); + break; + default: + logger.error("Dependent process definition's cycleEnum is {},not support!!", cycleEnum.name()); + break; + } + maxExpirationTime = calendar.getTime(); + } catch (Exception e) { + logger.error(e.getMessage(),e); + } + return DateUtils.compare(startTimeMax,maxExpirationTime)?maxExpirationTime:startTimeMax; + } + + /** + * get the end time of the day by value of date + * @param date + * @return + */ + private static Date getEndTime(Date date) { + Calendar end = new GregorianCalendar(); + end.setTime(date); + end.set(Calendar.HOUR_OF_DAY,23); + end.set(Calendar.MINUTE,59); + end.set(Calendar.SECOND,59); + end.set(Calendar.MILLISECOND,999); + return end.getTime(); + } + +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/utils/cron/CycleFactory.java b/escheduler-dao/src/main/java/cn/escheduler/dao/utils/cron/CycleFactory.java new file mode 100644 index 0000000000..fabf289b96 --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/utils/cron/CycleFactory.java @@ -0,0 +1,211 @@ +/* + * 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.dao.utils.cron; + +import cn.escheduler.common.enums.CycleEnum; +import com.cronutils.model.Cron; +import com.cronutils.model.field.expression.Always; +import com.cronutils.model.field.expression.QuestionMark; + +/** + * Crontab Cycle Tool Factory + */ +public class CycleFactory { + + public static AbstractCycle min(Cron cron) { + return new MinCycle(cron); + } + + public static AbstractCycle hour(Cron cron) { + return new HourCycle(cron); + } + + public static AbstractCycle day(Cron cron) { + return new DayCycle(cron); + } + + public static AbstractCycle week(Cron cron) { + return new WeekCycle(cron); + } + + public static AbstractCycle month(Cron cron) { + return new MonthCycle(cron); + } + + /** + * day cycle + */ + public static class DayCycle extends AbstractCycle { + + public DayCycle(Cron cron) { + super(cron); + } + + @Override + protected CycleEnum getCycle() { + + if (minFiledIsSetAll() + && hourFiledIsSetAll() + && dayOfMonthFieldIsEvery() + && dayOfWeekField.getExpression() instanceof QuestionMark + && monthField.getExpression() instanceof Always) { + return CycleEnum.DAY; + } + + return null; + } + + @Override + protected CycleEnum getMiniCycle() { + if (dayOfMonthFieldIsEvery()) { + return CycleEnum.DAY; + } + + return null; + } + } + + /** + * hour cycle + */ + public static class HourCycle extends AbstractCycle { + + public HourCycle(Cron cron) { + super(cron); + } + + @Override + protected CycleEnum getCycle() { + if (minFiledIsSetAll() + && hourFiledIsEvery() + && dayOfMonthField.getExpression() instanceof Always + && dayOfWeekField.getExpression() instanceof QuestionMark + && monthField.getExpression() instanceof Always) { + return CycleEnum.HOUR; + } + + return null; + } + + @Override + protected CycleEnum getMiniCycle() { + if(hourFiledIsEvery()){ + return CycleEnum.HOUR; + } + return null; + } + } + + /** + * minute cycle + */ + public static class MinCycle extends AbstractCycle { + + public MinCycle(Cron cron) { + super(cron); + } + + @Override + protected CycleEnum getCycle() { + if (minFiledIsEvery() + && hourField.getExpression() instanceof Always + && dayOfMonthField.getExpression() instanceof Always + && monthField.getExpression() instanceof Always) { + return CycleEnum.MINUTE; + } + + return null; + } + + @Override + protected CycleEnum getMiniCycle() { + if(minFiledIsEvery()){ + return CycleEnum.MINUTE; + } + return null; + } + } + + /** + * month cycle + */ + public static class MonthCycle extends AbstractCycle { + + public MonthCycle(Cron cron) { + super(cron); + } + + @Override + protected CycleEnum getCycle() { + boolean flag = (minFiledIsSetAll() + && hourFiledIsSetAll() + && dayOfMonthFieldIsSetAll() + && dayOfWeekField.getExpression() instanceof QuestionMark + && monthFieldIsEvery()) || + (minFiledIsSetAll() + && hourFiledIsSetAll() + && dayOfMonthField.getExpression() instanceof QuestionMark + && dayofWeekFieldIsSetAll() + && monthFieldIsEvery()); + if (flag) { + return CycleEnum.MONTH; + } + + return null; + } + + @Override + protected CycleEnum getMiniCycle() { + if (monthFieldIsEvery()) { + return CycleEnum.MONTH; + } + + return null; + } + } + + /** + * week cycle + */ + public static class WeekCycle extends AbstractCycle { + public WeekCycle(Cron cron) { + super(cron); + } + + @Override + protected CycleEnum getCycle() { + if (minFiledIsSetAll() + && hourFiledIsSetAll() + && dayOfMonthField.getExpression() instanceof QuestionMark + && dayofWeekFieldIsEvery() + && monthField.getExpression() instanceof Always) { + return CycleEnum.WEEK; + } + + return null; + } + + @Override + protected CycleEnum getMiniCycle() { + if (dayofWeekFieldIsEvery()) { + return CycleEnum.WEEK; + } + + return null; + } + } +} diff --git a/escheduler-dao/src/main/java/cn/escheduler/dao/utils/cron/CycleLinks.java b/escheduler-dao/src/main/java/cn/escheduler/dao/utils/cron/CycleLinks.java new file mode 100644 index 0000000000..3447e267ca --- /dev/null +++ b/escheduler-dao/src/main/java/cn/escheduler/dao/utils/cron/CycleLinks.java @@ -0,0 +1,64 @@ +/* + * 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.dao.utils.cron; + +import cn.escheduler.common.enums.CycleEnum; +import com.cronutils.model.Cron; + +import java.util.ArrayList; +import java.util.List; + +/** + * 链接判断工具 + */ +public class CycleLinks extends AbstractCycle { + private final List cycleList = new ArrayList<>(); + + public CycleLinks(Cron cron) { + super(cron); + } + + @Override + public CycleLinks addCycle(AbstractCycle cycle) { + cycleList.add(cycle); + return this; + } + + @Override + protected CycleEnum getCycle() { + for (AbstractCycle abstractCycle : cycleList) { + CycleEnum cycle = abstractCycle.getCycle(); + if (cycle != null) { + return cycle; + } + } + + return null; + } + + @Override + protected CycleEnum getMiniCycle() { + for (AbstractCycle cycleHelper : cycleList) { + CycleEnum cycle = cycleHelper.getMiniCycle(); + if (cycle != null) { + return cycle; + } + } + + return null; + } +} \ No newline at end of file diff --git a/escheduler-dao/src/main/resources/dao/data_source.properties b/escheduler-dao/src/main/resources/dao/data_source.properties new file mode 100644 index 0000000000..cac3aa5e20 --- /dev/null +++ b/escheduler-dao/src/main/resources/dao/data_source.properties @@ -0,0 +1,53 @@ +# base spring data source configuration +spring.datasource.type=com.alibaba.druid.pool.DruidDataSource +spring.datasource.driver-class-name=com.mysql.jdbc.Driver +spring.datasource.url=jdbc:mysql://192.168.xx.xx:3306/escheduler?characterEncoding=UTF-8 +spring.datasource.username=xx +spring.datasource.password=xx + +# connection configuration +spring.datasource.initialSize=5 +# min connection number +spring.datasource.minIdle=5 +# max connection number +spring.datasource.maxActive=50 + +# max wait time for get a connection in milliseconds. if configuring maxWait, fair locks are enabled by default and concurrency efficiency decreases. +# If necessary, unfair locks can be used by configuring the useUnfairLock attribute to true. +spring.datasource.maxWait=60000 + +# milliseconds for check to close free connections +spring.datasource.timeBetweenEvictionRunsMillis=60000 + +# the Destroy thread detects the connection interval and closes the physical connection in milliseconds if the connection idle time is greater than or equal to minEvictableIdleTimeMillis. +spring.datasource.timeBetweenConnectErrorMillis=60000 + +# the longest time a connection remains idle without being evicted, in milliseconds +spring.datasource.minEvictableIdleTimeMillis=300000 + +#the SQL used to check whether the connection is valid requires a query statement. If validation Query is null, testOnBorrow, testOnReturn, and testWhileIdle will not work. +spring.datasource.validationQuery=SELECT 1 +#check whether the connection is valid for timeout, in seconds +spring.datasource.validationQueryTimeout=3 + +# when applying for a connection, if it is detected that the connection is idle longer than time Between Eviction Runs Millis, +# validation Query is performed to check whether the connection is valid +spring.datasource.testWhileIdle=true + +#execute validation to check if the connection is valid when applying for a connection +spring.datasource.testOnBorrow=true +#execute validation to check if the connection is valid when the connection is returned +spring.datasource.testOnReturn=false +spring.datasource.defaultAutoCommit=true +spring.datasource.keepAlive=true + +# open PSCache, specify count PSCache for every connection +spring.datasource.poolPreparedStatements=true +spring.datasource.maxPoolPreparedStatementPerConnectionSize=20 + +# data quality analysis is not currently in use. please ignore the following configuration +# task record flag +task.record.flag=false +task.record.datasource.url=jdbc:mysql://192.168.xx.xx:3306/etl?characterEncoding=UTF-8 +task.record.datasource.username=xx +task.record.datasource.password=xx \ No newline at end of file diff --git a/escheduler-dao/src/test/java/cn/escheduler/dao/ProcessDaoTest.java b/escheduler-dao/src/test/java/cn/escheduler/dao/ProcessDaoTest.java new file mode 100644 index 0000000000..c5c9f1ba18 --- /dev/null +++ b/escheduler-dao/src/test/java/cn/escheduler/dao/ProcessDaoTest.java @@ -0,0 +1,32 @@ +/* + * 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.dao; + +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; + +public class ProcessDaoTest { + + + @Autowired + ProcessDao processDao; + + @Test + public void test(){ + } + +} \ No newline at end of file diff --git a/escheduler-dao/src/test/java/cn/escheduler/dao/cron/CronUtilsTest.java b/escheduler-dao/src/test/java/cn/escheduler/dao/cron/CronUtilsTest.java new file mode 100644 index 0000000000..3c1ff978f1 --- /dev/null +++ b/escheduler-dao/src/test/java/cn/escheduler/dao/cron/CronUtilsTest.java @@ -0,0 +1,181 @@ +/* + * 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.dao.cron; + +import cn.escheduler.common.enums.CycleEnum; +import cn.escheduler.dao.utils.cron.CronUtils; +import com.cronutils.builder.CronBuilder; +import com.cronutils.model.Cron; +import com.cronutils.model.CronType; +import com.cronutils.model.definition.CronDefinitionBuilder; +import com.cronutils.model.field.CronField; +import com.cronutils.model.field.CronFieldName; +import com.cronutils.model.field.expression.*; +import org.junit.Assert; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.text.ParseException; + +import static com.cronutils.model.field.expression.FieldExpressionFactory.*; + +/** + */ +public class CronUtilsTest { + + private static final Logger logger = LoggerFactory.getLogger(CronUtilsTest.class); + + @Test + public void cronAsStringTest() { + Cron cron = CronBuilder.cron(CronDefinitionBuilder.instanceDefinitionFor(CronType.QUARTZ)) + .withYear(always()) + .withDoW(questionMark()) + .withMonth(always()) + .withDoM(always()) + .withHour(always()) + .withMinute(every(5)) + .withSecond(on(0)) + .instance(); + // Obtain the string expression + String cronAsString = cron.asString(); // 0 */5 * * * ? * 每5分钟一次 + + Assert.assertEquals(cronAsString, "0 */5 * * * ? *"); + + } + + + @Test + public void testParse() throws ParseException { + String strCrontab = "0 1 2 3 * ? *"; + Cron depCron = CronUtils.parse2Cron(strCrontab); + Assert.assertEquals(depCron.retrieve(CronFieldName.SECOND).getExpression().asString(), "0"); + Assert.assertEquals(depCron.retrieve(CronFieldName.MINUTE).getExpression().asString(), "1"); + Assert.assertEquals(depCron.retrieve(CronFieldName.HOUR).getExpression().asString(), "2"); + Assert.assertEquals(depCron.retrieve(CronFieldName.DAY_OF_MONTH).getExpression().asString(), "3"); + Assert.assertEquals(depCron.retrieve(CronFieldName.MONTH).getExpression().asString(), "*"); + Assert.assertEquals(depCron.retrieve(CronFieldName.YEAR).getExpression().asString(), "*"); + } + + @Test + public void testParse1() throws ParseException { + String strCrontab = "* * 0/1 * * ? *"; + strCrontab = "0/50 0/59 * * * ? *"; + strCrontab = "3/5 * 0/5 * * ? *"; + strCrontab = "1/5 3/5 1/5 3/30 * ? *"; + Cron depCron = CronUtils.parse2Cron(strCrontab); + logger.info(depCron.validate().asString()); + } + + @Test + public void scheduleTypeTest() throws ParseException { + + CycleEnum cycleEnum = CronUtils.getMaxCycle("0 */1 * * * ? *"); + Assert.assertEquals(cycleEnum.name(), "MINUTE"); + + CycleEnum cycleEnum2 = CronUtils.getMaxCycle("0 * * * * ? *"); + Assert.assertEquals(cycleEnum2.name(), "MINUTE"); + } + + @Test + public void test2(){ + Cron cron1 = CronBuilder.cron(CronDefinitionBuilder.instanceDefinitionFor(CronType.QUARTZ)) + .withYear(always()) + .withDoW(questionMark()) + .withMonth(always()) + .withDoM(always()) + .withHour(always()) + .withMinute(every(5)) + .withSecond(on(0)) + .instance(); + + String cronAsString = cron1.asString(); // 0 */5 * * * ? * 每5分钟一次 + //logger.info(cronAsString); + // Obtain the string expression + //String minCrontab = "0 0 * * * ? *"; + //String minCrontab = "0 0 10,14,16 * * ?"; + //String minCrontab = "0 0-5 14 * * ? *"; + //String minCrontab = "0 0 2 ? * SUN *"; + //String minCrontab = "* 0,3 2 SUN * 1#1 *"; + //String minCrontab = "* 0,3 * 1W * ? *"; + //cron = CronUtils.parse2Cron("0 * * * * ? *"); + // 月份周期 + /*String[] cronArayy = new String[]{"* 0,3 * 1W * ? *","* 0 0 1W * ? *", + "0 0 0 L 3/5 ? *","0 0 0 ? 3/5 2/2 *"};*/ + // 分钟周期 + String[] cronArayy = new String[]{"* * * * * ? *","* 0 * * * ? *", + "* 5 * * 3/5 ? *","0 0 * * * ? *"}; + // 周周期 + /*String[] cronArayy = new String[]{"* * * ? * 2/1 *","0 *//*5 * ? * 2/1 *", + "* * *//*5 ? * 2/1 *"};*/ + for(String minCrontab:cronArayy){ + if (!org.quartz.CronExpression.isValidExpression(minCrontab)) { + throw new RuntimeException(minCrontab+"验证失败,表达式无效"); + } + Cron cron = CronUtils.parse2Cron(minCrontab); + CronField minField = cron.retrieve(CronFieldName.MINUTE); + logger.info("minField instanceof Between:"+(minField.getExpression() instanceof Between)); + logger.info("minField instanceof Every:"+(minField.getExpression() instanceof Every)); + logger.info("minField instanceof Always:" + (minField.getExpression() instanceof Always)); + logger.info("minField instanceof On:"+(minField.getExpression() instanceof On)); + logger.info("minField instanceof And:"+(minField.getExpression() instanceof And)); + CronField hourField = cron.retrieve(CronFieldName.HOUR); + logger.info("hourField instanceof Between:"+(hourField.getExpression() instanceof Between)); + logger.info("hourField instanceof Always:"+(hourField.getExpression() instanceof Always)); + logger.info("hourField instanceof Every:"+(hourField.getExpression() instanceof Every)); + logger.info("hourField instanceof On:"+(hourField.getExpression() instanceof On)); + logger.info("hourField instanceof And:"+(hourField.getExpression() instanceof And)); + + CronField dayOfMonthField = cron.retrieve(CronFieldName.DAY_OF_MONTH); + logger.info("dayOfMonthField instanceof Between:"+(dayOfMonthField.getExpression() instanceof Between)); + logger.info("dayOfMonthField instanceof Always:"+(dayOfMonthField.getExpression() instanceof Always)); + logger.info("dayOfMonthField instanceof Every:"+(dayOfMonthField.getExpression() instanceof Every)); + logger.info("dayOfMonthField instanceof On:"+(dayOfMonthField.getExpression() instanceof On)); + logger.info("dayOfMonthField instanceof And:"+(dayOfMonthField.getExpression() instanceof And)); + logger.info("dayOfMonthField instanceof QuestionMark:"+(dayOfMonthField.getExpression() instanceof QuestionMark)); + + CronField monthField = cron.retrieve(CronFieldName.MONTH); + logger.info("monthField instanceof Between:"+(monthField.getExpression() instanceof Between)); + logger.info("monthField instanceof Always:"+(monthField.getExpression() instanceof Always)); + logger.info("monthField instanceof Every:"+(monthField.getExpression() instanceof Every)); + logger.info("monthField instanceof On:"+(monthField.getExpression() instanceof On)); + logger.info("monthField instanceof And:"+(monthField.getExpression() instanceof And)); + logger.info("monthField instanceof QuestionMark:"+(monthField.getExpression() instanceof QuestionMark)); + + CronField dayOfWeekField = cron.retrieve(CronFieldName.DAY_OF_WEEK); + logger.info("dayOfWeekField instanceof Between:"+(dayOfWeekField.getExpression() instanceof Between)); + logger.info("dayOfWeekField instanceof Always:"+(dayOfWeekField.getExpression() instanceof Always)); + logger.info("dayOfWeekField instanceof Every:"+(dayOfWeekField.getExpression() instanceof Every)); + logger.info("dayOfWeekField instanceof On:"+(dayOfWeekField.getExpression() instanceof On)); + logger.info("dayOfWeekField instanceof And:"+(dayOfWeekField.getExpression() instanceof And)); + logger.info("dayOfWeekField instanceof QuestionMark:"+(dayOfWeekField.getExpression() instanceof QuestionMark)); + + CronField yearField = cron.retrieve(CronFieldName.YEAR); + + //CycleEnum cycleEnum = CronUtils.getMaxCycle("0 * * * * ? *"); + CycleEnum cycleEnum = CronUtils.getMaxCycle(minCrontab); + if(cycleEnum !=null){ + logger.info(cycleEnum.name()); + }else{ + logger.info("无法获取到scheduleType"); + } + } + + + + } +} diff --git a/escheduler-dao/src/test/java/cn/escheduler/dao/mapper/AlertGroupMapperTest.java b/escheduler-dao/src/test/java/cn/escheduler/dao/mapper/AlertGroupMapperTest.java new file mode 100644 index 0000000000..1ef3d8e5d7 --- /dev/null +++ b/escheduler-dao/src/test/java/cn/escheduler/dao/mapper/AlertGroupMapperTest.java @@ -0,0 +1,59 @@ +/* + * 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.dao.mapper; + +import cn.escheduler.common.enums.AlertType; +import cn.escheduler.dao.datasource.ConnectionFactory; +import cn.escheduler.dao.model.AlertGroup; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.util.Date; + +public class AlertGroupMapperTest { + + + AlertGroupMapper alertGroupMapper; + + + @Before + public void before(){ + alertGroupMapper = ConnectionFactory.getSqlSession().getMapper(AlertGroupMapper.class); + } + + + @Test + public void testMapper(){ + AlertGroup alertGroup = new AlertGroup(); + alertGroup.setGroupName("alert group test"); + alertGroup.setDesc("alert group test"); + alertGroup.setGroupType(AlertType.EMAIL); + alertGroup.setUpdateTime(new Date()); + alertGroup.setCreateTime(new Date()); + alertGroupMapper.insert(alertGroup); + Assert.assertNotEquals(alertGroup.getId(), 0); + alertGroup.setDesc("test alert group"); + alertGroupMapper.update(alertGroup); + alertGroup = alertGroupMapper.queryById(alertGroup.getId()); + Assert.assertEquals(alertGroup.getDesc(), "test alert group"); + int delete = alertGroupMapper.delete(alertGroup.getId()); + Assert.assertEquals(delete, 1); + + } + +} diff --git a/escheduler-dao/src/test/java/cn/escheduler/dao/mapper/AlertMapperTest.java b/escheduler-dao/src/test/java/cn/escheduler/dao/mapper/AlertMapperTest.java new file mode 100644 index 0000000000..fc5c82fda1 --- /dev/null +++ b/escheduler-dao/src/test/java/cn/escheduler/dao/mapper/AlertMapperTest.java @@ -0,0 +1,62 @@ +/* + * 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.dao.mapper; + +import cn.escheduler.common.enums.AlertStatus; +import cn.escheduler.common.enums.AlertType; +import cn.escheduler.common.enums.ShowType; +import cn.escheduler.dao.datasource.ConnectionFactory; +import cn.escheduler.dao.model.Alert; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.util.Date; + +public class AlertMapperTest { + + + AlertMapper alertMapper; + + @Before + public void before(){ + alertMapper = ConnectionFactory.getSqlSession().getMapper(AlertMapper.class); + } + + @Test + public void testMapper(){ + Alert alert = new Alert(); + alert.setAlertType(AlertType.EMAIL); + alert.setContent("content test "); + alert.setShowType(ShowType.TABLE); + alert.setTitle("alert test"); + alert.setAlertGroupId(1); + alert.setCreateTime(new Date()); + alert.setUpdateTime(new Date()); + alert.setAlertStatus(AlertStatus.WAIT_EXECUTION); + alertMapper.insert(alert); + Assert.assertNotEquals(alert.getId(), 0); + + alert.setTitle("alert title"); + int update = alertMapper.update(AlertStatus.EXECUTION_SUCCESS, "execute successfully", + new Date(), alert.getId()); + + Assert.assertEquals(update, 1); + int delete = alertMapper.delete(alert.getId()); + Assert.assertEquals(delete, 1); + } +} diff --git a/escheduler-dao/src/test/java/cn/escheduler/dao/mapper/CommandMapperTest.java b/escheduler-dao/src/test/java/cn/escheduler/dao/mapper/CommandMapperTest.java new file mode 100644 index 0000000000..cb02321e32 --- /dev/null +++ b/escheduler-dao/src/test/java/cn/escheduler/dao/mapper/CommandMapperTest.java @@ -0,0 +1,70 @@ +/* + * 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.dao.mapper; + +import cn.escheduler.common.enums.CommandType; +import cn.escheduler.common.enums.FailureStrategy; +import cn.escheduler.common.enums.TaskDependType; +import cn.escheduler.common.enums.WarningType; +import cn.escheduler.dao.datasource.ConnectionFactory; +import cn.escheduler.dao.model.Command; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.util.List; + +public class CommandMapperTest { + + CommandMapper commandMapper; + + + @Before + public void before(){ + commandMapper = ConnectionFactory.getSqlSession().getMapper(CommandMapper.class); + } + + @Test + public void testMapper(){ + + Command command = new Command(); + command.setCommandType(CommandType.START_PROCESS); + command.setProcessDefinitionId(1); + command.setExecutorId(10); + command.setFailureStrategy(FailureStrategy.CONTINUE); + command.setWarningType(WarningType.NONE); + command.setWarningGroupId(1); + command.setTaskDependType(TaskDependType.TASK_POST); + commandMapper.insert(command); + Assert.assertNotEquals(command.getId(), 0); + + command.setCommandParam("command parameter test"); + int update = commandMapper.update(command); + Assert.assertEquals(update, 1); + + int delete = commandMapper.delete(command.getId()); + Assert.assertEquals(delete, 1); + } + + @Test + public void testQuery(){ + List commandList = commandMapper.queryAllCommand(); + Assert.assertNotEquals(commandList, null); + } + + +} diff --git a/escheduler-dao/src/test/java/cn/escheduler/dao/mapper/DataSourceMapperTest.java b/escheduler-dao/src/test/java/cn/escheduler/dao/mapper/DataSourceMapperTest.java new file mode 100644 index 0000000000..c49b776bbd --- /dev/null +++ b/escheduler-dao/src/test/java/cn/escheduler/dao/mapper/DataSourceMapperTest.java @@ -0,0 +1,67 @@ +/* + * 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.dao.mapper; + +import cn.escheduler.common.enums.DbType; +import cn.escheduler.dao.datasource.ConnectionFactory; +import cn.escheduler.dao.model.DataSource; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.util.Date; +import java.util.List; + +public class DataSourceMapperTest { + + + DataSourceMapper dataSourceMapper; + + @Before + public void before(){ + dataSourceMapper = ConnectionFactory.getSqlSession().getMapper(DataSourceMapper.class); + } + + + @Test + public void testMapper(){ + + DataSource dataSource = new DataSource(); + dataSource.setType(DbType.MYSQL); + dataSource.setName("data source"); + dataSource.setConnectionParams("connections"); + dataSource.setNote("mysql test"); + dataSource.setCreateTime(new Date()); + dataSource.setUpdateTime(new Date()); + + dataSourceMapper.insert(dataSource); + Assert.assertNotEquals(dataSource.getId(), 0); + + List dataSources = dataSourceMapper.queryAllDataSourcePaging("", 0, 30); + DataSource findDataSource = null; + for(DataSource dataSource1 : dataSources){ + if(dataSource1.getId() == dataSource.getId()){ + findDataSource = dataSource1; + } + } + + Assert.assertNotEquals(findDataSource, null); + int delete = dataSourceMapper.deleteDataSourceById(dataSource.getId()); + Assert.assertEquals(delete, 1); + + } +} diff --git a/escheduler-dao/src/test/java/cn/escheduler/dao/mapper/MasterServerMapperTest.java b/escheduler-dao/src/test/java/cn/escheduler/dao/mapper/MasterServerMapperTest.java new file mode 100644 index 0000000000..9f66069eeb --- /dev/null +++ b/escheduler-dao/src/test/java/cn/escheduler/dao/mapper/MasterServerMapperTest.java @@ -0,0 +1,74 @@ +/* + * 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.dao.mapper; + +import cn.escheduler.dao.datasource.ConnectionFactory; +import cn.escheduler.dao.model.MasterServer; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +import java.util.Date; +import java.util.List; + +@SpringBootTest +public class MasterServerMapperTest { + + @Autowired + MasterServerMapper masterServerMapper; + + @Before + public void before(){ + masterServerMapper =ConnectionFactory.getSqlSession().getMapper(MasterServerMapper.class); + } + + @Test + public void queryAllMaster() { + + MasterServer masterServer = new MasterServer(); + String host = "127.22.2.1"; + masterServer.setHost(host); + masterServer.setLastHeartbeatTime(new Date()); + masterServer.setPort(19282); + masterServer.setCreateTime(new Date()); + masterServer.setZkDirectory("/root"); + + masterServerMapper.insert(masterServer); + Assert.assertNotEquals(masterServer.getId(), 0); + + masterServer.setPort(12892); + int update = masterServerMapper.update(masterServer); + Assert.assertEquals(update, 1); + List masterServers = masterServerMapper.queryAllMaster(); + + MasterServer findMaster = null; + for(MasterServer master : masterServers){ + if(master.getId() == masterServer.getId()){ + findMaster = master; + } + } + Assert.assertNotEquals(findMaster, null); + + int delete = masterServerMapper.deleteWorkerByHost(host); + Assert.assertEquals(delete, 1); + + + } + +} \ No newline at end of file diff --git a/escheduler-dao/src/test/java/cn/escheduler/dao/mapper/ProcessDefinitionMapperTest.java b/escheduler-dao/src/test/java/cn/escheduler/dao/mapper/ProcessDefinitionMapperTest.java new file mode 100644 index 0000000000..fb0a8421f5 --- /dev/null +++ b/escheduler-dao/src/test/java/cn/escheduler/dao/mapper/ProcessDefinitionMapperTest.java @@ -0,0 +1,76 @@ +/* + * 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.dao.mapper; + +import cn.escheduler.common.enums.Flag; +import cn.escheduler.dao.datasource.ConnectionFactory; +import cn.escheduler.dao.model.ProcessDefinition; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.util.Date; +import java.util.List; + +public class ProcessDefinitionMapperTest { + + + ProcessDefinitionMapper processDefinitionMapper; + + + @Before + public void before(){ + processDefinitionMapper = ConnectionFactory.getSqlSession().getMapper(ProcessDefinitionMapper.class); + } + @Test + public void testMapper() { + ProcessDefinition processDefinition = new ProcessDefinition(); + + processDefinition.setProcessDefinitionJson("json field"); + + processDefinition.setName("test"); + processDefinition.setConnects("[]"); + processDefinition.setLocations("[]"); + processDefinition.setFlag(Flag.YES); + processDefinition.setDesc("test"); + processDefinition.setProjectId(1024); + processDefinition.setUpdateTime(new Date()); + processDefinition.setCreateTime(new Date()); + + processDefinitionMapper.insert(processDefinition); + Assert.assertNotEquals(processDefinition.getId(), 0); + processDefinition.setName("test definition"); + int update = processDefinitionMapper.update(processDefinition); + Assert.assertEquals(update, 1); + + ProcessDefinition findProcess = null; + List processDefinitionList = processDefinitionMapper.queryAllDefinitionList(1024); + for(ProcessDefinition processDefinition1 : processDefinitionList){ + if(processDefinition1.getId() == processDefinition.getId()){ + findProcess = processDefinition1; + break; + } + } + Assert.assertNotEquals(findProcess, null); + + int delete = processDefinitionMapper.delete(processDefinition.getId()); + Assert.assertEquals(delete, 1); + + + } + +} \ No newline at end of file diff --git a/escheduler-dao/src/test/java/cn/escheduler/dao/mapper/TenantMapperTest.java b/escheduler-dao/src/test/java/cn/escheduler/dao/mapper/TenantMapperTest.java new file mode 100644 index 0000000000..7fd791efa2 --- /dev/null +++ b/escheduler-dao/src/test/java/cn/escheduler/dao/mapper/TenantMapperTest.java @@ -0,0 +1,60 @@ +/* + * 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.dao.mapper; + +import cn.escheduler.dao.datasource.ConnectionFactory; +import cn.escheduler.dao.model.Tenant; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.springframework.transaction.annotation.Transactional; + +import java.util.Date; + +public class TenantMapperTest { + + + TenantMapper tenantMapper; + + @Before + public void before(){ + tenantMapper = ConnectionFactory.getSqlSession().getMapper(TenantMapper.class); + } + + @Test + @Transactional + public void testMapper(){ + + Tenant tenant = new Tenant(); + tenant.setTenantName("大数据平台部"); + tenant.setQueueId(1); + tenant.setCreateTime(new Date()); + tenant.setUpdateTime(new Date()); + tenantMapper.insert(tenant); + Assert.assertNotEquals(tenant.getId(), 0); + tenant.setTenantName("大数据平台部test"); + int update = tenantMapper.update(tenant); + Assert.assertEquals(update, 1); + + tenant = tenantMapper.queryById(tenant.getId()); + Assert.assertEquals(tenant.getTenantName(), "大数据平台部test"); + + int delete = tenantMapper.deleteById(tenant.getId()); + Assert.assertEquals(delete, 1); + } + +} diff --git a/escheduler-dao/src/test/java/cn/escheduler/dao/mapper/UdfFuncMapperTest.java b/escheduler-dao/src/test/java/cn/escheduler/dao/mapper/UdfFuncMapperTest.java new file mode 100644 index 0000000000..ef1ce3106d --- /dev/null +++ b/escheduler-dao/src/test/java/cn/escheduler/dao/mapper/UdfFuncMapperTest.java @@ -0,0 +1,61 @@ +/* + * 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.dao.mapper; + +import cn.escheduler.dao.datasource.ConnectionFactory; +import cn.escheduler.dao.model.Resource; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Date; + +public class UdfFuncMapperTest { + + private final Logger logger = LoggerFactory.getLogger(UdfFuncMapperTest.class); + + ResourceMapper resourceMapper; + UdfFuncMapper udfFuncMapper; + + @Before + public void before(){ + + resourceMapper = ConnectionFactory.getSqlSession().getMapper(ResourceMapper.class); + udfFuncMapper = ConnectionFactory.getSqlSession().getMapper(UdfFuncMapper.class); + } + + @Test + public void testMapper(){ + Resource resource = new Resource(); + resource.setAlias("aa"); + resource.setFileName("aa"); + resource.setDesc("aa"); + resource.setUserId(2); + resource.setCreateTime(new Date()); + resource.setUpdateTime(new Date()); + resourceMapper.insert(resource); + Assert.assertNotEquals(resource.getId(), 0); + resource.setAlias("aa123"); + resourceMapper.update(resource); + resource = resourceMapper.queryResourceById(resource.getId()); + Assert.assertEquals(resource.getAlias(), "aa123"); + int delete = resourceMapper.delete(resource.getId()); + Assert.assertEquals(delete, 1); + } +} \ No newline at end of file diff --git a/escheduler-dao/src/test/java/cn/escheduler/dao/mapper/UserAlertGroupMapperTest.java b/escheduler-dao/src/test/java/cn/escheduler/dao/mapper/UserAlertGroupMapperTest.java new file mode 100644 index 0000000000..8e4c59c2e5 --- /dev/null +++ b/escheduler-dao/src/test/java/cn/escheduler/dao/mapper/UserAlertGroupMapperTest.java @@ -0,0 +1,58 @@ +/* + * 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.dao.mapper; + +import cn.escheduler.dao.datasource.ConnectionFactory; +import cn.escheduler.dao.model.UserAlertGroup; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; + +import java.util.Date; + + +public class UserAlertGroupMapperTest { + + + @Autowired + UserAlertGroupMapper userAlertGroupMapper; + + @Before + public void before(){ + userAlertGroupMapper = ConnectionFactory.getSqlSession().getMapper(UserAlertGroupMapper.class); + } + + @Test + public void testInsert(){ + UserAlertGroup userAlertGroup = new UserAlertGroup(); + userAlertGroup.setUserId(2); + userAlertGroup.setAlertgroupId(10021); + userAlertGroup.setCreateTime(new Date()); + userAlertGroup.setUpdateTime(new Date()); + userAlertGroupMapper.insert(userAlertGroup); + Assert.assertNotEquals(userAlertGroup.getId(), 0); + int delete = userAlertGroupMapper.deleteByAlertgroupId(userAlertGroup.getAlertgroupId()); + Assert.assertEquals(delete, 1); + + + + + } + + +} diff --git a/escheduler-dao/src/test/java/cn/escheduler/dao/mapper/UserMapperTest.java b/escheduler-dao/src/test/java/cn/escheduler/dao/mapper/UserMapperTest.java new file mode 100644 index 0000000000..94ae0ca175 --- /dev/null +++ b/escheduler-dao/src/test/java/cn/escheduler/dao/mapper/UserMapperTest.java @@ -0,0 +1,63 @@ +/* + * 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.dao.mapper; + +import cn.escheduler.common.enums.UserType; +import cn.escheduler.dao.datasource.ConnectionFactory; +import cn.escheduler.dao.model.User; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.util.Date; + + +public class UserMapperTest { + + + UserMapper userMapper; + + @Before + public void before(){ + userMapper = ConnectionFactory.getSqlSession().getMapper(UserMapper.class); + } + + @Test + public void testInsert(){ + User user = new User(); + user.setUserName("Dr.strange"); + user.setUserPassword("1234567890"); + user.setEmail("wwww@123.com"); + user.setPhone("12345678901"); + user.setUserType(UserType.GENERAL_USER); + user.setTenantId(1); + user.setCreateTime(new Date()); + user.setUpdateTime(new Date()); + userMapper.insert(user); + Assert.assertNotEquals(user.getId(), 0); + + user.setUserName("Dr.chemistry"); + int update = userMapper.update(user); + Assert.assertEquals(update, 1); + user = userMapper.queryById(user.getId()); + Assert.assertEquals(user.getUserName(), "Dr.chemistry"); + int delete = userMapper.delete(user.getId()); + Assert.assertEquals(delete, 1); + + } + +}