You can not select more than 25 topics
			Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
		
		
		
		
			
				
					269 lines
				
				12 KiB
			
		
		
			
		
	
	
					269 lines
				
				12 KiB
			| 
											1 year ago
										 | from fastapi import Request | ||
|  | from sqlalchemy.ext.asyncio import AsyncSession | ||
|  | from typing import List | ||
| 
											1 year ago
										 | from config.constant import CommonConstant, JobConstant | ||
| 
											2 years ago
										 | from config.get_scheduler import SchedulerUtil | ||
| 
											1 year ago
										 | from exceptions.exception import ServiceException | ||
| 
											1 year ago
										 | from module_admin.dao.job_dao import JobDao | ||
|  | from module_admin.entity.vo.common_vo import CrudResponseModel | ||
|  | from module_admin.entity.vo.job_vo import DeleteJobModel, EditJobModel, JobModel, JobPageQueryModel | ||
|  | from module_admin.service.dict_service import DictDataService | ||
|  | from utils.common_util import CamelCaseUtil, export_list2excel | ||
| 
											1 year ago
										 | from utils.cron_util import CronUtil | ||
| 
											1 year ago
										 | from utils.string_util import StringUtil | ||
| 
											2 years ago
										 | 
 | ||
|  | 
 | ||
|  | class JobService: | ||
|  |     """
 | ||
|  |     定时任务管理模块服务层 | ||
|  |     """
 | ||
|  | 
 | ||
|  |     @classmethod | ||
| 
											1 year ago
										 |     async def get_job_list_services( | ||
|  |         cls, query_db: AsyncSession, query_object: JobPageQueryModel, is_page: bool = False | ||
|  |     ): | ||
| 
											2 years ago
										 |         """
 | ||
|  |         获取定时任务列表信息service | ||
| 
											1 year ago
										 | 
 | ||
| 
											2 years ago
										 |         :param query_db: orm对象 | ||
|  |         :param query_object: 查询参数对象 | ||
| 
											2 years ago
										 |         :param is_page: 是否开启分页 | ||
| 
											2 years ago
										 |         :return: 定时任务列表信息对象 | ||
|  |         """
 | ||
| 
											1 year ago
										 |         job_list_result = await JobDao.get_job_list(query_db, query_object, is_page) | ||
| 
											2 years ago
										 | 
 | ||
| 
											2 years ago
										 |         return job_list_result | ||
| 
											2 years ago
										 | 
 | ||
| 
											1 year ago
										 |     @classmethod | ||
|  |     async def check_job_unique_services(cls, query_db: AsyncSession, page_object: JobModel): | ||
|  |         """
 | ||
|  |         校验定时任务是否存在service | ||
|  | 
 | ||
|  |         :param query_db: orm对象 | ||
|  |         :param page_object: 定时任务对象 | ||
|  |         :return: 校验结果 | ||
|  |         """
 | ||
|  |         job_id = -1 if page_object.job_id is None else page_object.job_id | ||
|  |         job = await JobDao.get_job_detail_by_info(query_db, page_object) | ||
|  |         if job and job.job_id != job_id: | ||
|  |             return CommonConstant.NOT_UNIQUE | ||
|  |         return CommonConstant.UNIQUE | ||
|  | 
 | ||
| 
											2 years ago
										 |     @classmethod | ||
| 
											1 year ago
										 |     async def add_job_services(cls, query_db: AsyncSession, page_object: JobModel): | ||
| 
											2 years ago
										 |         """
 | ||
|  |         新增定时任务信息service | ||
| 
											1 year ago
										 | 
 | ||
| 
											2 years ago
										 |         :param query_db: orm对象 | ||
|  |         :param page_object: 新增定时任务对象 | ||
|  |         :return: 新增定时任务校验结果 | ||
|  |         """
 | ||
| 
											1 year ago
										 |         if not CronUtil.validate_cron_expression(page_object.cron_expression): | ||
| 
											1 year ago
										 |             raise ServiceException(message=f'新增定时任务{page_object.job_name}失败,Cron表达式不正确') | ||
|  |         elif StringUtil.contains_ignore_case(page_object.invoke_target, CommonConstant.LOOKUP_RMI): | ||
|  |             raise ServiceException(message=f'新增定时任务{page_object.job_name}失败,目标字符串不允许rmi调用') | ||
|  |         elif StringUtil.contains_any_ignore_case( | ||
|  |             page_object.invoke_target, [CommonConstant.LOOKUP_LDAP, CommonConstant.LOOKUP_LDAPS] | ||
|  |         ): | ||
|  |             raise ServiceException(message=f'新增定时任务{page_object.job_name}失败,目标字符串不允许ldap(s)调用') | ||
|  |         elif StringUtil.contains_any_ignore_case( | ||
|  |             page_object.invoke_target, [CommonConstant.HTTP, CommonConstant.HTTPS] | ||
|  |         ): | ||
|  |             raise ServiceException(message=f'新增定时任务{page_object.job_name}失败,目标字符串不允许http(s)调用') | ||
|  |         elif StringUtil.startswith_any_case(page_object.invoke_target, JobConstant.JOB_ERROR_LIST): | ||
|  |             raise ServiceException(message=f'新增定时任务{page_object.job_name}失败,目标字符串存在违规') | ||
|  |         elif not StringUtil.startswith_any_case(page_object.invoke_target, JobConstant.JOB_WHITE_LIST): | ||
|  |             raise ServiceException(message=f'新增定时任务{page_object.job_name}失败,目标字符串不在白名单内') | ||
| 
											1 year ago
										 |         elif not await cls.check_job_unique_services(query_db, page_object): | ||
|  |             raise ServiceException(message=f'新增定时任务{page_object.job_name}失败,定时任务已存在') | ||
| 
											2 years ago
										 |         else: | ||
|  |             try: | ||
| 
											1 year ago
										 |                 add_job = await JobDao.add_job_dao(query_db, page_object) | ||
|  |                 job_info = await cls.job_detail_services(query_db, add_job.job_id) | ||
| 
											2 years ago
										 |                 if job_info.status == '0': | ||
|  |                     SchedulerUtil.add_scheduler_job(job_info=job_info) | ||
| 
											1 year ago
										 |                 await query_db.commit() | ||
| 
											2 years ago
										 |                 result = dict(is_success=True, message='新增成功') | ||
|  |             except Exception as e: | ||
| 
											1 year ago
										 |                 await query_db.rollback() | ||
| 
											2 years ago
										 |                 raise e | ||
|  | 
 | ||
|  |         return CrudResponseModel(**result) | ||
|  | 
 | ||
|  |     @classmethod | ||
| 
											1 year ago
										 |     async def edit_job_services(cls, query_db: AsyncSession, page_object: EditJobModel): | ||
| 
											2 years ago
										 |         """
 | ||
|  |         编辑定时任务信息service | ||
| 
											1 year ago
										 | 
 | ||
| 
											2 years ago
										 |         :param query_db: orm对象 | ||
|  |         :param page_object: 编辑定时任务对象 | ||
|  |         :return: 编辑定时任务校验结果 | ||
|  |         """
 | ||
|  |         edit_job = page_object.model_dump(exclude_unset=True) | ||
|  |         if page_object.type == 'status': | ||
|  |             del edit_job['type'] | ||
| 
											1 year ago
										 |         job_info = await cls.job_detail_services(query_db, page_object.job_id) | ||
| 
											2 years ago
										 |         if job_info: | ||
| 
											1 year ago
										 |             if page_object.type != 'status': | ||
| 
											1 year ago
										 |                 if not CronUtil.validate_cron_expression(page_object.cron_expression): | ||
| 
											1 year ago
										 |                     raise ServiceException(message=f'修改定时任务{page_object.job_name}失败,Cron表达式不正确') | ||
|  |                 elif StringUtil.contains_ignore_case(page_object.invoke_target, CommonConstant.LOOKUP_RMI): | ||
|  |                     raise ServiceException(message=f'修改定时任务{page_object.job_name}失败,目标字符串不允许rmi调用') | ||
|  |                 elif StringUtil.contains_any_ignore_case( | ||
|  |                     page_object.invoke_target, [CommonConstant.LOOKUP_LDAP, CommonConstant.LOOKUP_LDAPS] | ||
|  |                 ): | ||
|  |                     raise ServiceException( | ||
|  |                         message=f'修改定时任务{page_object.job_name}失败,目标字符串不允许ldap(s)调用' | ||
|  |                     ) | ||
|  |                 elif StringUtil.contains_any_ignore_case( | ||
|  |                     page_object.invoke_target, [CommonConstant.HTTP, CommonConstant.HTTPS] | ||
|  |                 ): | ||
|  |                     raise ServiceException( | ||
|  |                         message=f'修改定时任务{page_object.job_name}失败,目标字符串不允许http(s)调用' | ||
|  |                     ) | ||
|  |                 elif StringUtil.startswith_any_case(page_object.invoke_target, JobConstant.JOB_ERROR_LIST): | ||
|  |                     raise ServiceException(message=f'修改定时任务{page_object.job_name}失败,目标字符串存在违规') | ||
|  |                 elif not StringUtil.startswith_any_case(page_object.invoke_target, JobConstant.JOB_WHITE_LIST): | ||
|  |                     raise ServiceException(message=f'修改定时任务{page_object.job_name}失败,目标字符串不在白名单内') | ||
| 
											1 year ago
										 |                 elif not await cls.check_job_unique_services(query_db, page_object): | ||
|  |                     raise ServiceException(message=f'修改定时任务{page_object.job_name}失败,定时任务已存在') | ||
| 
											2 years ago
										 |             try: | ||
| 
											1 year ago
										 |                 await JobDao.edit_job_dao(query_db, edit_job) | ||
| 
											12 months ago
										 |                 SchedulerUtil.remove_scheduler_job(job_id=edit_job.get('job_id')) | ||
| 
											2 years ago
										 |                 if edit_job.get('status') == '0': | ||
| 
											1 year ago
										 |                     job_info = await cls.job_detail_services(query_db, edit_job.get('job_id')) | ||
| 
											2 years ago
										 |                     SchedulerUtil.add_scheduler_job(job_info=job_info) | ||
| 
											1 year ago
										 |                 await query_db.commit() | ||
| 
											1 year ago
										 |                 return CrudResponseModel(is_success=True, message='更新成功') | ||
| 
											2 years ago
										 |             except Exception as e: | ||
| 
											1 year ago
										 |                 await query_db.rollback() | ||
| 
											2 years ago
										 |                 raise e | ||
|  |         else: | ||
| 
											1 year ago
										 |             raise ServiceException(message='定时任务不存在') | ||
| 
											2 years ago
										 | 
 | ||
|  |     @classmethod | ||
| 
											1 year ago
										 |     async def execute_job_once_services(cls, query_db: AsyncSession, page_object: JobModel): | ||
| 
											2 years ago
										 |         """
 | ||
|  |         执行一次定时任务service | ||
| 
											1 year ago
										 | 
 | ||
| 
											2 years ago
										 |         :param query_db: orm对象 | ||
|  |         :param page_object: 定时任务对象 | ||
|  |         :return: 执行一次定时任务结果 | ||
|  |         """
 | ||
| 
											12 months ago
										 |         SchedulerUtil.remove_scheduler_job(job_id=page_object.job_id) | ||
| 
											1 year ago
										 |         job_info = await cls.job_detail_services(query_db, page_object.job_id) | ||
| 
											2 years ago
										 |         if job_info: | ||
|  |             SchedulerUtil.execute_scheduler_job_once(job_info=job_info) | ||
| 
											1 year ago
										 |             return CrudResponseModel(is_success=True, message='执行成功') | ||
| 
											2 years ago
										 |         else: | ||
| 
											1 year ago
										 |             raise ServiceException(message='定时任务不存在') | ||
| 
											2 years ago
										 | 
 | ||
|  |     @classmethod | ||
| 
											1 year ago
										 |     async def delete_job_services(cls, query_db: AsyncSession, page_object: DeleteJobModel): | ||
| 
											2 years ago
										 |         """
 | ||
|  |         删除定时任务信息service | ||
| 
											1 year ago
										 | 
 | ||
| 
											2 years ago
										 |         :param query_db: orm对象 | ||
|  |         :param page_object: 删除定时任务对象 | ||
|  |         :return: 删除定时任务校验结果 | ||
|  |         """
 | ||
| 
											1 year ago
										 |         if page_object.job_ids: | ||
| 
											2 years ago
										 |             job_id_list = page_object.job_ids.split(',') | ||
|  |             try: | ||
|  |                 for job_id in job_id_list: | ||
| 
											1 year ago
										 |                     await JobDao.delete_job_dao(query_db, JobModel(jobId=job_id)) | ||
| 
											12 months ago
										 |                     SchedulerUtil.remove_scheduler_job(job_id=job_id) | ||
| 
											1 year ago
										 |                 await query_db.commit() | ||
| 
											1 year ago
										 |                 return CrudResponseModel(is_success=True, message='删除成功') | ||
| 
											2 years ago
										 |             except Exception as e: | ||
| 
											1 year ago
										 |                 await query_db.rollback() | ||
| 
											2 years ago
										 |                 raise e | ||
|  |         else: | ||
| 
											1 year ago
										 |             raise ServiceException(message='传入定时任务id为空') | ||
| 
											2 years ago
										 | 
 | ||
|  |     @classmethod | ||
| 
											1 year ago
										 |     async def job_detail_services(cls, query_db: AsyncSession, job_id: int): | ||
| 
											2 years ago
										 |         """
 | ||
|  |         获取定时任务详细信息service | ||
| 
											1 year ago
										 | 
 | ||
| 
											2 years ago
										 |         :param query_db: orm对象 | ||
|  |         :param job_id: 定时任务id | ||
|  |         :return: 定时任务id对应的信息 | ||
|  |         """
 | ||
| 
											1 year ago
										 |         job = await JobDao.get_job_detail_by_id(query_db, job_id=job_id) | ||
| 
											1 year ago
										 |         if job: | ||
|  |             result = JobModel(**CamelCaseUtil.transform_result(job)) | ||
|  |         else: | ||
|  |             result = JobModel(**dict()) | ||
| 
											2 years ago
										 | 
 | ||
|  |         return result | ||
|  | 
 | ||
|  |     @staticmethod | ||
|  |     async def export_job_list_services(request: Request, job_list: List): | ||
|  |         """
 | ||
|  |         导出定时任务信息service | ||
| 
											1 year ago
										 | 
 | ||
| 
											2 years ago
										 |         :param request: Request对象 | ||
|  |         :param job_list: 定时任务信息列表 | ||
|  |         :return: 定时任务信息对应excel的二进制数据 | ||
|  |         """
 | ||
|  |         # 创建一个映射字典,将英文键映射到中文键 | ||
|  |         mapping_dict = { | ||
| 
											1 year ago
										 |             'jobId': '任务编码', | ||
|  |             'jobName': '任务名称', | ||
|  |             'jobGroup': '任务组名', | ||
|  |             'jobExecutor': '任务执行器', | ||
|  |             'invokeTarget': '调用目标字符串', | ||
|  |             'jobArgs': '位置参数', | ||
|  |             'jobKwargs': '关键字参数', | ||
|  |             'cronExpression': 'cron执行表达式', | ||
|  |             'misfirePolicy': '计划执行错误策略', | ||
|  |             'concurrent': '是否并发执行', | ||
|  |             'status': '状态', | ||
|  |             'createBy': '创建者', | ||
|  |             'createTime': '创建时间', | ||
|  |             'updateBy': '更新者', | ||
|  |             'updateTime': '更新时间', | ||
|  |             'remark': '备注', | ||
| 
											2 years ago
										 |         } | ||
|  | 
 | ||
|  |         data = job_list | ||
| 
											1 year ago
										 |         job_group_list = await DictDataService.query_dict_data_list_from_cache_services( | ||
|  |             request.app.state.redis, dict_type='sys_job_group' | ||
|  |         ) | ||
| 
											2 years ago
										 |         job_group_option = [dict(label=item.get('dictLabel'), value=item.get('dictValue')) for item in job_group_list] | ||
|  |         job_group_option_dict = {item.get('value'): item for item in job_group_option} | ||
| 
											1 year ago
										 |         job_executor_list = await DictDataService.query_dict_data_list_from_cache_services( | ||
|  |             request.app.state.redis, dict_type='sys_job_executor' | ||
|  |         ) | ||
|  |         job_executor_option = [ | ||
|  |             dict(label=item.get('dictLabel'), value=item.get('dictValue')) for item in job_executor_list | ||
|  |         ] | ||
| 
											2 years ago
										 |         job_executor_option_dict = {item.get('value'): item for item in job_executor_option} | ||
|  | 
 | ||
|  |         for item in data: | ||
|  |             if item.get('status') == '0': | ||
|  |                 item['status'] = '正常' | ||
|  |             else: | ||
|  |                 item['status'] = '暂停' | ||
|  |             if str(item.get('jobGroup')) in job_group_option_dict.keys(): | ||
|  |                 item['jobGroup'] = job_group_option_dict.get(str(item.get('jobGroup'))).get('label') | ||
|  |             if str(item.get('jobExecutor')) in job_executor_option_dict.keys(): | ||
|  |                 item['jobExecutor'] = job_executor_option_dict.get(str(item.get('jobExecutor'))).get('label') | ||
|  |             if item.get('misfirePolicy') == '1': | ||
|  |                 item['misfirePolicy'] = '立即执行' | ||
|  |             elif item.get('misfirePolicy') == '2': | ||
|  |                 item['misfirePolicy'] = '执行一次' | ||
|  |             else: | ||
|  |                 item['misfirePolicy'] = '放弃执行' | ||
|  |             if item.get('concurrent') == '0': | ||
|  |                 item['concurrent'] = '允许' | ||
|  |             else: | ||
|  |                 item['concurrent'] = '禁止' | ||
| 
											1 year ago
										 |         new_data = [ | ||
|  |             {mapping_dict.get(key): value for key, value in item.items() if mapping_dict.get(key)} for item in data | ||
|  |         ] | ||
| 
											2 years ago
										 |         binary_data = export_list2excel(new_data) | ||
|  | 
 | ||
|  |         return binary_data |