diff --git a/dubhe-server/HELP.md b/dubhe-server/HELP.md new file mode 100644 index 0000000..ee42ad0 --- /dev/null +++ b/dubhe-server/HELP.md @@ -0,0 +1,9 @@ +# Getting Started + +### Reference Documentation +For further reference, please consider the following sections: + +* [Official Apache Maven documentation](https://maven.apache.org/guides/index.html) +* [Spring Boot Maven Plugin Reference Guide](https://docs.spring.io/spring-boot/docs/2.4.0/maven-plugin/reference/html/) +* [Create an OCI image](https://docs.spring.io/spring-boot/docs/2.4.0/maven-plugin/reference/html/#build-image) + diff --git a/dubhe-server/admin/pom.xml b/dubhe-server/admin/pom.xml new file mode 100644 index 0000000..f57082d --- /dev/null +++ b/dubhe-server/admin/pom.xml @@ -0,0 +1,154 @@ + + + + server + org.dubhe + 0.0.1-SNAPSHOT + + 4.0.0 + + admin + Admin 系统服务 + + + + org.dubhe.biz + base + ${org.dubhe.biz.base.version} + + + org.dubhe.biz + file + ${org.dubhe.biz.file.version} + + + org.dubhe.biz + data-permission + ${org.dubhe.biz.data-permission.version} + + + org.dubhe.biz + redis + ${org.dubhe.biz.redis.version} + + + + org.dubhe.cloud + registration + ${org.dubhe.cloud.registration.version} + + + + org.dubhe.cloud + configuration + ${org.dubhe.cloud.configuration.version} + + + + org.dubhe.cloud + swagger + ${org.dubhe.cloud.swagger.version} + + + + org.dubhe.biz + data-response + ${org.dubhe.biz.data-response.version} + + + + org.dubhe.cloud + auth-config + ${org.dubhe.cloud.auth-config.version} + + + + org.dubhe.cloud + remote-call + ${org.dubhe.cloud.remote-call.version} + + + + org.dubhe.biz + log + ${org.dubhe.biz.log.version} + + + org.springframework.boot + spring-boot-starter-web + + + + + org.springframework.boot + spring-boot-starter-mail + + + + + + org.mapstruct + mapstruct-jdk8 + ${mapstruct.version} + + + org.mapstruct + mapstruct-processor + ${mapstruct.version} + provided + + + + com.github.whvcse + easy-captcha + ${easy-captcha.version} + + + + org.dubhe + common-recycle + ${org.dubhe.common-recycle.version} + + + + org.dubhe.cloud + unit-test + ${org.dubhe.cloud.unit-test.version} + test + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + org.springframework.boot + spring-boot-maven-plugin + + false + true + exec + + + + + org.apache.maven.plugins + maven-surefire-plugin + + true + + + + + + true + src/main/resources + + + + \ No newline at end of file diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/AdminApplication.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/AdminApplication.java new file mode 100644 index 0000000..d4abdf7 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/AdminApplication.java @@ -0,0 +1,34 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin; + +import org.mybatis.spring.annotation.MapperScan; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + + +/** + * @description Admin启动类 + * @date 2020-12-02 + */ +@SpringBootApplication(scanBasePackages = "org.dubhe") +@MapperScan(basePackages = {"org.dubhe.**.dao"}) +public class AdminApplication { + public static void main(String[] args) { + SpringApplication.run(AdminApplication.class, args); + } +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/client/AuthServiceClient.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/client/AuthServiceClient.java new file mode 100644 index 0000000..ae26325 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/client/AuthServiceClient.java @@ -0,0 +1,54 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.client; + +import org.dubhe.admin.client.fallback.AuthServiceFallback; +import org.dubhe.biz.base.constant.ApplicationNameConst; +import org.dubhe.biz.base.dto.Oauth2TokenDTO; +import org.dubhe.biz.base.vo.DataResponseBody; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestParam; + +import java.util.Map; + +/** + * @description feign调用demo + * @date 2020-11-04 + */ +@FeignClient(value = ApplicationNameConst.SERVER_AUTHORIZATION,fallback = AuthServiceFallback.class) +public interface AuthServiceClient { + + /** + * 获取token + * + * @param parameters 获取token请求map + * @return token 信息 + */ + @PostMapping(value = "/oauth/token") + DataResponseBody postAccessToken(@RequestParam Map parameters); + + /** + * 登出 + * @param accessToken token + * @return + */ + @DeleteMapping(value="/oauth/logout") + DataResponseBody logout(@RequestParam("token")String accessToken); + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/client/fallback/AuthServiceFallback.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/client/fallback/AuthServiceFallback.java new file mode 100644 index 0000000..5aa0c78 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/client/fallback/AuthServiceFallback.java @@ -0,0 +1,55 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.client.fallback; + +import org.dubhe.admin.client.AuthServiceClient; +import org.dubhe.biz.base.vo.DataResponseBody; +import org.dubhe.biz.dataresponse.factory.DataResponseFactory; +import org.springframework.stereotype.Component; + +import java.util.Map; + +/** + * @description Feign 熔断处理类 + * @date 2020-11-04 + */ +@Component +public class AuthServiceFallback implements AuthServiceClient { + + + /** + * 获取token + * + * @param parameters 获取token请求map + * @return token 信息 + */ + @Override + public DataResponseBody postAccessToken(Map parameters) { + return DataResponseFactory.failed("call auth server postAccessToken error "); + } + + /** + * 退出登录 + * + * @param accessToken token + * @return + */ + @Override + public DataResponseBody logout(String accessToken) { + return DataResponseFactory.failed("call auth server logout error "); + } +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/dao/AuthCodeMapper.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/dao/AuthCodeMapper.java new file mode 100644 index 0000000..f93973d --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/dao/AuthCodeMapper.java @@ -0,0 +1,105 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.dao; + +import com.baomidou.mybatisplus.core.conditions.Wrapper; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.apache.ibatis.annotations.*; +import org.apache.ibatis.mapping.FetchType; +import org.dubhe.admin.domain.entity.*; + +import java.util.List; +import java.util.Set; + +/** + * @description 权限组mapper接口 + * @date 2021-05-14 + */ +public interface AuthCodeMapper extends BaseMapper { + + + /** + * 根据角色id查询对应的权限组 + * + * @param queryWrapper role的wrapper对象 + * @return 角色集合 + */ + @Select("select * from role ${ew.customSqlSegment}") + @Results(id = "roleMapperResults", + value = { + @Result(property = "id", column = "id"), + @Result(property = "auths", + column = "id", + many = @Many(select = "org.dubhe.admin.dao.AuthCodeMapper.selectByRoleId", fetchType = FetchType.LAZY))}) + List selectCollList(@Param("ew") Wrapper queryWrapper); + + + /** + * 给权限组绑定具体的权限 + * + * @param list 权限列表 + */ + void tiedWithPermission(List list); + + /** + * 清空指定权限组的权限 + * + * @param authId 权限组id + */ + @Delete("delete from auth_permission where auth_id=#{authId} ") + void untiedWithPermission(Long authId); + + @Delete("") + void untiedByPermissionId(@Param("ids") Set ids); + + /** + * 绑定角色权限 + * + * @param roleAuths 角色权限关联DTO + */ + void tiedRoleAuth(List roleAuths); + + /** + * 根据角色ID解绑角色权限 + * + * @param roleId 角色ID + */ + @Update("delete from roles_auth where role_id = #{roleId}") + void untiedRoleAuthByRoleId(Long roleId); + + /** + * 通过权限组id获取权限 + * + * @param authId 权限组id + * @return List 权限列表 + */ + @Select("select * from permission where id in (select permission_id from auth_permission where auth_id=#{authId}) and deleted=0 order by id") + List getPermissionByAuthId(Long authId); + + /** + * 根据角色id获取绑定的权限组列表 + * + * @param roleId 角色id + * @return 权限组列表 + */ + @Select("select * from auth where id in (select auth_id from roles_auth where role_id=#{roleId}) and deleted=0") + List selectByRoleId(long roleId); + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/dao/DataSequenceMapper.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/dao/DataSequenceMapper.java new file mode 100644 index 0000000..5930a41 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/dao/DataSequenceMapper.java @@ -0,0 +1,59 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * Licensed 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 org.dubhe.admin.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; +import org.apache.ibatis.annotations.Update; +import org.dubhe.admin.domain.entity.DataSequence; + +/** + * @description 数据序列 Mapper + * @date 2020-09-23 + */ +public interface DataSequenceMapper extends BaseMapper { + /** + * 根据业务编码查询序列 + * @param businessCode 业务编码 + * @return DataSequence 序号 + */ + @Select("select id, business_code ,start, step from data_sequence where business_code = #{businessCode} for update") + DataSequence selectByBusiness(String businessCode); + + /** + * 根据业务编码更新序列起始值 + * @param businessCode 业务编码 + * @return DataSequence 序号 + */ + @Update("update data_sequence set start = start + step where business_code = #{businessCode} ") + int updateStartByBusinessCode(String businessCode); + + /** + * 查询存在表的记录数 + * @param tableName 表名 + * @return int 查询表记录数 + */ + @Select("select count(1) from ${tableName}") + int checkTableExist(@Param("tableName") String tableName); + + /** + * 执行创建表 + * @param tableName 新表表名 + * @param oldTableName 模板表表名 + */ + @Update({"CREATE TABLE ${tableName} like ${oldTableName}"}) + void createNewTable(@Param("tableName") String tableName, @Param("oldTableName") String oldTableName); + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/dao/DictDetailMapper.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/dao/DictDetailMapper.java new file mode 100644 index 0000000..c63f0b5 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/dao/DictDetailMapper.java @@ -0,0 +1,59 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.apache.ibatis.annotations.Select; +import org.apache.ibatis.annotations.Update; +import org.dubhe.admin.domain.entity.DictDetail; + +import java.io.Serializable; +import java.util.List; + +/** + * @description 字典详情 mapper + * @date 2020-03-26 + */ +public interface DictDetailMapper extends BaseMapper { + /** + * 根据字典ID查找 + * + * @param dictId + * @return + */ + @Select("select * from dict_detail where dict_id =#{dictId} order by sort") + List selectByDictId(Serializable dictId); + + /** + * 根据字典ID和标签查找 + * + * @param dictId + * @param label + * @return + */ + @Select("select * from dict_detail where dict_id=#{dictId} and label=#{label}") + DictDetail selectByDictIdAndLabel(Serializable dictId, String label); + + /** + * 根据字典ID删除 + * + * @param dictId + * @return + */ + @Update("delete from dict_detail where dict_id =#{dictId}") + int deleteByDictId(Serializable dictId); +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/dao/DictMapper.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/dao/DictMapper.java new file mode 100644 index 0000000..587f3da --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/dao/DictMapper.java @@ -0,0 +1,81 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.dao; + +import com.baomidou.mybatisplus.core.conditions.Wrapper; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.apache.ibatis.annotations.*; +import org.apache.ibatis.mapping.FetchType; +import org.dubhe.admin.domain.entity.Dict; + +import java.io.Serializable; +import java.util.List; + +/** + * @description 字典 mapper + * @date 2020-03-26 + */ +public interface DictMapper extends BaseMapper { + /** + * 查询实体及关联对象 + * + * @param queryWrapper 字典wrapper对象 + * @return 字典列表 + */ + @Select("select * from dict ${ew.customSqlSegment}") + @Results(id = "dictMapperResults", + value = { + @Result(property = "id", column = "id"), + @Result(property = "dictDetails", + column = "id", + many = @Many(select = "org.dubhe.admin.dao.DictDetailMapper.selectByDictId", + fetchType = FetchType.LAZY))}) + List selectCollList(@Param("ew") Wrapper queryWrapper); + + /** + * 分页查询实体及关联对象 + * + * @param page 分页对象 + * @param queryWrapper 字典wrapper对象 + * @return 分页字典集合 + */ + @Select("select * from dict ${ew.customSqlSegment}") + @ResultMap(value = "dictMapperResults") + IPage selectCollPage(Page page, @Param("ew") Wrapper queryWrapper); + + /** + * 根据ID查询实体及关联对象 + * + * @param id 序列id + * @return 字典对象 + */ + @Select("select * from dict where id=#{id}") + @ResultMap("dictMapperResults") + Dict selectCollById(Serializable id); + + /** + * 根据Name查询实体及关联对象 + * + * @param name 字典名称 + * @return 字典对象 + */ + @Select("select * from dict where name=#{name}") + @ResultMap("dictMapperResults") + Dict selectCollByName(String name); +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/dao/LogMapper.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/dao/LogMapper.java new file mode 100644 index 0000000..7c45cf1 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/dao/LogMapper.java @@ -0,0 +1,45 @@ +/** + * Copyright 2019-2020 Zheng Jie + * + * Licensed 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 org.dubhe.admin.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.apache.ibatis.annotations.Delete; +import org.apache.ibatis.annotations.Select; +import org.dubhe.admin.domain.entity.Log; + +/** + * @description 获取一个时间段的IP记录 + * @date 2020-03-25 + */ +public interface LogMapper extends BaseMapper { + /** + * 获取一个时间段的IP记录 + * + * @param date1 startTime + * @param date2 entTime + * @return IP数目 + */ + @Select("select count(*) FROM (select request_ip FROM log where create_time between #{date1} and #{date2} GROUP BY request_ip) as s") + Long findIp(String date1, String date2); + + /** + * 根据日志类型删除信息 + * + * @param logType 日志类型 + */ + @Delete("delete from log where log_type = #{logType}") + void deleteByLogType(String logType); +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/dao/MenuMapper.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/dao/MenuMapper.java new file mode 100644 index 0000000..7233fee --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/dao/MenuMapper.java @@ -0,0 +1,83 @@ +/** + * Copyright 2019-2020 Zheng Jie + * + * Licensed 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 org.dubhe.admin.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; +import org.apache.ibatis.annotations.SelectProvider; +import org.dubhe.admin.dao.provider.MenuProvider; +import org.dubhe.admin.domain.entity.Menu; +import org.dubhe.biz.base.dto.SysPermissionDTO; + +import java.util.List; +import java.util.Set; + +/** + * @description 菜单 mapper + * @date 2020-04-02 + */ +public interface MenuMapper extends BaseMapper { + + + /** + * 根据角色id查询用户权限 + * + * @param roleIds 用户id + * @return 权限信息 + */ + List selectPermissionByRoleIds(@Param("list") List roleIds); + + + /** + * 根据组件名称查询 + * + * @param name 组件名称 + * @return 菜单对象 + */ + @Select("select * from menu where component=#{name} and deleted = 0 ") + Menu findByComponentName(String name); + + /** + * 根据菜单的 PID 查询 + * + * @param pid 菜单pid + * @return 菜单列表 + */ + @Select("select * from menu where pid=#{pid} and deleted = 0 ") + List findByPid(long pid); + + /** + * 根据角色ID与菜单类型查询菜单 + * + * @param roleIds roleIDs + * @param type 类型 + * @return 菜单列表 + */ + @SelectProvider(type = MenuProvider.class, method = "findByRolesIdInAndTypeNotOrderBySortAsc") + List findByRolesIdInAndTypeNotOrderBySortAsc(Set roleIds, int type); + + + /** + * 根据角色ID与查询菜单 + * + * @param roleId 角色id + * @return 菜单列表 + */ + @Select("select m.* from menu m,roles_menus rm where m.id= rm.menu_id and rm.role_id=#{roleId} and deleted = 0 ") + List selectByRoleId(long roleId); + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/dao/PermissionMapper.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/dao/PermissionMapper.java new file mode 100644 index 0000000..78241e7 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/dao/PermissionMapper.java @@ -0,0 +1,111 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.dao; + +import com.baomidou.mybatisplus.core.conditions.Wrapper; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.apache.ibatis.annotations.Many; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Result; +import org.apache.ibatis.annotations.Results; +import org.apache.ibatis.annotations.Select; +import org.apache.ibatis.annotations.Update; +import org.apache.ibatis.mapping.FetchType; +import org.dubhe.admin.domain.entity.Permission; +import org.dubhe.admin.domain.entity.Role; +import org.dubhe.biz.base.dto.SysPermissionDTO; + +import java.util.List; + +/** + * @description 角色权限关联mapper + * @date 2021-04-26 + */ +public interface PermissionMapper extends BaseMapper { + + + /** + * 查询实体及关联对象 + * + * @param queryWrapper 角色wrapper对象 + * @return 角色列表 + */ + @Select("select * from role ${ew.customSqlSegment}") + @Results(id = "roleMapperResults", + value = { + @Result(property = "id", column = "id"), + @Result(property = "Permissions", + column = "id", + many = @Many(select = "org.dubhe.admin.dao.PermissionMapper.selectByRoleId", fetchType = FetchType.LAZY))}) + List selectCollList(@Param("ew") Wrapper queryWrapper); + + + /** + * 绑定角色权限 + * + * @param roleId 角色ID + * @param menuId 权限ID + */ + @Update("insert into roles_auth values (#{roleId}, #{menuId})") + void tiedRoleAuth(Long roleId, Long menuId); + + + /** + * 根据roleId查询权限列表 + * + * @param roleId roleId + * @return List 权限列表 + */ + @Select("select p.permission, p.name from permission p left join auth_permission ap on p.id = ap.permission_id left join roles_auth ra on ap.auth_id = ra.auth_id where ra.role_id=#{roleId} and deleted=0 ") + List selectByRoleId(long roleId); + + /** + * 根据权限的 PID 查询 + * + * @param pid 父权限id + * @return List 权限列表 + */ + @Select("select * from permission where pid=#{pid} and deleted = 0 ") + List findByPid(long pid); + + + /** + * 根据角色id查询用户权限 + * + * @param roleIds 用户id + * @return 权限信息 + */ + List selectPermissinByRoleIds(@Param("list") List roleIds); + + /** + * 根据权限名获取权限信息 + * + * @param name 权限名称 + * @return 权限 + */ + @Select("select * from permission where name=#{name} and deleted=0") + Permission findByName(String name); + + +} + + + + + + + diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/dao/ResourceSpecsMapper.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/dao/ResourceSpecsMapper.java new file mode 100644 index 0000000..b580aea --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/dao/ResourceSpecsMapper.java @@ -0,0 +1,27 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.dubhe.admin.domain.entity.ResourceSpecs; + +/** + * @description 资源规格管理mapper接口 + * @date 2021-05-27 + */ +public interface ResourceSpecsMapper extends BaseMapper { +} \ No newline at end of file diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/dao/RoleMapper.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/dao/RoleMapper.java new file mode 100644 index 0000000..9cae87b --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/dao/RoleMapper.java @@ -0,0 +1,163 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.dao; + +import com.baomidou.mybatisplus.core.conditions.Wrapper; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.apache.ibatis.annotations.*; +import org.apache.ibatis.mapping.FetchType; +import org.dubhe.admin.dao.provider.RoleProvider; +import org.dubhe.admin.domain.entity.Role; + +import java.io.Serializable; +import java.util.List; + +/** + * @description 角色 mapper + * @date 2020-11-26 + */ +public interface RoleMapper extends BaseMapper { + + /** + * 根据用户id查询用户角色 + * + * @param userId 用户id + * @return 用户信息 + */ + @Select("select sr.id, sr.name, sur.user_id from users_roles sur left join role sr on sr.id = sur.role_id where sur.user_id = #{userId} and sr.deleted = 0 ") + List selectRoleByUserId(@Param("userId") Long userId); + + + /** + * 查询实体及关联对象 + * + * @param queryWrapper 角色wrapper对象 + * @return List 角色列表 + */ + @Select("select * from role ${ew.customSqlSegment}") + @Results(id = "roleMapperResults", + value = { + @Result(property = "id", column = "id"), + @Result(property = "menus", + column = "id", + many = @Many(select = "org.dubhe.admin.dao.MenuMapper.selectByRoleId", fetchType = FetchType.LAZY)), + @Result(property = "auths", + column = "id", + many = @Many(select = "org.dubhe.admin.dao.AuthCodeMapper.selectByRoleId", fetchType = FetchType.LAZY))}) + List selectCollList(@Param("ew") Wrapper queryWrapper); + + /** + * 分页查询实体及关联对象 + * + * @param page 分页对象 + * @param queryWrapper 角色wrapper对象 + * @return IPage 分页角色集合 + */ + @Select("select * from role ${ew.customSqlSegment}") + @ResultMap(value = "roleMapperResults") + IPage selectCollPage(Page page, @Param("ew") Wrapper queryWrapper); + + /** + * 根据ID查询实体及关联对象 + * + * @param id 序列id + * @return 角色 + */ + @Select("select * from role where id=#{id} and deleted = 0 ") + @ResultMap("roleMapperResults") + Role selectCollById(Serializable id); + + /** + * 根据名称查询 + * + * @param name 角色名称 + * @return 角色 + */ + @Select("select * from role where name = #{name} and deleted = 0 ") + Role findByName(String name); + + /** + * 绑定用户角色 + * + * @param userId 用户ID + * @param roleId 角色ID + */ + @Update("insert into users_roles values (#{userId}, #{roleId})") + void tiedUserRole(Long userId, Long roleId); + + /** + * 根据用户ID解绑用户角色 + * + * @param userId 用户ID + */ + @Update("delete from users_roles where user_id = #{userId}") + void untiedUserRoleByUserId(Long userId); + + /** + * 根据角色ID解绑用户角色 + * + * @param roleId 角色ID + */ + @Update("delete from users_roles where role_id = #{roleId}") + void untiedUserRoleByRoleId(Long roleId); + + /** + * 绑定角色菜单 + * + * @param roleId 角色ID + * @param menuId 菜单ID + */ + @Update("insert into roles_menus values (#{roleId}, #{menuId})") + void tiedRoleMenu(Long roleId, Long menuId); + + /** + * 根据角色ID解绑角色菜单 + * + * @param roleId 角色ID + */ + @Update("delete from roles_menus where role_id = #{roleId}") + void untiedRoleMenuByRoleId(Long roleId); + + /** + * 根据菜单ID解绑角色菜单 + * + * @param menuId 菜单ID + */ + @Update("delete from roles_menus where menu_id = #{menuId}") + void untiedRoleMenuByMenuId(Long menuId); + + /** + * 根据用户ID查询角色 + * + * @param userId 用户ID + * @return List 角色列表 + */ + @SelectProvider(type = RoleProvider.class, method = "findRolesByUserId") + List findRolesByUserId(Long userId); + + /** + * 根据团队ID和用户ID查询角色 + * + * @param userId 用户ID + * @param teamId 团队ID + * @return List 角色列表 + */ + @SelectProvider(type = RoleProvider.class, method = "findByUserIdAndTeamId") + List findByUserIdAndTeamId(Long userId, Long teamId); +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/dao/TeamMapper.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/dao/TeamMapper.java new file mode 100644 index 0000000..f29f7b2 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/dao/TeamMapper.java @@ -0,0 +1,58 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.apache.ibatis.annotations.*; +import org.apache.ibatis.mapping.FetchType; +import org.dubhe.admin.dao.provider.TeamProvider; +import org.dubhe.admin.domain.entity.Team; + +import java.io.Serializable; +import java.util.List; + +/** + * @description 团队 mapper + * @date 2020-03-25 + */ +public interface TeamMapper extends BaseMapper { + + /** + * 根据ID查询名称 + * + * @param userId 用户id + * @return List 团队列表 + */ + @SelectProvider(type = TeamProvider.class, method = "findByUserId") + List findByUserId(Long userId); + + + /** + * 根据ID查询团队实体及关联对象 + * + * @param id 序列id + * @return 团队 + */ + @Select("select * from team where id=#{id}") + @Results(id = "teamMapperResults", + value = { + @Result(column = "id", property = "teamUserList", + many = @Many(select = "org.dubhe.admin.dao.UserMapper.findByTeamId", + fetchType = FetchType.LAZY))}) + Team selectCollById(Serializable id); +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/dao/UserAvatarMapper.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/dao/UserAvatarMapper.java new file mode 100644 index 0000000..66f4ed9 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/dao/UserAvatarMapper.java @@ -0,0 +1,26 @@ +/** + * Copyright 2019-2020 Zheng Jie + * + * Licensed 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 org.dubhe.admin.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.dubhe.admin.domain.entity.UserAvatar; + +/** + * @description 用户头像 mapper + * @date 2020-03-25 + */ +public interface UserAvatarMapper extends BaseMapper { +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/dao/UserGroupMapper.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/dao/UserGroupMapper.java new file mode 100644 index 0000000..639bc2e --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/dao/UserGroupMapper.java @@ -0,0 +1,86 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.apache.ibatis.annotations.Delete; +import org.apache.ibatis.annotations.Insert; +import org.apache.ibatis.annotations.Select; +import org.apache.ibatis.annotations.Update; +import org.dubhe.admin.domain.entity.Group; +import org.dubhe.admin.domain.entity.User; + +import java.util.List; + +/** + * @description 用户组mapper接口 + * @date 2021-05-08 + */ +public interface UserGroupMapper extends BaseMapper { + + /** + * 获取用户组成员信息 + * + * @param groupId 用户组id + * @return List 用户列表 + */ + @Select("select u.* from user u left join user_group gu on u.id = gu.user_id where gu.group_id=#{groupId} and deleted=0 ") + List queryUserByGroupId(Long groupId); + + /** + * 删除用户组 + * + * @param groupId 用户组id + */ + @Update("update pt_group set deleted=1 where id=#{groupId} ") + void delUserGroupByGroupId(Long groupId); + + /** + * 清空用户组成员 + * + * @param groupId 用户组id + */ + @Delete("delete from user_group where group_id=#{groupId} ") + void delUserByGroupId(Long groupId); + + /** + * 新增用户组成员 + * + * @param groupId 用户组id + * @param userId 用户id + */ + @Insert("insert into user_group values (#{groupId},#{userId})") + void addUserWithGroup(Long groupId, Long userId); + + /** + * 删除用户组成员 + * + * @param groupId 用户组id + * @param userId 用户id + */ + @Delete("delete from user_group where group_id=#{groupId} and user_id=#{userId}") + void delUserWithGroup(Long groupId, Long userId); + + /** + * 获取还未分组的用户 + * + * @return List 用户组成员列表 + */ + @Select("select * from user where id not in (select user_id from user_group) and deleted=0") + List findUserWithOutGroup(); + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/dao/UserMapper.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/dao/UserMapper.java new file mode 100644 index 0000000..cff32e5 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/dao/UserMapper.java @@ -0,0 +1,147 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.dao; + +import com.baomidou.mybatisplus.core.conditions.Wrapper; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.apache.ibatis.annotations.Many; +import org.apache.ibatis.annotations.One; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Result; +import org.apache.ibatis.annotations.ResultMap; +import org.apache.ibatis.annotations.Results; +import org.apache.ibatis.annotations.Select; +import org.apache.ibatis.annotations.Update; +import org.apache.ibatis.mapping.FetchType; +import org.dubhe.admin.domain.entity.User; + +import java.util.Date; +import java.util.List; +import java.util.Set; + +/** + * @description Demo服务mapper + * @date 2020-11-26 + */ +public interface UserMapper extends BaseMapper { + + + /** + * 根据ID查询实体及关联对象 + * + * @param id 用户id + * @return 用户 + */ + @Select("select * from user where id=#{id} and deleted = 0") + @Results(id = "userMapperResults", + value = { + @Result(property = "id", column = "id"), + @Result(property = "roles", + column = "id", + many = @Many(select = "org.dubhe.admin.dao.RoleMapper.findRolesByUserId", + fetchType = FetchType.LAZY)), + @Result(property = "userAvatar", + column = "avatar_id", + one = @One(select = "org.dubhe.admin.dao.UserAvatarMapper.selectById", + fetchType = FetchType.LAZY))}) + User selectCollById(Long id); + + /** + * 根据用户名查询 + * + * @param username 用户名 + * @return 用户 + */ + @Select("select * from user where username=#{username} and deleted = 0") + @ResultMap(value = "userMapperResults") + User findByUsername(String username); + + /** + * 根据邮箱查询 + * + * @param email 邮箱 + * @return 用户 + */ + @Select("select * from user where email=#{email} and deleted = 0") + @ResultMap(value = "userMapperResults") + User findByEmail(String email); + + /** + * 修改密码 + * + * @param username 用户名 + * @param pass 密码 + * @param lastPasswordResetTime 密码最后一次重置时间 + */ + + @Update("update user set password = #{pass} , last_password_reset_time = #{lastPasswordResetTime} where username = #{username}") + void updatePass(String username, String pass, Date lastPasswordResetTime); + + /** + * 修改邮箱 + * + * @param username 用户名 + * @param email 邮箱 + */ + @Update("update user set email = #{email} where username = #{username}") + void updateEmail(String username, String email); + + /** + * 查找用户权限 + * + * @param userId 用户id + * @return 权限集合 + */ + Set queryPermissionByUserId(Long userId); + + + /** + * 查询实体及关联对象 + * + * @param queryWrapper 用户wrapper对象 + * @return 用户集合 + */ + @Select("select * from user ${ew.customSqlSegment}") + @ResultMap(value = "userMapperResults") + List selectCollList(@Param("ew") Wrapper queryWrapper); + + /** + * 分页查询实体及关联对象 + * + * @param page 分页对象 + * @param queryWrapper 用户wrapper对象 + * @return 分页user集合 + */ + @Select("select * from user ${ew.customSqlSegment} order by id desc") + @ResultMap(value = "userMapperResults") + IPage selectCollPage(Page page, @Param("ew") Wrapper queryWrapper); + + /** + * 根据角色分页查询实体及关联对象 + * + * @param page 分页对象 + * @param queryWrapper 用户wrapper对象 + * @param roleId 角色id + * @return 分页用户集合 + */ + @Select("select u.* from user u join users_roles ur on u.id=ur.user_id and ur.role_id=#{roleId} ${ew.customSqlSegment} order by u.id desc") + @ResultMap(value = "userMapperResults") + IPage selectCollPageByRoleId(Page page, @Param("ew") Wrapper queryWrapper, Long roleId); + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/dao/UserRoleMapper.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/dao/UserRoleMapper.java new file mode 100644 index 0000000..e5e7494 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/dao/UserRoleMapper.java @@ -0,0 +1,46 @@ +/** + * Copyright 2019-2020 Zheng Jie + * + * Licensed 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 org.dubhe.admin.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.apache.ibatis.annotations.Param; +import org.dubhe.admin.domain.entity.UserRole; + +import java.util.List; +import java.util.Set; + +/** + * @description 用户角色 mapper + * @date 2020-6-9 + */ +public interface UserRoleMapper extends BaseMapper { + + /** + * 批量删除用户 + * + * @param userIds 用户id集合 + */ + void deleteByUserId(@Param("list") Set userIds); + + /** + * 批量添加用户角色 + * + * @param userRoles 用户角色实体集合 + */ + void insertBatchs(List userRoles); + +} + diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/dao/provider/MenuProvider.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/dao/provider/MenuProvider.java new file mode 100644 index 0000000..e531ba6 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/dao/provider/MenuProvider.java @@ -0,0 +1,45 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.dao.provider; + +import org.apache.ibatis.jdbc.SQL; + +import java.util.Map; +import java.util.Set; + +/** + * @description 菜单sql构建类 + * @date 2020-04-02 + */ +public class MenuProvider { + public String findByRolesIdInAndTypeNotOrderBySortAsc(Map para) { + Set roleIds = (Set) para.get("roleIds"); + int type = (int) para.get("type"); + StringBuffer roleIdsql = new StringBuffer("rm.role_id in (-1 "); + roleIds.forEach(id -> { + roleIdsql.append("," + id.toString()); + }); + roleIdsql.append(" )"); + return new SQL() {{ + SELECT_DISTINCT("m.*"); + FROM("menu m, roles_menus rm "); + WHERE(roleIdsql + " and m.id=rm.menu_id and m.deleted = 0 and m.type<>" + type); + ORDER_BY("pid, sort, id"); + }}.toString(); + } +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/dao/provider/RoleProvider.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/dao/provider/RoleProvider.java new file mode 100644 index 0000000..1509781 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/dao/provider/RoleProvider.java @@ -0,0 +1,43 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.dao.provider; + +import java.util.Map; + +/** + * @description 角色构建类 + * @date 2020-04-15 + */ +public class RoleProvider { + public String findRolesByUserId(Long userId) { + StringBuffer sql = new StringBuffer("select r.* from role r, users_roles ur "); + sql.append(" where ur.user_id=#{userId} "); + sql.append(" and ur.role_id=r.id"); + sql.append(" and r.deleted = 0"); + return sql.toString(); + } + + public String findByUserIdAndTeamId(Map para) { + StringBuffer sql = new StringBuffer("select r.* from role r, teams_users_roles tur "); + sql.append(" where tur.user_id=#{userId} "); + sql.append(" and tur.team_id=#{teamId} "); + sql.append(" and tur.role_id=r.id"); + sql.append(" and r.deleted = 0"); + return sql.toString(); + } +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/dao/provider/TeamProvider.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/dao/provider/TeamProvider.java new file mode 100644 index 0000000..0523de1 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/dao/provider/TeamProvider.java @@ -0,0 +1,32 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.dao.provider; + +/** + * @description 团队构建类 + * @date 2020-04-15 + */ +public class TeamProvider { + + public String findByUserId(Long userId) { + StringBuffer sql = new StringBuffer("select t.* from team t, teams_users_roles tur "); + sql.append(" where tur.user_id=#{userId} "); + sql.append(" and tur.team_id=t.id "); + return sql.toString(); + } +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/dao/provider/UserProvider.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/dao/provider/UserProvider.java new file mode 100644 index 0000000..b3a44a6 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/dao/provider/UserProvider.java @@ -0,0 +1,45 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.dao.provider; + +/** + * @description 用户sql构建类 + * @date 2020-04-02 + */ +public class UserProvider { + public String queryPermissionByUserId(Long userId) { + StringBuffer sql = new StringBuffer("select m.permission from menu m, users_roles ur, roles_menus rm "); + sql.append(" where ur.user_id = #{userId} and ur.role_id = rm.role_id and rm.menu_id = m.id and m.permission <> '' and m.deleted = 0 "); + return sql.toString(); + } + + public String findPermissionByUserIdAndTeamId(Long userId, Long teamId) { + StringBuffer sql = new StringBuffer("select m.permission from menu m, teams_users_roles tur ,roles_menus rm "); + sql.append(" where tur.user_id=#{userId} "); + sql.append(" and tur.role_id=rm.role_id "); + sql.append(" and tur.team_id=#{team_id} "); + sql.append(" and rm.menu_id=m.id"); + sql.append(" and and m.deleted = 0 "); + return sql.toString(); + } + + public String findByTeamId(Long teamId) { + StringBuffer sql = new StringBuffer("select u.* from user u,teams_users_roles tur where tur.team_id=#{teamId} and tur.user_id=u.id and u.deleted = 0"); + return sql.toString(); + } +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/AuthCodeCreateDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/AuthCodeCreateDTO.java new file mode 100644 index 0000000..a7fb30f --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/AuthCodeCreateDTO.java @@ -0,0 +1,47 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; +import java.io.Serializable; +import java.util.Set; + +/** + * @description 创建权限组DTO + * @date 2021-05-14 + */ +@Data +public class AuthCodeCreateDTO implements Serializable { + + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "autoCode", required = true) + @NotEmpty(message = "权限组code不能为空") + private String authCode; + + @ApiModelProperty(value = "权限id集合", required = true) + @NotNull(message = "权限不能为空") + private Set permissions; + + @ApiModelProperty("描述") + private String description; + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/AuthCodeDeleteDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/AuthCodeDeleteDTO.java new file mode 100644 index 0000000..41812d5 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/AuthCodeDeleteDTO.java @@ -0,0 +1,36 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import lombok.Data; + +import javax.validation.constraints.NotNull; +import java.io.Serializable; +import java.util.Set; + +/** + * @description 删除权限组DTO + * @date 2021-05-17 + */ +@Data +public class AuthCodeDeleteDTO implements Serializable { + + private static final long serialVersionUID = 1L; + + @NotNull(message = "id不能为空") + private Set ids; +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/AuthCodeQueryDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/AuthCodeQueryDTO.java new file mode 100644 index 0000000..b514437 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/AuthCodeQueryDTO.java @@ -0,0 +1,37 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import org.dubhe.biz.db.base.PageQueryBase; + +import java.io.Serializable; + +/** + * @description 分页查看权限组列表 + * @date 2021-05-14 + */ + +@Data +public class AuthCodeQueryDTO extends PageQueryBase implements Serializable { + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "权限组名称") + private String authCode; + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/AuthCodeUpdateDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/AuthCodeUpdateDTO.java new file mode 100644 index 0000000..2f58d6d --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/AuthCodeUpdateDTO.java @@ -0,0 +1,46 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import javax.validation.constraints.NotEmpty; +import java.io.Serializable; +import java.util.Set; + +/** + * @description 修改权限组DTO + * @date 2021-05-14 + */ +@Data +public class AuthCodeUpdateDTO implements Serializable { + private static final long serialVersionUID = 1L; + + private Long id; + + @ApiModelProperty(value = "autoCode", required = true) + @NotEmpty(message = "权限组code不能为空") + private String authCode; + + @ApiModelProperty(value = "权限id集合") + private Set permissions; + + @ApiModelProperty("描述") + private String description; + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/AuthPermissionUpdDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/AuthPermissionUpdDTO.java new file mode 100644 index 0000000..758a896 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/AuthPermissionUpdDTO.java @@ -0,0 +1,39 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import javax.validation.constraints.NotNull; +import java.io.Serializable; +import java.util.Set; + +/** + * @description 修改权限组权限DTO + * @date 2021-05-14 + */ +@Data +public class AuthPermissionUpdDTO implements Serializable { + + @ApiModelProperty(value = "权限组id") + @NotNull(message = "权限组id不能为空") + private Long authId; + + @ApiModelProperty(value = "权限id集合") + private Set permissionIds; +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/AuthUpdateDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/AuthUpdateDTO.java new file mode 100644 index 0000000..4c6a55b --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/AuthUpdateDTO.java @@ -0,0 +1,71 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import org.dubhe.admin.domain.entity.Permission; + +import javax.validation.constraints.Size; +import java.io.Serializable; +import java.util.Objects; +import java.util.Set; + +/** + * @description 修改操作权限DTO + * @date 2021-04-28 + */ +@Data +public class AuthUpdateDTO implements Serializable { + + private static final long serialVersionUID = 1L; + + private Long id; + + @ApiModelProperty(value = "操作权限名称") + @Size(max = 255, message = "名称长度不能超过255") + private String name; + + @ApiModelProperty(value = "操作权限标识") + @Size(max = 255, message = "默认权限长度不能超过255") + private String permission; + + + private Set permissions; + + private Boolean deleted; + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AuthUpdateDTO role = (AuthUpdateDTO) o; + return Objects.equals(id, role.id); + } + + @Override + public int hashCode() { + return Objects.hash(id); + } + + public @interface Update { + } +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/AuthUserDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/AuthUserDTO.java new file mode 100644 index 0000000..eea9ae8 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/AuthUserDTO.java @@ -0,0 +1,48 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; +import lombok.Getter; +import lombok.Setter; + +import javax.validation.constraints.NotBlank; +import java.io.Serializable; + +/** + * @description 用户登录dto + * @date 2020-06-01 + */ +@Getter +@Setter +public class AuthUserDTO implements Serializable { + + private static final long serialVersionUID = 6243696246160576285L; + @NotBlank + private String username; + + @NotBlank + private String password; + + private String code; + + private String uuid = ""; + + @Override + public String toString() { + return "{username=" + username + ", password= ******}"; + } +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/DictCreateDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/DictCreateDTO.java new file mode 100644 index 0000000..57805b7 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/DictCreateDTO.java @@ -0,0 +1,51 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import com.baomidou.mybatisplus.annotation.TableField; +import lombok.Data; +import org.dubhe.admin.domain.entity.DictDetail; +import org.hibernate.validator.constraints.Length; + +import javax.validation.constraints.NotBlank; +import java.io.Serializable; +import java.sql.Timestamp; +import java.util.List; + +/** + * @description 字典新增DTO + * @date 2020-06-01 + */ +@Data +public class DictCreateDTO implements Serializable { + + private static final long serialVersionUID = -901581636964448858L; + + @NotBlank(message = "字典名称不能为空") + @Length(max = 255, message = "名称长度不能超过255") + private String name; + + @Length(max = 255, message = "备注长度不能超过255") + private String remark; + + private Timestamp createTime; + + @TableField(exist = false) + private List dictDetails; + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/DictDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/DictDTO.java new file mode 100644 index 0000000..d00654f --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/DictDTO.java @@ -0,0 +1,42 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import lombok.Data; + +import java.io.Serializable; +import java.sql.Timestamp; +import java.util.List; +/** + * @description 字典DTO + * @date 2020-06-01 + */ +@Data +public class DictDTO implements Serializable { + + private static final long serialVersionUID = 1L; + private Long id; + + private String name; + + private String remark; + + private List dictDetails; + + private Timestamp createTime; +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/DictDeleteDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/DictDeleteDTO.java new file mode 100644 index 0000000..7692168 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/DictDeleteDTO.java @@ -0,0 +1,36 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import lombok.Data; + +import javax.validation.constraints.NotEmpty; +import java.io.Serializable; +import java.util.Set; + +/** + * @description 字典删除DTO + * @date 2020-06-01 + */ +@Data +public class DictDeleteDTO implements Serializable { + + private static final long serialVersionUID = 6346677566514471535L; + + @NotEmpty(message = "id不能为空") + Set ids; +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/DictDetailCreateDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/DictDetailCreateDTO.java new file mode 100644 index 0000000..10decae --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/DictDetailCreateDTO.java @@ -0,0 +1,53 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import org.hibernate.validator.constraints.Length; + +import java.io.Serializable; +import java.sql.Timestamp; + +/** + * @description 字典详情修改DTO + * @date 2020-06-29 + */ +@Data +public class DictDetailCreateDTO implements Serializable { + + private static final long serialVersionUID = -1936563127368448645L; + + @ApiModelProperty(value = "字典标签") + @Length(max = 255, message = "字典标签长度不能超过255") + private String label; + + @ApiModelProperty(value = "字典值") + @Length(max = 255, message = "字典值长度不能超过255") + private String value; + + @ApiModelProperty(value = "排序") + private String sort = "999"; + + private Long dictId; + + private Timestamp createTime; + + public @interface Update { + } +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/DictDetailDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/DictDetailDTO.java new file mode 100644 index 0000000..d9e2984 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/DictDetailDTO.java @@ -0,0 +1,53 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.io.Serializable; +import java.sql.Timestamp; + +/** + * @description 字典详情DTO + * @date 2020-06-01 + */ +@Data +public class DictDetailDTO implements Serializable { + + private static final long serialVersionUID = 1521993584428225098L; + + @ApiModelProperty(value = "字典详情id") + private Long id; + + @ApiModelProperty(value = "字典label") + private String label; + + @ApiModelProperty(value = "字典详情value") + private String value; + + @ApiModelProperty(value = "排序") + private String sort; + + @ApiModelProperty(value = "字典id") + private Long dictId; + + private Timestamp createTime; + + private Timestamp updateTime; +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/DictDetailDeleteDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/DictDetailDeleteDTO.java new file mode 100644 index 0000000..a3db766 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/DictDetailDeleteDTO.java @@ -0,0 +1,38 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import lombok.Data; + +import javax.validation.constraints.NotEmpty; +import java.io.Serializable; +import java.util.Set; + +/** + * @description 字典详情删除DTO + * @date 2020-06-29 + */ +@Data +public class DictDetailDeleteDTO implements Serializable { + + private static final long serialVersionUID = -151060582445500836L; + + @NotEmpty(message = "id不能为空") + private Set ids; + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/DictDetailQueryDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/DictDetailQueryDTO.java new file mode 100644 index 0000000..2e22718 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/DictDetailQueryDTO.java @@ -0,0 +1,38 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import lombok.Data; +import org.dubhe.biz.db.annotation.Query; + +import java.io.Serializable; + +/** + * @description 字典详情查询实体 + * @date 2020-06-01 + */ +@Data +public class DictDetailQueryDTO implements Serializable { + + private static final long serialVersionUID = 1L; + @Query(type = Query.Type.LIKE) + private String label; + + @Query(propName = "dict_id", type = Query.Type.EQ) + private Long dictId; +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/DictDetailUpdateDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/DictDetailUpdateDTO.java new file mode 100644 index 0000000..c0721f9 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/DictDetailUpdateDTO.java @@ -0,0 +1,60 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import org.dubhe.admin.domain.entity.DictDetail; +import org.hibernate.validator.constraints.Length; + + +import javax.validation.constraints.NotNull; +import java.io.Serializable; +import java.sql.Timestamp; + +/** + * @description 字典详情修改DTO + * @date 2020-06-29 + */ +@Data +public class DictDetailUpdateDTO implements Serializable { + + private static final long serialVersionUID = -1936563127368448645L; + + @NotNull(groups = DictDetail.Update.class) + private Long id; + + @ApiModelProperty(value = "字典标签") + @Length(max = 255, message = "字典标签长度不能超过255") + private String label; + + @ApiModelProperty(value = "字典值") + @Length(max = 255, message = "字典值长度不能超过255") + private String value; + + @ApiModelProperty(value = "排序") + private String sort = "999"; + + @ApiModelProperty(value = "字典id") + private Long dictId; + + private Timestamp createTime; + + public @interface Update { + } +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/DictQueryDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/DictQueryDTO.java new file mode 100644 index 0000000..a608d66 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/DictQueryDTO.java @@ -0,0 +1,35 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import lombok.Data; +import org.dubhe.biz.db.annotation.Query; + +import java.io.Serializable; + +/** + * @description 公共查询类 + * @date 2020-05-10 + */ +@Data +public class DictQueryDTO implements Serializable { + + private static final long serialVersionUID = -8221913871799888949L; + @Query(blurry = "name,remark") + private String blurry; +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/DictSmallDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/DictSmallDTO.java new file mode 100644 index 0000000..be1fb62 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/DictSmallDTO.java @@ -0,0 +1,32 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import lombok.Data; + +import java.io.Serializable; + +/** + * @description 实体类 + * @date 2020-03-16 + */ +@Data +public class DictSmallDTO implements Serializable { + private Long id; + private String name; +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/DictSmallQueryDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/DictSmallQueryDTO.java new file mode 100644 index 0000000..3369dcc --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/DictSmallQueryDTO.java @@ -0,0 +1,33 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import lombok.Data; + +import java.io.Serializable; + +/** + * @description 字典查询转换DTO + * @date 2020-06-01 + */ +@Data +public class DictSmallQueryDTO implements Serializable { + private static final long serialVersionUID = 5825111154262768118L; + private Long id; + private String name; +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/DictUpdateDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/DictUpdateDTO.java new file mode 100644 index 0000000..9241c22 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/DictUpdateDTO.java @@ -0,0 +1,58 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import com.baomidou.mybatisplus.annotation.TableField; +import lombok.Data; +import org.dubhe.admin.domain.entity.Dict; +import org.dubhe.admin.domain.entity.DictDetail; +import org.hibernate.validator.constraints.Length; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; +import java.io.Serializable; +import java.sql.Timestamp; +import java.util.List; + +/** + * @description 字典新增DTO + * @date 2020-06-01 + */ +@Data +public class DictUpdateDTO implements Serializable { + + private static final long serialVersionUID = -901581636964448858L; + + @NotNull(groups = Dict.Update.class) + private Long id; + + @NotBlank + @Length(max = 255, message = "名称长度不能超过255") + private String name; + + @Length(max = 255, message = "备注长度不能超过255") + private String remark; + + private Timestamp createTime; + + @TableField(exist = false) + private List dictDetails; + + public @interface Update { + } +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/EmailDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/EmailDTO.java new file mode 100644 index 0000000..8b202a7 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/EmailDTO.java @@ -0,0 +1,48 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * @description 邮件DTO + * @date 2020-06-01 + */ +@Data +@Builder +@AllArgsConstructor +@NoArgsConstructor +public class EmailDTO { + + @ApiModelProperty(value = "邮箱地址") + String receiverMailAddress; + + @ApiModelProperty(value = "标题") + String subject; + + @ApiModelProperty(value = "验证码") + String code; + + @ApiModelProperty(value = "类型 1 用户注册 2 修改邮箱 3 其他") + Integer type; + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/ExtConfigDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/ExtConfigDTO.java new file mode 100644 index 0000000..30dd9dd --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/ExtConfigDTO.java @@ -0,0 +1,37 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import io.swagger.annotations.ApiModelProperty; +import lombok.*; + +import java.io.Serializable; + +/** + * @description 扩展配置DTO + * @date 2021-01-25 + */ +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class ExtConfigDTO implements Serializable { + + @ApiModelProperty(value = "返回上一级菜单") + private String backTo; +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/LogDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/LogDTO.java new file mode 100644 index 0000000..a66b662 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/LogDTO.java @@ -0,0 +1,50 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import lombok.Data; + +import java.io.Serializable; +import java.sql.Timestamp; + +/** + * @description 日志转换DTO + * @date 2020-06-01 + */ +@Data +public class LogDTO implements Serializable { + + private static final long serialVersionUID = 1L; + private Long id; + + private String username; + + private String description; + + private String method; + + private String params; + + private String browser; + + private String requestIp; + + private String address; + + private Timestamp createTime; +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/LogQueryDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/LogQueryDTO.java new file mode 100644 index 0000000..96db88c --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/LogQueryDTO.java @@ -0,0 +1,41 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import lombok.Data; +import org.dubhe.biz.db.annotation.Query; + +import java.sql.Timestamp; +import java.util.List; + +/** + * @description 日志查询类 + * @date 2020-06-01 + */ +@Data +public class LogQueryDTO { + + @Query(blurry = "username,requestIp,method,params") + private String blurry; + + @Query + private String logType; + + @Query(type = Query.Type.BETWEEN) + private List createTime; +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/LogSmallDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/LogSmallDTO.java new file mode 100644 index 0000000..33fc8c6 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/LogSmallDTO.java @@ -0,0 +1,43 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import lombok.Data; + +import java.io.Serializable; +import java.sql.Timestamp; + +/** + * @description 实体类 + * @date 2020-03-16 + */ +@Data +public class LogSmallDTO implements Serializable { + + private String description; + + private String requestIp; + + private Long time; + + private String address; + + private String browser; + + private Timestamp createTime; +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/MenuCreateDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/MenuCreateDTO.java new file mode 100644 index 0000000..4b929c4 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/MenuCreateDTO.java @@ -0,0 +1,94 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import lombok.Data; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Size; +import java.io.Serializable; + +/** + * @description 菜单新增 dto + * @date 2020-06-29 + */ +@Data +public class MenuCreateDTO implements Serializable { + + private static final long serialVersionUID = 3587665050240667198L; + + @NotBlank + private String name; + + private Long sort = 999L; + + @Size(max = 255, message = "路由地址长度不能超过255") + private String path; + + @Size(max = 255, message = "路径长度不能超过255") + private String component; + + /** + * 类型,目录、菜单、按钮 + */ + private Integer type; + + /** + * 权限 + */ + @Size(max = 255, message = "权限长度不能超过255") + private String permission; + + private String componentName; + + @Size(max = 255, message = "图标长度不能超过255") + private String icon; + + /** + * 布局类型 + */ + @Size(max = 255, message = "布局类型不能超过255") + private String layout; + + private Boolean cache; + + private Boolean hidden; + + /** + * 上级菜单ID + */ + private Long pid; + + + private Boolean deleted; + + /** + * 回到上一级 + */ + private String backTo; + + /** + * 扩展配置 + */ + @Size(max = 255, message = "扩展配置长度不能超过255") + private String extConfig; + + public @interface Update { + } + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/MenuDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/MenuDTO.java new file mode 100644 index 0000000..5df0a54 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/MenuDTO.java @@ -0,0 +1,82 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.io.Serializable; +import java.sql.Timestamp; +import java.util.List; + +/** + * @description 字典查询转换DTO + * @date 2020-06-01 + */ +@Data +public class MenuDTO implements Serializable { + + private Long id; + + @ApiModelProperty(value = "菜单类型: 0目录,1页面,2权限,3外链") + private Integer type; + + @ApiModelProperty(value = "权限标识") + private String permission; + + @ApiModelProperty(value = "名称") + private String name; + + @ApiModelProperty(value = "菜单排序") + private Long sort; + + @ApiModelProperty(value = "路径或外链URL") + private String path; + + @ApiModelProperty(value = "组件路径") + private String component; + + @ApiModelProperty(value = "上级菜单ID") + private Long pid; + + @ApiModelProperty(value = "路由缓存 keep-alive") + private Boolean cache; + + @ApiModelProperty(value = "菜单栏不显示") + private Boolean hidden; + + @ApiModelProperty(value = "路由名称") + private String componentName; + + @ApiModelProperty(value = "菜单图标") + private String icon; + + @ApiModelProperty(value = "页面布局类型") + private String layout; + + + private List children; + + private Timestamp createTime; + + @ApiModelProperty(value = "回到上一级") + private String backTo; + + @ApiModelProperty(value = "扩展配置") + private String extConfig; +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/MenuDeleteDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/MenuDeleteDTO.java new file mode 100644 index 0000000..91ee7b2 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/MenuDeleteDTO.java @@ -0,0 +1,38 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import lombok.Data; + +import javax.validation.constraints.NotEmpty; +import java.io.Serializable; +import java.util.Set; + +/** + * @description 菜单删除 dto + * @date 2020-06-29 + */ +@Data +public class MenuDeleteDTO implements Serializable { + + private static final long serialVersionUID = -6599428238298923816L; + + @NotEmpty(message = "id不能为空") + private Set ids; + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/MenuQueryDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/MenuQueryDTO.java new file mode 100644 index 0000000..109e5bd --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/MenuQueryDTO.java @@ -0,0 +1,43 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import lombok.Data; +import org.dubhe.biz.db.annotation.Query; + +import java.sql.Timestamp; +import java.util.List; + +/** + * @description 菜单查询实体类 + * @date 2020-06-01 + */ +@Data +public class MenuQueryDTO { + + @Query(blurry = "name,path,component_name") + private String blurry; + + @Query(propName = "create_time", type = Query.Type.BETWEEN) + private List createTime; + + + @Query(propName = "deleted", type = Query.Type.EQ) + private Boolean deleted = false; + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/MenuUpdateDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/MenuUpdateDTO.java new file mode 100644 index 0000000..85660d9 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/MenuUpdateDTO.java @@ -0,0 +1,117 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import lombok.Data; +import org.dubhe.admin.domain.entity.Menu; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; +import java.io.Serializable; +import java.util.Objects; + +/** + * @description 菜单修改 dto + * @date 2020-06-29 + */ +@Data +public class MenuUpdateDTO implements Serializable { + + private static final long serialVersionUID = 3587665050240667198L; + + @NotNull(groups = {Menu.Update.class}) + private Long id; + + @NotBlank + private String name; + + private Long sort = 999L; + + @Size(max = 255, message = "路由地址长度不能超过255") + private String path; + + @Size(max = 255, message = "路径长度不能超过255") + private String component; + + /** + * 类型,目录、菜单、按钮 + */ + private Integer type; + + /** + * 权限 + */ + @Size(max = 255, message = "权限长度不能超过255") + private String permission; + + private String componentName; + + @Size(max = 255, message = "图标长度不能超过255") + private String icon; + + /** + * 布局类型 + */ + @Size(max = 255, message = "布局类型不能超过255") + private String layout; + + private Boolean cache; + + private Boolean hidden; + + /** + * 上级菜单ID + */ + private Long pid; + + + private Boolean deleted; + + /** + * 回到上一级 + */ + private String backTo; + + /** + * 扩展配置 + */ + @Size(max = 255, message = "扩展配置长度不能超过255") + private String extConfig; + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MenuUpdateDTO menu = (MenuUpdateDTO) o; + return Objects.equals(id, menu.id); + } + + @Override + public int hashCode() { + return Objects.hash(id); + } + + public @interface Update { + } + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/NodeDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/NodeDTO.java new file mode 100644 index 0000000..937ca36 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/NodeDTO.java @@ -0,0 +1,72 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.util.List; + + +/** + * @description 节点实体类 + * @date 2020-06-03 + */ +@Data +public class NodeDTO { + + + @ApiModelProperty(value = "node节点id值") + private String uid; + + @ApiModelProperty(value = "node节点名称") + private String name; + + @ApiModelProperty(value = "node节点ip地址") + private String ip; + + @ApiModelProperty(value = "node节点状态") + private String status; + + @ApiModelProperty(value = "gpu总数") + private String gpuCapacity; + + @ApiModelProperty(value = "gpu可用数") + private String gpuAvailable; + + @ApiModelProperty(value = "创建字段保存gpu使用数") + private String gpuUsed; + + @ApiModelProperty(value = "保存节点信息") + private List pods; + + @ApiModelProperty(value = "node节点的使用内存") + private String nodeMemory; + + @ApiModelProperty(value = "node节点的使用cpu") + private String nodeCpu; + + @ApiModelProperty(value = "node节点的总的cpu") + private String totalNodeCpu; + + @ApiModelProperty(value = "node节点的总的内存") + private String totalNodeMemory; + + @ApiModelProperty(value = "node节点的警告") + private String warning; +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/PermissionCreateDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/PermissionCreateDTO.java new file mode 100644 index 0000000..82ea30b --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/PermissionCreateDTO.java @@ -0,0 +1,43 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import org.dubhe.admin.domain.entity.Permission; + +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; +import java.io.Serializable; +import java.util.List; + +/** + * @description 新增权限DTO + * @date 2021-05-31 + */ +@Data +public class PermissionCreateDTO implements Serializable { + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "权限父id") + @NotNull(message = "父级权限id不能为空") + private Long pid; + + @NotEmpty(message = "权限不能为空") + private List permissions; + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/PermissionDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/PermissionDTO.java new file mode 100644 index 0000000..4b62b0c --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/PermissionDTO.java @@ -0,0 +1,43 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.io.Serializable; + +/** + * @description 操作权限DTO + * @date 2021-04-29 + */ +@Data +public class PermissionDTO implements Serializable { + + private static final long serialVersionUID = 1L; + @ApiModelProperty(value = "权限id") + private Long id; + + @ApiModelProperty(value = "父权限id") + private Long pid; + + @ApiModelProperty("权限标识") + private String permission; + + @ApiModelProperty(value = "权限名称") + private String name; +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/PermissionDeleteDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/PermissionDeleteDTO.java new file mode 100644 index 0000000..92a6723 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/PermissionDeleteDTO.java @@ -0,0 +1,34 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import lombok.Data; + +import java.io.Serializable; +import java.util.Set; + +/** + * @description 删除权限DTO + * @date 2021-05-31 + */ +@Data +public class PermissionDeleteDTO implements Serializable { + + private static final long serialVersionUID = 1L; + + private Set ids; +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/PermissionQueryDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/PermissionQueryDTO.java new file mode 100644 index 0000000..77d2f35 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/PermissionQueryDTO.java @@ -0,0 +1,33 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import lombok.Data; + +import java.io.Serializable; + +/** + * @description 权限查询DTO + * @date 2021-05-31 + */ +@Data +public class PermissionQueryDTO implements Serializable { + + private static final long serialVersionUID = 1L; + + private String keyword; +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/PermissionUpdateDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/PermissionUpdateDTO.java new file mode 100644 index 0000000..2163eca --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/PermissionUpdateDTO.java @@ -0,0 +1,47 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import org.dubhe.admin.domain.entity.Permission; + +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; +import java.io.Serializable; +import java.util.List; + +/** + * @description 修改权限DTO + * @date 2021-06-01 + */ +@Data +public class PermissionUpdateDTO implements Serializable { + + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "权限id") + @NotNull(message = "权限id不能为空") + private Long id; + + @ApiModelProperty(value = "权限父id") + @NotNull(message = "父级权限id不能为空") + private Long pid; + + @NotEmpty(message = "权限不能为空") + private List permissions; +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/PodDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/PodDTO.java new file mode 100644 index 0000000..b13c9f4 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/PodDTO.java @@ -0,0 +1,52 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +/** + * @description pod的实体类 + * @date 2020-06-03 + */ +@Data +public class PodDTO { + + @ApiModelProperty(value = "pod的name") + private String podName; + + @ApiModelProperty(value = "pod的内存") + private String podMemory; + + @ApiModelProperty(value = "pod的cpu") + private String podCpu; + + @ApiModelProperty(value = "pod的显卡") + private String podCard; + + @ApiModelProperty(value = "pod的状态") + private String status; + + @ApiModelProperty(value = "node的name") + private String nodeName; + + @ApiModelProperty(value = "pod的创建时间") + private String podCreateTime; + + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/ResourceSpecsCreateDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/ResourceSpecsCreateDTO.java new file mode 100644 index 0000000..7c6f44e --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/ResourceSpecsCreateDTO.java @@ -0,0 +1,74 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import lombok.experimental.Accessors; +import org.dubhe.biz.base.constant.MagicNumConstant; +import org.dubhe.biz.base.constant.StringConstant; +import org.hibernate.validator.constraints.Length; + +import javax.validation.constraints.*; +import java.io.Serializable; + +/** + * @description 资源规格创建 + * @date 2021-05-27 + */ +@Data +@Accessors(chain = true) +public class ResourceSpecsCreateDTO implements Serializable { + + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "规格名称", required = true) + @NotBlank(message = "规格名称不能为空") + @Length(max = MagicNumConstant.THIRTY_TWO, message = "规格名称错误-输入长度不能超过32个字符") + @Pattern(regexp = StringConstant.REGEXP_SPECS, message = "规格名称支持字母、数字、汉字、英文横杠、下划线和空白字符") + private String specsName; + + @ApiModelProperty(value = "所属业务场景(0:通用,1:dubhe-notebook,2:dubhe-train,3:dubhe-serving)", required = true) + @NotNull(message = "所属业务场景不能为空") + @Min(value = MagicNumConstant.ZERO, message = "所属业务场景错误") + @Max(value = MagicNumConstant.THREE, message = "所属业务场景错误") + private Integer module; + + @ApiModelProperty(value = "CPU数量,单位:核", required = true) + @NotNull(message = "CPU数量不能为空") + @Min(value = MagicNumConstant.ZERO, message = "CPU数量不能小于0") + @Max(value = MagicNumConstant.TWO_BILLION, message = "CPU数量超限") + private Integer cpuNum; + + @ApiModelProperty(value = "GPU数量,单位:核", required = true) + @NotNull(message = "GPU数量不能为空") + @Min(value = MagicNumConstant.ZERO, message = "GPU数量不能小于0") + @Max(value = MagicNumConstant.TWO_BILLION, message = "GPU数量超限") + private Integer gpuNum; + + @ApiModelProperty(value = "内存大小,单位:M", required = true) + @NotNull(message = "内存数值不能为空") + @Min(value = MagicNumConstant.ZERO, message = "内存不能小于0") + @Max(value = MagicNumConstant.TWO_BILLION, message = "内存数值超限") + private Integer memNum; + + @ApiModelProperty(value = "工作空间的存储配额,单位:M", required = true) + @NotNull(message = "工作空间的存储配额不能为空") + @Min(value = MagicNumConstant.ZERO, message = "工作空间的存储配额不能小于0") + @Max(value = MagicNumConstant.TWO_BILLION, message = "工作空间的存储配额超限") + private Integer workspaceRequest; +} \ No newline at end of file diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/ResourceSpecsDeleteDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/ResourceSpecsDeleteDTO.java new file mode 100644 index 0000000..a4e4a08 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/ResourceSpecsDeleteDTO.java @@ -0,0 +1,40 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import lombok.experimental.Accessors; + +import javax.validation.constraints.NotNull; +import java.io.Serializable; +import java.util.Set; + +/** + * @description 资源规格删除 + * @date 2021-05-27 + */ +@Data +@Accessors(chain = true) +public class ResourceSpecsDeleteDTO implements Serializable { + + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "id", required = true) + @NotNull(message = "id不能为空") + private Set ids; +} \ No newline at end of file diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/ResourceSpecsQueryDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/ResourceSpecsQueryDTO.java new file mode 100644 index 0000000..ff7c247 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/ResourceSpecsQueryDTO.java @@ -0,0 +1,51 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import lombok.experimental.Accessors; +import org.dubhe.biz.base.constant.MagicNumConstant; +import org.dubhe.biz.db.base.PageQueryBase; +import org.hibernate.validator.constraints.Length; + +import javax.validation.constraints.Max; +import javax.validation.constraints.Min; +import java.io.Serializable; + +/** + * @description 查询资源规格 + * @date 2021-05-27 + */ +@Data +@Accessors(chain = true) +public class ResourceSpecsQueryDTO extends PageQueryBase implements Serializable { + + private static final long serialVersionUID = 1L; + + @ApiModelProperty("规格名称") + @Length(max = MagicNumConstant.THIRTY_TWO, message = "规格名称错误") + private String specsName; + + @ApiModelProperty("规格类型(0为CPU, 1为GPU)") + private Boolean resourcesPoolType; + + @ApiModelProperty("所属业务场景(0:通用,1:dubhe-notebook,2:dubhe-train,3:dubhe-serving)") + @Min(value = MagicNumConstant.ZERO, message = "所属业务场景错误") + @Max(value = MagicNumConstant.THREE, message = "所属业务场景错误") + private Integer module; +} \ No newline at end of file diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/ResourceSpecsUpdateDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/ResourceSpecsUpdateDTO.java new file mode 100644 index 0000000..3662bb1 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/ResourceSpecsUpdateDTO.java @@ -0,0 +1,77 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import lombok.experimental.Accessors; +import org.dubhe.biz.base.constant.MagicNumConstant; +import org.dubhe.biz.base.constant.StringConstant; +import org.hibernate.validator.constraints.Length; + +import javax.validation.constraints.Max; +import javax.validation.constraints.Min; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Pattern; +import java.io.Serializable; + +/** + * @description 资源规格修改 + * @date 2021-05-27 + */ +@Data +@Accessors(chain = true) +public class ResourceSpecsUpdateDTO implements Serializable { + + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "id", required = true) + @NotNull(message = "id不能为null") + @Min(value = MagicNumConstant.ONE, message = "id必须大于1") + private Long id; + + @ApiModelProperty(value = "规格名称") + @Length(max = MagicNumConstant.THIRTY_TWO, message = "规格名称错误-输入长度不能超过32个字符") + @Pattern(regexp = StringConstant.REGEXP_SPECS, message = "规格名称支持字母、数字、汉字、英文横杠、下划线和空白字符") + private String specsName; + + @ApiModelProperty(value = "所属业务场景(0:通用,1:dubhe-notebook,2:dubhe-train,3:dubhe-serving)", required = true) + @NotNull(message = "所属业务场景不能为空") + @Min(value = MagicNumConstant.ZERO, message = "所属业务场景错误") + @Max(value = MagicNumConstant.THREE, message = "所属业务场景错误") + private Integer module; + + @ApiModelProperty(value = "CPU数量,单位:核") + @Min(value = MagicNumConstant.ZERO, message = "CPU数量不能小于0") + @Max(value = MagicNumConstant.TWO_BILLION, message = "CPU数量超限") + private Integer cpuNum; + + @ApiModelProperty(value = "GPU数量,单位:核") + @Min(value = MagicNumConstant.ZERO, message = "GPU数量不能小于0") + @Max(value = MagicNumConstant.TWO_BILLION, message = "GPU数量超限") + private Integer gpuNum; + + @ApiModelProperty(value = "内存大小,单位:M") + @Min(value = MagicNumConstant.ZERO, message = "内存不能小于0") + @Max(value = MagicNumConstant.TWO_BILLION, message = "内存数值超限") + private Integer memNum; + + @ApiModelProperty(value = "工作空间的存储配额,单位:M") + @Min(value = MagicNumConstant.ZERO, message = "工作空间的存储配额不能小于0") + @Max(value = MagicNumConstant.TWO_BILLION, message = "工作空间的存储配额超限") + private Integer workspaceRequest; +} \ No newline at end of file diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/RoleAuthUpdateDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/RoleAuthUpdateDTO.java new file mode 100644 index 0000000..c47b1ce --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/RoleAuthUpdateDTO.java @@ -0,0 +1,39 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import lombok.Data; + +import javax.validation.constraints.NotNull; +import java.io.Serializable; +import java.util.Set; + +/** + * @description + * @date 2021-05-17 + */ +@Data +public class RoleAuthUpdateDTO implements Serializable { + + private static final long serialVersionUID = 1L; + + @NotNull(message = "角色id不能为空") + private Long roleId; + + @NotNull(message = "权限组id不能为空") + private Set authIds; +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/RoleCreateDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/RoleCreateDTO.java new file mode 100644 index 0000000..81bddd1 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/RoleCreateDTO.java @@ -0,0 +1,55 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import lombok.Data; +import org.dubhe.admin.domain.entity.Menu; + +import javax.validation.constraints.Size; +import java.io.Serializable; +import java.util.Set; + +/** + * @description 角色创建 DTO + * @date 2020-06-29 + */ +@Data +public class RoleCreateDTO implements Serializable { + + private static final long serialVersionUID = -8685787591892312697L; + + private Long id; + + @Size(max = 255, message = "名称长度不能超过255") + private String name; + + /** + * 权限 + */ + @Size(max = 255, message = "默认权限长度不能超过255") + private String permission; + + @Size(max = 255, message = "备注长度不能超过255") + private String remark; + + private Set menus; + + private Boolean deleted; + + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/RoleDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/RoleDTO.java new file mode 100644 index 0000000..23b084b --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/RoleDTO.java @@ -0,0 +1,48 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import lombok.Data; +import org.dubhe.admin.domain.vo.AuthVO; + +import java.io.Serializable; +import java.sql.Timestamp; +import java.util.Set; + +/** + * @description 角色的实体类 + * @date 2020-06-01 + */ +@Data +public class RoleDTO implements Serializable { + + private static final long serialVersionUID = -7250301719333643312L; + private Long id; + + private String name; + + private String remark; + + private String permission; + + private Set menus; + + private Set auths; + + private Timestamp createTime; +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/RoleDeleteDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/RoleDeleteDTO.java new file mode 100644 index 0000000..734b7db --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/RoleDeleteDTO.java @@ -0,0 +1,38 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import lombok.Data; + +import javax.validation.constraints.NotEmpty; +import java.io.Serializable; +import java.util.Set; + +/** + * @description 角色删除 dto + * @date 2020-06-29 + */ +@Data +public class RoleDeleteDTO implements Serializable { + + private static final long serialVersionUID = -6599428238298923816L; + + @NotEmpty(message = "角色id不能为空") + private Set ids; + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/RoleQueryDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/RoleQueryDTO.java new file mode 100644 index 0000000..0986cc4 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/RoleQueryDTO.java @@ -0,0 +1,44 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import lombok.Data; +import org.dubhe.biz.db.annotation.Query; + +import java.io.Serializable; +import java.sql.Timestamp; +import java.util.List; + +/** + * @description 角色请求实体DTO + * @date 2020-06-01 + */ +@Data +public class RoleQueryDTO implements Serializable { + + private static final long serialVersionUID = 1266792048261542801L; + @Query(blurry = "name,remark") + private String blurry; + + @Query(propName = "create_time", type = Query.Type.BETWEEN) + private List createTime; + + @Query(propName = "deleted", type = Query.Type.EQ) + private Boolean deleted = false; + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/RoleSmallDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/RoleSmallDTO.java new file mode 100644 index 0000000..35642c6 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/RoleSmallDTO.java @@ -0,0 +1,35 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import lombok.Data; + +import java.io.Serializable; + +/** + * @description 角色的实体转换 + * @date 2020-06-01 + */ +@Data +public class RoleSmallDTO implements Serializable { + + private static final long serialVersionUID = -6601893040730122984L; + private Long id; + + private String name; +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/RoleUpdateDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/RoleUpdateDTO.java new file mode 100644 index 0000000..ed7402e --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/RoleUpdateDTO.java @@ -0,0 +1,75 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import lombok.Data; +import org.dubhe.admin.domain.entity.Menu; + +import javax.validation.constraints.Size; +import java.io.Serializable; +import java.util.Objects; +import java.util.Set; + +/** + * @description 角色修改 DTO + * @date 2020-06-29 + */ +@Data +public class RoleUpdateDTO implements Serializable { + + private static final long serialVersionUID = -8685787591892312697L; + + private Long id; + + @Size(max = 255, message = "名称长度不能超过255") + private String name; + + /** + * 权限 + */ + @Size(max = 255, message = "默认权限长度不能超过255") + private String permission; + + @Size(max = 255, message = "备注长度不能超过255") + private String remark; + + private Set menus; + + private Boolean deleted; + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + RoleUpdateDTO role = (RoleUpdateDTO) o; + return Objects.equals(id, role.id); + } + + @Override + public int hashCode() { + return Objects.hash(id); + } + + public @interface Update { + } + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/TeamCreateDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/TeamCreateDTO.java new file mode 100644 index 0000000..3f54027 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/TeamCreateDTO.java @@ -0,0 +1,52 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import lombok.Data; +import org.dubhe.admin.domain.entity.User; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; +import java.io.Serializable; +import java.sql.Timestamp; +import java.util.List; + +/** + * @description 团队创建实体 + * @date 2020-06-29 + */ +@Data +public class TeamCreateDTO implements Serializable { + + private static final long serialVersionUID = 8922409236439269071L; + + + @NotBlank + private String name; + + @NotNull + private Boolean enabled; + + /** + * 团队成员 + */ + private List teamUserList; + + private Timestamp createTime; + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/TeamQueryDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/TeamQueryDTO.java new file mode 100644 index 0000000..c54f0ac --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/TeamQueryDTO.java @@ -0,0 +1,50 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import lombok.Data; +import org.dubhe.biz.db.annotation.Query; + +import java.io.Serializable; +import java.sql.Timestamp; +import java.util.List; +import java.util.Set; + +/** + * @description 团队查询DTO + * @date 2020-06-01 + */ +@Data +public class TeamQueryDTO implements Serializable { + + private static final long serialVersionUID = 700075706114767404L; + @Query(type = Query.Type.IN, propName = "id") + private Set ids; + + @Query(type = Query.Type.LIKE) + private String name; + + @Query + private Boolean enabled; + + @Query + private Long pid; + + @Query(propName = "create_time", type = Query.Type.BETWEEN) + private List createTime; +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/TeamUpdateDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/TeamUpdateDTO.java new file mode 100644 index 0000000..1a7366a --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/TeamUpdateDTO.java @@ -0,0 +1,55 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import lombok.Data; +import org.dubhe.admin.domain.entity.User; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; +import java.io.Serializable; +import java.sql.Timestamp; +import java.util.List; + +/** + * @description + * @date 2020-06-29 + */ +@Data +public class TeamUpdateDTO implements Serializable { + + private static final long serialVersionUID = 8922409236439269071L; + + @NotNull + private Long id; + + @NotBlank + private String name; + + @NotNull + private Boolean enabled; + + /** + * 团队成员 + */ + private List teamUserList; + + private Timestamp createTime; + + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/TeamUserRoleSmallDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/TeamUserRoleSmallDTO.java new file mode 100644 index 0000000..7887a55 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/TeamUserRoleSmallDTO.java @@ -0,0 +1,33 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import lombok.Data; + +import java.io.Serializable; + +/** + * @description 团队用户角色DTO + * @date 2020-06-01 + */ +@Data +public class TeamUserRoleSmallDTO implements Serializable { + private static final long serialVersionUID = 6589829002637730619L; + private Long id; + private RoleSmallDTO role; +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/UserAvatarUpdateDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/UserAvatarUpdateDTO.java new file mode 100644 index 0000000..4044acc --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/UserAvatarUpdateDTO.java @@ -0,0 +1,34 @@ +/** + * Copyright 2019-2020 Zheng Jie + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import lombok.Data; + +import javax.validation.constraints.Size; + +/** + * @description 修改头像 + * @date 2020-06-01 + */ +@Data +public class UserAvatarUpdateDTO { + + @Size(max = 255, message = "名称长度不能超过255") + private String realName; + + @Size(max = 255, message = "头像长度不能超过255") + private String path; +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/UserCenterUpdateDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/UserCenterUpdateDTO.java new file mode 100644 index 0000000..3bd4c51 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/UserCenterUpdateDTO.java @@ -0,0 +1,55 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import org.dubhe.admin.domain.entity.User; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Pattern; +import javax.validation.constraints.Size; +import java.io.Serializable; + +/** + * @description 用户中心修改DTO + * @date 2020-06-29 + */ +@Data +public class UserCenterUpdateDTO implements Serializable { + + private static final long serialVersionUID = -6196691710092809498L; + @NotNull(groups = User.Update.class) + private Long id; + + @ApiModelProperty(value = "用户昵称") + @NotBlank(message = "用户昵称不能为空") + @Size(max = 255, message = "昵称长度不能超过255") + private String nickName; + + @ApiModelProperty(value = "性别") + private String sex; + + @NotBlank + @Pattern(regexp = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$", message = "手机号格式有误") + private String phone; + + private String remark; + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/UserCreateDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/UserCreateDTO.java new file mode 100644 index 0000000..d9ee743 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/UserCreateDTO.java @@ -0,0 +1,84 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import lombok.Data; +import org.dubhe.admin.domain.entity.Role; +import org.dubhe.admin.domain.entity.UserAvatar; + +import javax.validation.constraints.*; +import java.io.Serializable; +import java.util.Date; +import java.util.List; + +/** + * @description 用户创建DTO + * @date 2020-06-29 + */ +@Data +public class UserCreateDTO implements Serializable { + + private static final long serialVersionUID = -6196691710092809498L; + + + @NotBlank + @Size(max = 255, message = "名称长度不能超过255") + private String username; + + /** + * 用户昵称 + */ + @NotBlank + @Size(max = 255, message = "昵称长度不能超过255") + private String nickName; + + /** + * 性别 + */ + private String sex; + + @NotBlank + @Pattern(regexp = "^([\\w-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([\\w-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$", message = "邮箱地址格式有误") + private String email; + + @NotBlank + @Pattern(regexp = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$", message = "手机号格式有误") + private String phone; + + @NotNull + private Boolean enabled; + + private String password; + + private Date lastPasswordResetTime; + + @Size(max = 255, message = "昵称长度不能超过255") + private String remark; + + private Long avatarId; + + + private UserAvatar userAvatar; + + + @NotEmpty + private List roles; + + private Boolean deleted; + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/UserDeleteDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/UserDeleteDTO.java new file mode 100644 index 0000000..5c6d774 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/UserDeleteDTO.java @@ -0,0 +1,40 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import javax.validation.constraints.NotEmpty; +import java.io.Serializable; +import java.util.Set; + +/** + * @description 用户删除 dto + * @date 2020-06-29 + */ +@Data +public class UserDeleteDTO implements Serializable { + + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "用户id集合") + @NotEmpty + private Set ids; + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/UserEmailUpdateDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/UserEmailUpdateDTO.java new file mode 100644 index 0000000..d80f70f --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/UserEmailUpdateDTO.java @@ -0,0 +1,62 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Pattern; +import java.io.Serializable; + +/** + * @description 用户邮箱修改信息 + * @date 2020-06-01 + */ +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +@ApiModel(value = "邮箱修改请求实体", description = "邮箱修改请求实体") +public class UserEmailUpdateDTO implements Serializable { + + private static final long serialVersionUID = -5997222212073811466L; + + @NotNull(message = "用户ID不能为空") + @ApiModelProperty(value = "用户ID", name = "userId", example = "1") + private Long userId; + + @Pattern(regexp = "^([\\w-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([\\w-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$", message = "邮箱地址格式有误") + @NotEmpty(message = "邮箱地址不能为空") + @ApiModelProperty(value = "邮箱地址", name = "email", example = "xx@163.com") + private String email; + + + @NotNull(message = "密码不能为空") + @ApiModelProperty(value = "密码", name = "password", example = "123456") + private String password; + + @NotNull(message = "激活码不能为空") + @ApiModelProperty(value = "激活码", name = "code", example = "998877") + private String code; +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/UserGroupDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/UserGroupDTO.java new file mode 100644 index 0000000..00e3d8f --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/UserGroupDTO.java @@ -0,0 +1,50 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import org.hibernate.validator.constraints.Length; + +import javax.validation.constraints.NotBlank; +import java.io.Serializable; +import java.util.Set; + +/** + * @description 新增用户组实体DTO + * @date 2021-05-08 + */ +@Data +public class UserGroupDTO implements Serializable { + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "用户组id") + private Long id; + + @ApiModelProperty(value = "用户组名称") + @NotBlank(message = "用户组名称不能为空") + @Length(max = 32, message = "名称长度不能超过32") + private String name; + + @ApiModelProperty("用户组描述") + @Length(max = 255, message = "描述长度不能超过255") + private String description; + + @ApiModelProperty(value = "用户id集合") + private Set userIds; + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/UserGroupDeleteDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/UserGroupDeleteDTO.java new file mode 100644 index 0000000..b8477b6 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/UserGroupDeleteDTO.java @@ -0,0 +1,36 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import lombok.Data; + +import javax.validation.constraints.NotNull; +import java.io.Serializable; +import java.util.Set; + +/** + * @description 删除用户组DTO + * @date 2021-05-11 + */ +@Data +public class UserGroupDeleteDTO implements Serializable { + + private static final long serialVersionUID = 1L; + + @NotNull(message = "用户组id不能为空") + private Set ids; +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/UserGroupQueryDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/UserGroupQueryDTO.java new file mode 100644 index 0000000..768fe72 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/UserGroupQueryDTO.java @@ -0,0 +1,41 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.experimental.Accessors; +import org.dubhe.biz.db.base.PageQueryBase; + +import java.io.Serializable; + +/** + * @description 获取用户组信息 + * @date 2021-05-06 + */ +@Data +@Accessors(chain = true) +@EqualsAndHashCode +public class UserGroupQueryDTO extends PageQueryBase implements Serializable { + + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "用户组id或名称") + private String keyword; + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/UserGroupUpdDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/UserGroupUpdDTO.java new file mode 100644 index 0000000..2b10922 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/UserGroupUpdDTO.java @@ -0,0 +1,43 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import javax.validation.constraints.NotNull; +import java.io.Serializable; +import java.util.Set; + +/** + * @description 用户组成员操作DTO + * @date 2021-05-11 + */ +@Data +public class UserGroupUpdDTO implements Serializable { + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "用户组id") + @NotNull(message = "用户组id不能为空") + private Long groupId; + + @ApiModelProperty(value = "用户id集合") + private Set userIds; + + @ApiModelProperty(value = "角色id集合") + private Set roleIds; +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/UserPassUpdateDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/UserPassUpdateDTO.java new file mode 100644 index 0000000..387bf62 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/UserPassUpdateDTO.java @@ -0,0 +1,36 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import lombok.Data; + +import javax.validation.constraints.Size; + +/** + * @description 修改密码的 + * @date 2020-06-01 + */ +@Data +public class UserPassUpdateDTO { + + @Size(max = 255, message = "密码长度不能超过255") + private String oldPass; + + @Size(max = 255, message = "密码长度不能超过255") + private String newPass; +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/UserQueryDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/UserQueryDTO.java new file mode 100644 index 0000000..feedf31 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/UserQueryDTO.java @@ -0,0 +1,53 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import lombok.Data; +import org.dubhe.biz.db.annotation.Query; + +import java.io.Serializable; +import java.sql.Timestamp; +import java.util.List; + +/** + * @description 用户查询DTO + * @date 2020-06-01 + */ + +@Data +public class UserQueryDTO implements Serializable { + + private static final long serialVersionUID = -6863842533017963450L; + @Query + private Long id; + + @Query(blurry = "email,username,nick_name") + private String blurry; + + @Query + private Boolean enabled; + + @Query(propName = "deleted", type = Query.Type.EQ) + private Boolean deleted = false; + + private Long roleId; + + + @Query(propName = "create_time", type = Query.Type.BETWEEN) + private List createTime; +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/UserRegisterDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/UserRegisterDTO.java new file mode 100644 index 0000000..afcc1f5 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/UserRegisterDTO.java @@ -0,0 +1,72 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Pattern; +import java.io.Serializable; + +/** + * @description 用户注册请求实体 + * @date 2020-06-01 + */ +@Data +@AllArgsConstructor +@NoArgsConstructor +@ApiModel(value = "用户注册请求实体", description = "用户注册请求实体") +public class UserRegisterDTO implements Serializable { + + private static final long serialVersionUID = -7351676930575145394L; + + @ApiModelProperty(value = "账号", name = "username", example = "test") + @NotEmpty(message = "账号不能为空") + private String username; + + @ApiModelProperty(value = "昵称", name = "nickName", example = "xt") + private String nickName; + + @ApiModelProperty(value = "性别", name = "sex", example = "1") + private Integer sex; + + @NotEmpty(message = "邮箱地址不能为空") + @Pattern(regexp = "^([\\w-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([\\w-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$", message = "邮箱地址格式有误") + @ApiModelProperty(value = "邮箱地址", name = "email", example = "xxx@163.com") + private String email; + + @NotNull(message = "手机号不能为空") + @Pattern(regexp = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$", message = "手机号格式有误") + @ApiModelProperty(value = "手机号", name = "phone", example = "13823370116") + private String phone; + + + @NotNull(message = "密码不能为空") + @ApiModelProperty(value = "密码", name = "password", example = "123456") + private String password; + + @NotNull(message = "激活码不能为空") + @ApiModelProperty(value = "激活码", name = "code", example = "998877") + private String code; + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/UserRegisterMailDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/UserRegisterMailDTO.java new file mode 100644 index 0000000..739460c --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/UserRegisterMailDTO.java @@ -0,0 +1,51 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Pattern; +import java.io.Serializable; + +/** + * @description 用户注册邮箱请求实体 + * @date 2020-06-01 + */ +@Data +@AllArgsConstructor +@NoArgsConstructor +@ApiModel(value = "发送邮箱验证码请求实体", description = "发送邮箱验证码请求实体") +public class UserRegisterMailDTO implements Serializable { + private static final long serialVersionUID = 5063855150803214253L; + + @NotNull(message = "类型不能为空") + @ApiModelProperty(value = "类型 1 用户注册 2 修改邮箱 3 其他 4 忘记密码", name = "type", example = "1") + private Integer type; + + @NotEmpty(message = "邮箱地址不能为空") + @Pattern(regexp = "^([\\w-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([\\w-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$", message = "邮箱地址格式有误") + @ApiModelProperty(value = "邮箱地址", name = "email", example = "xxx@163.com") + private String email; + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/UserResetPasswordDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/UserResetPasswordDTO.java new file mode 100644 index 0000000..9453926 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/UserResetPasswordDTO.java @@ -0,0 +1,57 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Pattern; +import java.io.Serializable; + +/** + * @description 用户重置密码请求实体 + * @date 2020-06-01 + */ +@Data +@AllArgsConstructor +@NoArgsConstructor +@ApiModel(value = "用户重置密码请求实体", description = "用户重置密码请求实体") +public class UserResetPasswordDTO implements Serializable { + + + private static final long serialVersionUID = -4249894291904235207L; + + @NotEmpty(message = "邮箱地址不能为空") + @Pattern(regexp = "^([\\w-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([\\w-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$", message = "邮箱地址格式有误") + @ApiModelProperty(value = "邮箱地址", name = "email", example = "xxx@163.com") + private String email; + + @NotNull(message = "密码不能为空") + @ApiModelProperty(value = "密码", name = "password", example = "123456") + private String password; + + @NotNull(message = "激活码不能为空") + @ApiModelProperty(value = "激活码", name = "code", example = "998877") + private String code; + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/UserRoleUpdateDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/UserRoleUpdateDTO.java new file mode 100644 index 0000000..b3cd28d --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/UserRoleUpdateDTO.java @@ -0,0 +1,43 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import javax.validation.constraints.NotNull; +import java.io.Serializable; +import java.util.Set; + +/** + * @description 批量修改用户组用户的角色 + * @date 2021-05-12 + */ +@Data +public class UserRoleUpdateDTO implements Serializable { + + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "用户组id") + @NotNull(message = "用户组id不能为空") + private Long groupId; + + @ApiModelProperty("角色id集合") + @NotNull(message = "角色id不能为空") + private Set roleIds; + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/UserStateUpdateDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/UserStateUpdateDTO.java new file mode 100644 index 0000000..c8d59c4 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/UserStateUpdateDTO.java @@ -0,0 +1,40 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import javax.validation.constraints.NotNull; +import java.io.Serializable; + +/** + * @description 批量修改用户组用户状态DTO + * @date 2021-05-12 + */ +@Data +public class UserStateUpdateDTO implements Serializable { + + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value ="用户组id" ) + @NotNull(message = "用户组id不能为空") + private Long groupId; + + @ApiModelProperty("用户状态:激活:true,锁定:false") + private boolean enabled; +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/UserUpdateDTO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/UserUpdateDTO.java new file mode 100644 index 0000000..9215ca8 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/UserUpdateDTO.java @@ -0,0 +1,86 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.dto; + +import lombok.Data; +import org.dubhe.admin.domain.entity.Role; +import org.dubhe.admin.domain.entity.User; +import org.dubhe.admin.domain.entity.UserAvatar; + +import javax.validation.constraints.*; +import java.io.Serializable; +import java.util.Date; +import java.util.List; + +/** + * @description 用户修改DTO + * @date 2020-06-29 + */ +@Data +public class UserUpdateDTO implements Serializable { + + private static final long serialVersionUID = -6196691710092809498L; + @NotNull(groups = User.Update.class) + private Long id; + + @NotBlank + @Size(max = 255, message = "名称长度不能超过255") + private String username; + + /** + * 用户昵称 + */ + @NotBlank + @Size(max = 255, message = "昵称长度不能超过255") + private String nickName; + + /** + * 性别 + */ + private String sex; + + @NotBlank + @Pattern(regexp = "^([\\w-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([\\w-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$", message = "邮箱地址格式有误") + private String email; + + @NotBlank + @Pattern(regexp = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$", message = "手机号格式有误") + private String phone; + + @NotNull + private Boolean enabled; + + private String password; + + private Date lastPasswordResetTime; + + @Size(max = 255, message = "昵称长度不能超过255") + private String remark; + + private Long avatarId; + + + private UserAvatar userAvatar; + + + @NotEmpty + private List roles; + + private Boolean deleted; + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/entity/Auth.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/entity/Auth.java new file mode 100644 index 0000000..1570deb --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/entity/Auth.java @@ -0,0 +1,43 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import org.dubhe.biz.db.entity.BaseEntity; + +/** + * @description 权限组实体类 + * @date 2021-05-14 + */ +@Data +@TableName("auth") +public class Auth extends BaseEntity { + + @TableId(value = "id", type = IdType.AUTO) + private Long id; + + @TableField(value = "auth_code") + private String authCode; + + @TableField(value = "description") + private String description; + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/entity/AuthPermission.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/entity/AuthPermission.java new file mode 100644 index 0000000..d74dd3a --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/entity/AuthPermission.java @@ -0,0 +1,45 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.io.Serializable; + +/** + * @description + * @date 2021-05-14 + */ +@Data +@TableName("auth_permission") +public class AuthPermission implements Serializable { + private static final long serialVersionUID = 1L; + + /** + * 权限组id + */ + @TableField(value = "auth_id") + private Long authId; + + /** + * 权限id + */ + @TableField(value = "permission_id") + private Long permissionId; +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/entity/DataSequence.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/entity/DataSequence.java new file mode 100644 index 0000000..b1eddb3 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/entity/DataSequence.java @@ -0,0 +1,45 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +/** + * @description 序列表 + * @date 2020-09-23 + */ +@Data +@TableName("data_sequence") +public class DataSequence { + + @TableId(value = "id", type = IdType.AUTO) + private Long id; + + @TableField(value = "business_code") + private String businessCode; + + @TableField(value = "start") + private Long start; + + @TableField(value = "step") + private Long step; + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/entity/Dict.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/entity/Dict.java new file mode 100644 index 0000000..14824fd --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/entity/Dict.java @@ -0,0 +1,75 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.hibernate.validator.constraints.Length; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; +import java.io.Serializable; +import java.sql.Timestamp; +import java.util.List; + +/** + * @description 字典实体 + * @date 2020-06-01 + */ +@Data +@TableName("dict") +@Builder +@AllArgsConstructor +@NoArgsConstructor +public class Dict implements Serializable { + + private static final long serialVersionUID = -3995510721958462699L; + @TableId(value = "id", type = IdType.AUTO) + @NotNull(groups = Update.class) + private Long id; + + /** + * 名称 + */ + @TableField(value = "name") + @NotBlank + @Length(max = 255, message = "名称长度不能超过255") + private String name; + + /** + * 备注 + */ + @TableField(value = "remark") + @Length(max = 255, message = "备注长度不能超过255") + private String remark; + + + @TableField(value = "create_time") + private Timestamp createTime; + + @TableField(exist = false) + private List dictDetails; + + public @interface Update { + } +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/entity/DictDetail.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/entity/DictDetail.java new file mode 100644 index 0000000..cd3dc60 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/entity/DictDetail.java @@ -0,0 +1,77 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.hibernate.validator.constraints.Length; + +import javax.validation.constraints.NotNull; +import java.io.Serializable; +import java.sql.Timestamp; + +/** + * @description 字典详情实体 + * @date 2020-06-01 + */ +@Data +@TableName("dict_detail") +@Builder +@AllArgsConstructor +@NoArgsConstructor +public class DictDetail implements Serializable { + + private static final long serialVersionUID = 299242717738411209L; + @TableId(value = "id", type = IdType.AUTO) + @NotNull(groups = Update.class) + private Long id; + + /** + * 字典标签 + */ + @TableField(value = "label") + @Length(max = 255, message = "字典标签长度不能超过255") + private String label; + + /** + * 字典值 + */ + @TableField(value = "value") + @Length(max = 255, message = "字典值长度不能超过255") + private String value; + + /** + * 排序 + */ + @TableField(value = "sort") + private String sort = "999"; + + @TableField(value = "dict_id") + private Long dictId; + + @TableField(value = "create_time") + private Timestamp createTime; + + public @interface Update { + } +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/entity/Group.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/entity/Group.java new file mode 100644 index 0000000..99e18c0 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/entity/Group.java @@ -0,0 +1,46 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.dubhe.biz.db.entity.BaseEntity; + +/** + * @description 用户组实体类 + * @date 2021-05-06 + */ +@Data +@AllArgsConstructor +@NoArgsConstructor +@TableName("pt_group") +public class Group extends BaseEntity { + + @TableId(value = "id", type = IdType.AUTO) + private Long id; + + @TableField(value = "name") + private String name; + + @TableField(value = "description") + private String description; +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/entity/Log.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/entity/Log.java new file mode 100644 index 0000000..50eca54 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/entity/Log.java @@ -0,0 +1,106 @@ +/** + * Copyright 2019-2020 Zheng Jie + * + * Licensed 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 org.dubhe.admin.domain.entity; + + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.io.Serializable; +import java.sql.Timestamp; + +/** + * @description 日志实体 + * @date 2020-06-01 + */ +@Data +@TableName("log") +@NoArgsConstructor +public class Log implements Serializable { + + private static final long serialVersionUID = -4447644691937249474L; + @TableId(value = "id", type = IdType.AUTO) + private Long id; + + /** + * 操作用户 + */ + @TableField(value = "username") + private String username; + + /** + * 描述 + */ + @TableField(value = "description") + private String description; + + /** + * 方法名 + */ + @TableField(value = "label") + private String method; + + /** + * 参数 + */ + @TableField(value = "text") + private String params; + + /** + * 日志类型 + */ + @TableField(value = "log_type") + private String logType; + + /** + * 请求ip + */ + @TableField(value = "request_ip") + private String requestIp; + + /** + * 浏览器 + */ + @TableField(value = "browser") + private String browser; + + /** + * 请求耗时 + */ + @TableField(value = "time") + private Long time; + + /** + * 异常详细 + */ + @TableField(value = "exception_detail") + private byte[] exceptionDetail; + + /** + * 创建日期 + */ + @TableField(value = "create_time") + private Timestamp createTime; + + public Log(String logType, Long time) { + this.logType = logType; + this.time = time; + } +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/entity/Menu.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/entity/Menu.java new file mode 100644 index 0000000..0866505 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/entity/Menu.java @@ -0,0 +1,109 @@ +/** + * Copyright 2019-2020 Zheng Jie + * + * Licensed 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 org.dubhe.admin.domain.entity; + +import com.baomidou.mybatisplus.annotation.*; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.dubhe.biz.db.entity.BaseEntity; + +import java.io.Serializable; + +/** + * @description 菜单实体 + * @date 2020-11-30 + */ +@Data +@Builder +@AllArgsConstructor +@NoArgsConstructor +@TableName("menu") +public class Menu extends BaseEntity implements Serializable { + + private static final long serialVersionUID = 3100515433018008777L; + + @TableId(value = "id", type = IdType.AUTO) + private Long id; + + private String name; + + @TableField(value = "sort") + private Long sort = 999L; + + @TableField(value = "path") + private String path; + + @TableField(value = "component") + private String component; + + /** + * 类型,目录、菜单、按钮 + */ + @TableField(value = "type") + private Integer type; + + /** + * 权限 + */ + @TableField(value = "permission") + private String permission; + + @TableField(value = "component_name") + private String componentName; + + @TableField(value = "icon") + private String icon; + + /** + * 布局类型 + */ + @TableField(value = "layout") + private String layout; + + @TableField(value = "cache") + private Boolean cache; + + @TableField(value = "hidden") + private Boolean hidden; + + /** + * 上级菜单ID + */ + @TableField(value = "pid") + private Long pid; + + @TableField(value = "deleted",fill = FieldFill.INSERT) + private Boolean deleted; + + /** + * 回到上一级 + */ + @TableField(updateStrategy = FieldStrategy.IGNORED) + private String backTo; + + /** + * 扩展配置 + */ + @TableField(updateStrategy = FieldStrategy.IGNORED) + private String extConfig; + + + public @interface Update { + } +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/entity/Permission.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/entity/Permission.java new file mode 100644 index 0000000..6c55db9 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/entity/Permission.java @@ -0,0 +1,48 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.experimental.Accessors; +import org.dubhe.biz.db.entity.BaseEntity; + +/** + * @description + * @date 2021-04-26 + */ +@Data +@TableName("permission") +@Accessors(chain = true) +public class Permission extends BaseEntity { + + @TableId(value = "id", type = IdType.AUTO) + private Long id; + + @TableId(value = "pid") + private Long pid; + + @TableField(value = "name") + private String name; + + @TableField(value = "permission") + private String permission; + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/entity/ResourceSpecs.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/entity/ResourceSpecs.java new file mode 100644 index 0000000..a3f7307 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/entity/ResourceSpecs.java @@ -0,0 +1,87 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.experimental.Accessors; +import org.dubhe.biz.db.entity.BaseEntity; + +import javax.validation.constraints.NotNull; + +/** + * @description 资源规格实体类 + * @date 2021-05-27 + */ +@Data +@Accessors(chain = true) +@TableName("resource_specs") +public class ResourceSpecs extends BaseEntity { + + /** + * 主键ID + */ + @TableId(value = "id", type = IdType.AUTO) + @NotNull(groups = {Update.class}) + private Long id; + + /** + * 规格名称 + */ + @TableField(value = "specs_name") + private String specsName; + + /** + * 规格类型(0为CPU, 1为GPU) + */ + @TableField(value = "resources_pool_type") + private Boolean resourcesPoolType; + + /** + * 所属业务场景 + */ + @TableField(value = "module") + private Integer module; + + /** + * CPU数量,单位:m(毫核) + */ + @TableField(value = "cpu_num") + private Integer cpuNum; + + /** + * GPU数量,单位:核 + */ + @TableField(value = "gpu_num") + private Integer gpuNum; + + /** + * 内存大小,单位:Mi + */ + @TableField(value = "mem_num") + private Integer memNum; + + /** + * 工作空间的存储配额,单位:Mi + */ + @TableField(value = "workspace_request") + private Integer workspaceRequest; + +} \ No newline at end of file diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/entity/Role.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/entity/Role.java new file mode 100644 index 0000000..9c0f152 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/entity/Role.java @@ -0,0 +1,69 @@ +/** + * Copyright 2019-2020 Zheng Jie + * + * Licensed 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 org.dubhe.admin.domain.entity; + +import com.baomidou.mybatisplus.annotation.*; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.dubhe.biz.db.entity.BaseEntity; + +import java.io.Serializable; +import java.util.Set; + +/** + * @description 角色实体 + * @date 2020-11-29 + */ +@Data +@Builder +@AllArgsConstructor +@NoArgsConstructor +@TableName("role") +public class Role extends BaseEntity implements Serializable { + + private static final long serialVersionUID = -812009584744832371L; + + @TableId(value = "id", type = IdType.AUTO) + private Long id; + + @TableField(value = "name") + private String name; + + /** + * 权限 + */ + @TableField(value = "permission") + private String permission; + + @TableField(value = "remark") + private String remark; + + @TableField(exist = false) + private Set menus; + + @TableField(exist = false) + private Set auths; + + @TableField(value = "deleted", fill = FieldFill.INSERT) + private Boolean deleted = false; + + + public @interface Update { + } +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/entity/RoleAuth.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/entity/RoleAuth.java new file mode 100644 index 0000000..e5de66e --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/entity/RoleAuth.java @@ -0,0 +1,40 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.io.Serializable; + +/** + * @description + * @date 2021-05-17 + */ +@Data +@TableName("roles_auth") +public class RoleAuth implements Serializable { + + private static final long serialVersionUID = 1L; + + @TableField(value = "role_id") + private Long roleId; + + @TableField(value = "auth_id") + private Long authId; +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/entity/RoleMenu.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/entity/RoleMenu.java new file mode 100644 index 0000000..6c0fa74 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/entity/RoleMenu.java @@ -0,0 +1,49 @@ +/** + * Copyright 2019-2020 Zheng Jie + * + * Licensed 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 org.dubhe.admin.domain.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.io.Serializable; + + +/** + * @description 角色菜单关系实体 + * @date 2020-06-29 + */ +@Data +@Builder +@AllArgsConstructor +@NoArgsConstructor +@TableName("roles_menus") +public class RoleMenu implements Serializable { + + private static final long serialVersionUID = -6296866205797727963L; + + @TableField(value = "menu_id") + private Long menuId; + + @TableField(value = "role_id") + private Long roleId; + + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/entity/Team.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/entity/Team.java new file mode 100644 index 0000000..760fa47 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/entity/Team.java @@ -0,0 +1,68 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; +import java.sql.Timestamp; +import java.util.List; + +/** + * @description 团队实体 + * @date 2020-06-29 + */ +@TableName("team") +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class Team { + @TableId(value = "id", type = IdType.AUTO) + @NotNull(groups = Update.class) + private Long id; + + @TableField(value = "name") + @NotBlank + private String name; + + @TableField(value = "enabled") + @NotNull + private Boolean enabled; + + /** + * 团队成员 + */ + @TableField(exist = false) + private List teamUserList; + + @TableField(value = "create_time") + private Timestamp createTime; + + + public @interface Update { + } +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/entity/TeamUserRole.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/entity/TeamUserRole.java new file mode 100644 index 0000000..d3b59ec --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/entity/TeamUserRole.java @@ -0,0 +1,58 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.entity; +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import javax.validation.constraints.NotNull; +import java.io.Serializable; + +/** + * @description 团队用户关系实体 + * @date 2020-06-29 + */ +@Data +@TableName("teams_users_roles") +public class TeamUserRole implements Serializable { + + @TableId(value = "id", type = IdType.AUTO) + @NotNull() + private Long id; + + /** + * 团队 + */ + @TableField(exist = false) + private Team team; + + /** + * 用户 + */ + @TableField(exist = false) + private User user; + + /** + * 角色 + */ + @TableField(exist = false) + private Role role; + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/entity/User.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/entity/User.java new file mode 100644 index 0000000..ed413bd --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/entity/User.java @@ -0,0 +1,94 @@ +/** + * Copyright 2019-2020 Zheng Jie + * + * Licensed 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 org.dubhe.admin.domain.entity; + +import com.baomidou.mybatisplus.annotation.*; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.dubhe.biz.db.entity.BaseEntity; + +import javax.validation.constraints.NotEmpty; +import java.io.Serializable; +import java.util.Date; +import java.util.List; + + +/** + * @description 用户实体 + * @date 2020-11-29 + */ +@Data +@TableName("user") +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class User extends BaseEntity implements Serializable { + + private static final long serialVersionUID = -3836401769559845765L; + + @TableId(value = "id", type = IdType.AUTO) + private Long id; + + @TableField(value = "username") + private String username; + + /** + * 用户昵称 + */ + @TableField(value = "nick_name") + private String nickName; + + /** + * 性别 + */ + @TableField(value = "sex") + private String sex; + + @TableField(value = "email") + private String email; + + @TableField(value = "phone") + private String phone; + + @TableField(value = "enabled") + private Boolean enabled; + + @TableField(value = "password") + private String password; + + @TableField(value = "last_password_reset_time") + private Date lastPasswordResetTime; + + @TableField(value = "remark") + private String remark; + + @TableField(value = "avatar_id") + private Long avatarId; + + @TableField(value = "deleted",fill = FieldFill.INSERT) + private Boolean deleted = false; + + @TableField(exist = false) + private UserAvatar userAvatar; + + + @NotEmpty + @TableField(exist = false) + private List roles; + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/entity/UserAvatar.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/entity/UserAvatar.java new file mode 100644 index 0000000..7da9d67 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/entity/UserAvatar.java @@ -0,0 +1,58 @@ +/** + * Copyright 2019-2020 Zheng Jie + * + * Licensed 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 org.dubhe.admin.domain.entity; + +import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.dubhe.biz.db.entity.BaseEntity; + +import java.io.Serializable; + + +/** + * @description 用户头像实体 + * @date 2020-06-29 + */ +@Data +@NoArgsConstructor +@TableName("user_avatar") +public class UserAvatar extends BaseEntity implements Serializable { + + @TableId(value = "id", type = IdType.AUTO) + private Long id; + + @TableField(value = "real_name") + private String realName; + + @TableField(value = "path") + private String path; + + @TableField(value = "size") + private String size; + + public UserAvatar(UserAvatar userAvatar, String realName, String path, String size) { + this.id = ObjectUtil.isNotEmpty(userAvatar) ? userAvatar.getId() : null; + this.realName = realName; + this.path = path; + this.size = size; + } + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/entity/UserRole.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/entity/UserRole.java new file mode 100644 index 0000000..2e1f2eb --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/entity/UserRole.java @@ -0,0 +1,47 @@ +/** + * Copyright 2019-2020 Zheng Jie + * + * Licensed 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 org.dubhe.admin.domain.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.io.Serializable; + +/** + * @description 用户角色关系实体 + * @date 2020-11-29 + */ +@Data +@Builder +@AllArgsConstructor +@NoArgsConstructor +@TableName("users_roles") +public class UserRole implements Serializable { + + private static final long serialVersionUID = -6296866205797727963L; + + @TableField(value = "user_id") + private Long userId; + + @TableField(value = "role_id") + private Long roleId; + + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/vo/AuthVO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/vo/AuthVO.java new file mode 100644 index 0000000..669896c --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/vo/AuthVO.java @@ -0,0 +1,59 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.vo; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import org.dubhe.admin.domain.entity.Permission; + +import java.io.Serializable; +import java.sql.Timestamp; +import java.util.List; + +/** + * @description + * @date 2021-05-17 + */ +@Data +public class AuthVO implements Serializable { + + private static final long serialVersionUID = -1584916470133872539L; + + @ApiModelProperty("权限组id") + private Long id; + + @ApiModelProperty("权限组名称") + private String authCode; + + @ApiModelProperty("创建人") + private Long createUserId; + + @ApiModelProperty("修改人") + private Long updateUserId; + + @ApiModelProperty("创建时间") + private Timestamp createTime; + + @ApiModelProperty("修改时间") + private Timestamp updateTime; + + @ApiModelProperty("描述") + private String description; + + @ApiModelProperty("权限列表") + private List permissions; +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/vo/EmailVo.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/vo/EmailVo.java new file mode 100644 index 0000000..e5fb0f2 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/vo/EmailVo.java @@ -0,0 +1,41 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.vo; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.io.Serializable; + +/** + * @description 用户邮箱信息 + * @date 2020-06-01 + */ +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class EmailVo implements Serializable { + private static final long serialVersionUID = -5997222212073811466L; + + private String email; + + private String code; +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/vo/MenuMetaVo.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/vo/MenuMetaVo.java new file mode 100644 index 0000000..f6b96a6 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/vo/MenuMetaVo.java @@ -0,0 +1,39 @@ +/** + * Copyright 2019-2020 Zheng Jie + * + * Licensed 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 org.dubhe.admin.domain.vo; + +import lombok.AllArgsConstructor; +import lombok.Data; + +import java.io.Serializable; + +/** + * @description 菜单元数据 + * @date 2020-06-01 + */ +@Data +@AllArgsConstructor +public class MenuMetaVo implements Serializable { + + private static final long serialVersionUID = 4641840267582701511L; + private String title; + + private String icon; + + private String layout; + + private Boolean noCache; +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/vo/MenuVo.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/vo/MenuVo.java new file mode 100644 index 0000000..736b0d6 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/vo/MenuVo.java @@ -0,0 +1,44 @@ +/** + * Copyright 2019-2020 Zheng Jie + * + * Licensed 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 org.dubhe.admin.domain.vo; + +import com.fasterxml.jackson.annotation.JsonInclude; +import lombok.Data; + +import java.io.Serializable; +import java.util.List; + +/** + * @description 菜单VO + * @date 2020-06-01 + */ +@Data +@JsonInclude(JsonInclude.Include.NON_EMPTY) +public class MenuVo implements Serializable { + + private static final long serialVersionUID = 7145999097655311261L; + private String name; + + private String path; + + private Boolean hidden; + + private String component; + + private MenuMetaVo meta; + + private List children; +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/vo/PermissionVO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/vo/PermissionVO.java new file mode 100644 index 0000000..e87f44b --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/vo/PermissionVO.java @@ -0,0 +1,47 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.vo; + +import lombok.Data; + +import java.io.Serializable; +import java.sql.Timestamp; +import java.util.List; + +/** + * @description 权限VO + * @date 2021-05-31 + */ +@Data +public class PermissionVO implements Serializable { + + private static final long serialVersionUID = 1L; + + private Long id; + + private Long pid; + + private String permission; + + private String name; + + private Timestamp createTime; + + private Timestamp updateTime; + + private List children; +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/vo/ResourceSpecsQueryVO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/vo/ResourceSpecsQueryVO.java new file mode 100644 index 0000000..9099476 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/vo/ResourceSpecsQueryVO.java @@ -0,0 +1,71 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.vo; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import lombok.experimental.Accessors; + +import java.io.Serializable; +import java.sql.Timestamp; + +/** + * @description 资源规格查询结果封装类 + * @date 2021-05-27 + */ +@Data +@Accessors(chain = true) +public class ResourceSpecsQueryVO implements Serializable { + + private static final long serialVersionUID = 1L; + + @ApiModelProperty("主键ID") + private Long id; + + @ApiModelProperty("规格名称") + private String specsName; + + @ApiModelProperty("规格类型(0为CPU, 1为GPU)") + private Boolean resourcesPoolType; + + @ApiModelProperty("所属业务场景") + private Integer module; + + @ApiModelProperty("CPU数量,单位:核") + private Integer cpuNum; + + @ApiModelProperty("GPU数量,单位:核") + private Integer gpuNum; + + @ApiModelProperty("内存大小,单位:Mi") + private Integer memNum; + + @ApiModelProperty("工作空间的存储配额,单位:Mi") + private Integer workspaceRequest; + + @ApiModelProperty("创建人") + private Long createUserId; + + @ApiModelProperty("创建时间") + private Timestamp createTime; + + @ApiModelProperty("更新人") + private Long updateUserId; + + @ApiModelProperty("更新时间") + private Timestamp updateTime; +} \ No newline at end of file diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/vo/UserGroupVO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/vo/UserGroupVO.java new file mode 100644 index 0000000..6f5caf2 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/vo/UserGroupVO.java @@ -0,0 +1,54 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.domain.vo; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.io.Serializable; +import java.sql.Timestamp; + +/** + * @description 用户组信息 + * @date 2021-05-11 + */ +@Data +public class UserGroupVO implements Serializable { + + private static final long serialVersionUID = -1584916470133872539L; + + @ApiModelProperty("用户组Id") + private Long id; + + @ApiModelProperty("用户组名称") + private String name; + + @ApiModelProperty("创建人") + private Long createUserId; + + @ApiModelProperty("修改人") + private Long updateUserId; + + @ApiModelProperty("创建时间") + private Timestamp createTime; + + @ApiModelProperty("修改时间") + private Timestamp updateTime; + + @ApiModelProperty("描述") + private String description; +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/vo/UserVO.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/vo/UserVO.java new file mode 100644 index 0000000..b2fe687 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/domain/vo/UserVO.java @@ -0,0 +1,58 @@ +/** + * Copyright 2019-2020 Zheng Jie + * + * Licensed 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 org.dubhe.admin.domain.vo; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.io.Serializable; + +/** + * @description 用户VO + * @date 2020-06-29 + */ +@Data +@Builder +@AllArgsConstructor +@NoArgsConstructor +public class UserVO implements Serializable { + + private static final long serialVersionUID = -8697100416579599857L; + + /** + * 账号 + */ + private String username; + + /** + * 邮箱地址 + */ + private String email; + + /** + * 密码 : 账号 + md5 + */ + private String password; + + /** + * 是否有管理员权限 + */ + private Boolean is_staff; + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/enums/MenuTypeEnum.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/enums/MenuTypeEnum.java new file mode 100644 index 0000000..df761f6 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/enums/MenuTypeEnum.java @@ -0,0 +1,101 @@ +/** + * Copyright 2019-2020 Zheng Jie + * + * Licensed 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 org.dubhe.admin.enums; + +/** + * @description 菜单类型 + * @date 2020-06-01 + */ +public enum MenuTypeEnum { + + /** + * DIR_TYPE 目录 + */ + DIR_TYPE(0, "目录"), + + /** + * PAGE_TYPE 页面 + */ + PAGE_TYPE(1, "页面"), + + /** + * ACTION_TYPE 操作(权限) + */ + ACTION_TYPE(2, "操作"), + + /** + * LINK_TYPE 外链 + */ + LINK_TYPE(3, "外链"), + + /** + * OTHER_TYPE 其他 + */ + OTHER_TYPE(-1, "其他"), + + ; + + private Integer value; + + private String desc; + + MenuTypeEnum(Integer value, String desc) { + this.value = value; + this.desc = desc; + } + + public Integer getValue() { + return this.value; + } + + public String getDesc() { + return desc; + } + + public void setDesc(String desc) { + this.desc = desc; + } + + public static MenuTypeEnum getEnumValue(Integer value) { + switch (value) { + case 0: + return DIR_TYPE; + case 1: + return PAGE_TYPE; + case 2: + return ACTION_TYPE; + case 3: + return LINK_TYPE; + default: + return OTHER_TYPE; + } + } + + public static boolean isExist(Integer value) { + for (MenuTypeEnum itm : MenuTypeEnum.values()) { + if (value.compareTo(itm.getValue())==0) { + return true; + } + } + return false; + } + + @Override + public String toString() { + return "[" + this.value + "]" + this.desc; + } + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/enums/SystemNodeEnum.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/enums/SystemNodeEnum.java new file mode 100644 index 0000000..55d7b81 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/enums/SystemNodeEnum.java @@ -0,0 +1,80 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.enums; + +/** + * @description 节点枚举类 + * @date 2020-07-08 + */ +public enum SystemNodeEnum { + /** + * 网络资源 + */ + NETWORK("NetworkUnavailable", "网络资源不足"), + /** + * 内存资源 + */ + MEMORY("MemoryPressure", "内存资源不足"), + /** + * 磁盘资源 + */ + DISK("DiskPressure", "磁盘资源不足"), + /** + * 进程资源 + */ + PROCESS("PIDPressure", "进程资源不足"); + + private String type; + private String message; + + SystemNodeEnum(String type, String message) { + this.type = type; + this.message = message; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + /** + * + * 根据type查询message信息 + * @param systemNodeType 节点类型 + * @return String message信息 + */ + public static String findMessageByType(String systemNodeType) { + SystemNodeEnum[] systemNodeEnums = SystemNodeEnum.values(); + for (SystemNodeEnum systemNodeEnum : systemNodeEnums) { + if (systemNodeType.equals(systemNodeEnum.getType())) { + return systemNodeEnum.getMessage(); + } + } + return null; + } +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/enums/UserMailCodeEnum.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/enums/UserMailCodeEnum.java new file mode 100644 index 0000000..8239814 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/enums/UserMailCodeEnum.java @@ -0,0 +1,96 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.enums; + +/** + * @description 邮箱code 类型 + * @date 2020-06-01 + */ +public enum UserMailCodeEnum { + /** + * REGISTER_CODE 天枢:注册激活验证 + */ + REGISTER_CODE(1, "天枢:注册激活验证"), + + /** + * MAIL_UPDATE_CODE 天枢:邮箱修改验证 + */ + MAIL_UPDATE_CODE(2, "天枢:邮箱修改验证"), + + /** + * OTHER_CODE 天枢:其他验证码 + */ + OTHER_CODE(3, "天枢:其他验证码"), + + /** + * FORGET_PASSWORD 天枢:忘记密码验证 + */ + FORGET_PASSWORD(4, "天枢:忘记密码验证"), + + ; + + private Integer value; + + private String desc; + + UserMailCodeEnum(Integer value, String desc) { + this.value = value; + this.desc = desc; + } + + public Integer getValue() { + return this.value; + } + + public String getDesc() { + return desc; + } + + public void setDesc(String desc) { + this.desc = desc; + } + + public static UserMailCodeEnum getEnumValue(Integer value) { + switch (value) { + case 1: + return REGISTER_CODE; + case 2: + return MAIL_UPDATE_CODE; + case 4: + return FORGET_PASSWORD; + default: + return OTHER_CODE; + } + } + + public static boolean isExist(Integer value) { + for (UserMailCodeEnum itm : UserMailCodeEnum.values()) { + if (value.compareTo(itm.getValue()) == 0) { + return true; + } + } + return false; + } + + + @Override + public String toString() { + return "[" + this.value + "]" + this.desc; + } + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/event/BaseEvent.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/event/BaseEvent.java new file mode 100644 index 0000000..9901d35 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/event/BaseEvent.java @@ -0,0 +1,49 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.event; + +import org.springframework.context.ApplicationEvent; + + +/** + * @description 超类 事件 + * @date 2020-06-01 + */ +public abstract class BaseEvent extends ApplicationEvent { + + private static final long serialVersionUID = 895628808370649881L; + + protected T eventData; + + public BaseEvent(Object source, T eventData) { + super(source); + this.eventData = eventData; + } + + public BaseEvent(T eventData) { + super(eventData); + } + + public T getEventData() { + return eventData; + } + + public void setEventData(T eventData) { + this.eventData = eventData; + } +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/event/EmailEvent.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/event/EmailEvent.java new file mode 100644 index 0000000..6ef4334 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/event/EmailEvent.java @@ -0,0 +1,39 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.event; + +import org.dubhe.admin.domain.dto.EmailDTO; + + +/** + * @description 邮件事件 + * @date 2020-06-01 + */ +public class EmailEvent extends BaseEvent { + + private static final long serialVersionUID = 8103187726344703089L; + + public EmailEvent(EmailDTO msg) { + super(msg); + } + + public EmailEvent(Object source, EmailDTO msg) { + super(source, msg); + } + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/event/EmailEventListener.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/event/EmailEventListener.java new file mode 100644 index 0000000..e206e77 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/event/EmailEventListener.java @@ -0,0 +1,71 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.event; + +import org.dubhe.admin.domain.dto.EmailDTO; +import org.dubhe.admin.service.MailService; +import org.dubhe.biz.base.enums.BaseErrorCodeEnum; +import org.dubhe.biz.base.exception.BusinessException; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.springframework.context.event.EventListener; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Component; + +import javax.annotation.Resource; + + +/** + * @description 邮箱事件监听 + * @date 2020-06-01 + */ +@Component +public class EmailEventListener { + + @Resource + private MailService mailService; + + + @EventListener + @Async("taskExecutor") + public void onApplicationEvent(EmailEvent event) { + EmailDTO emailDTO = (EmailDTO) event.getSource(); + sendMail(emailDTO.getReceiverMailAddress(), emailDTO.getSubject(), emailDTO.getCode()); + } + + + /** + * 发送邮件 + * + * @param receiverMailAddress 接受邮箱地址 + * @param subject 标题 + * @param code 验证码 + */ + public void sendMail(final String receiverMailAddress, String subject, String code) { + try { + final StringBuffer sb = new StringBuffer(); + sb.append("

" + "亲爱的" + receiverMailAddress + "您好!

") + .append("

您的验证码为:" + code + "

"); + mailService.sendHtmlMail(receiverMailAddress, subject, sb.toString()); + } catch (Exception e) { + LogUtil.error(LogEnum.SYS_ERR, "UserServiceImpl sendMail error , param:{} error:{}", receiverMailAddress, e); + throw new BusinessException(BaseErrorCodeEnum.ERROR_SYSTEM.getCode(), BaseErrorCodeEnum.ERROR_SYSTEM.getMsg()); + } + } + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/event/EmailEventPublisher.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/event/EmailEventPublisher.java new file mode 100644 index 0000000..9e69028 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/event/EmailEventPublisher.java @@ -0,0 +1,53 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.event; + +import org.dubhe.admin.domain.dto.EmailDTO; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; + +/** + * @description 邮箱事件发布者 + * @date 2020-06-01 + */ +@Service +public class EmailEventPublisher { + + @Resource + private ApplicationEventPublisher applicationEventPublisher; + + /** + * 邮件发送事件 + * + * @param dto + */ + @Async("taskExecutor") + public void sentEmailEvent(final EmailDTO dto) { + try { + EmailEvent emailEvent = new EmailEvent(dto); + applicationEventPublisher.publishEvent(emailEvent); + } catch (Exception e) { + LogUtil.error(LogEnum.SYS_ERR, "EmailEventPublisher sentEmailEvent error , param:{} error:{}", dto, e); + } + } +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/rest/AuthCodeController.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/rest/AuthCodeController.java new file mode 100644 index 0000000..f69430e --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/rest/AuthCodeController.java @@ -0,0 +1,88 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.rest; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.dubhe.admin.domain.dto.AuthCodeCreateDTO; +import org.dubhe.admin.domain.dto.AuthCodeDeleteDTO; +import org.dubhe.admin.domain.dto.AuthCodeQueryDTO; +import org.dubhe.admin.domain.dto.AuthCodeUpdateDTO; +import org.dubhe.admin.service.AuthCodeService; +import org.dubhe.biz.base.constant.Permissions; +import org.dubhe.biz.base.vo.DataResponseBody; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +/** + * @description + * @date 2021-05-17 + */ +@Api(tags = "系统:权限管理") +@RestController +@RequestMapping("/authCode") +public class AuthCodeController { + + @Autowired + private AuthCodeService authCodeService; + + @GetMapping + @ApiOperation("获取权限组列表") + @PreAuthorize(Permissions.AUTH_CODE) + public DataResponseBody queryAll(AuthCodeQueryDTO authCodeQueryDTO) { + return new DataResponseBody(authCodeService.queryAll(authCodeQueryDTO)); + } + + @PostMapping + @ApiOperation("创建权限组") + @PreAuthorize(Permissions.AUTH_CODE_CREATE) + public DataResponseBody create(@Validated @RequestBody AuthCodeCreateDTO authCodeCreateDTO) { + authCodeService.create(authCodeCreateDTO); + return new DataResponseBody(); + } + + @PutMapping() + @ApiOperation("修改权限组") + @PreAuthorize(Permissions.AUTH_CODE_EDIT) + public DataResponseBody update(@Validated @RequestBody AuthCodeUpdateDTO authCodeUpdateDTO) { + authCodeService.update(authCodeUpdateDTO); + return new DataResponseBody(); + } + + @DeleteMapping + @ApiOperation("删除权限组") + @PreAuthorize(Permissions.AUTH_CODE_DELETE) + public DataResponseBody delete(@RequestBody AuthCodeDeleteDTO authCodeDeleteDTO) { + authCodeService.delete(authCodeDeleteDTO.getIds()); + return new DataResponseBody(); + } + + @GetMapping("list") + @ApiOperation("获取权限组tree") + @PreAuthorize(Permissions.AUTH_CODE) + public DataResponseBody getAuthCodeList() { + return new DataResponseBody(authCodeService.getAuthCodeList()); + } +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/rest/DictController.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/rest/DictController.java new file mode 100644 index 0000000..d4c351b --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/rest/DictController.java @@ -0,0 +1,108 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.rest; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.dubhe.admin.domain.dto.DictCreateDTO; +import org.dubhe.admin.domain.dto.DictDeleteDTO; +import org.dubhe.admin.domain.dto.DictQueryDTO; +import org.dubhe.admin.domain.dto.DictUpdateDTO; +import org.dubhe.admin.service.DictService; +import org.dubhe.biz.base.constant.Permissions; +import org.dubhe.biz.base.vo.DataResponseBody; +import org.dubhe.biz.dataresponse.factory.DataResponseFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import javax.servlet.http.HttpServletResponse; +import javax.validation.Valid; +import java.io.IOException; + +/** + * @description 字典管理 控制器 + * @date 2020-06-01 + */ +@Api(tags = "系统:字典管理") +@RestController +@RequestMapping("/dict") +public class DictController { + + @Autowired + private DictService dictService; + + + @ApiOperation("导出字典数据") + @GetMapping(value = "/download") + @PreAuthorize(Permissions.DICT_DOWNLOAD) + public void download(HttpServletResponse response, DictQueryDTO criteria) throws IOException { + dictService.download(dictService.queryAll(criteria), response); + } + + @ApiOperation("查询字典") + @GetMapping(value = "/all") + @PreAuthorize(Permissions.DICT) + public DataResponseBody all() { + return new DataResponseBody(dictService.queryAll(new DictQueryDTO())); + } + + @ApiOperation("查询字典") + @GetMapping + @PreAuthorize(Permissions.DICT) + public DataResponseBody getDicts(DictQueryDTO resources, Page page) { + return new DataResponseBody(dictService.queryAll(resources, page)); + } + + @ApiOperation("新增字典") + @PostMapping + @PreAuthorize(Permissions.DICT_CREATE) + public DataResponseBody create(@Valid @RequestBody DictCreateDTO resources) { + return new DataResponseBody(dictService.create(resources)); + } + + @ApiOperation("修改字典") + @PutMapping + @PreAuthorize(Permissions.DICT_EDIT) + public DataResponseBody update(@Valid @RequestBody DictUpdateDTO resources) { + dictService.update(resources); + return new DataResponseBody(); + } + + @ApiOperation("批量删除字典") + @DeleteMapping + @PreAuthorize(Permissions.DICT_DELETE) + public DataResponseBody delete(@RequestBody DictDeleteDTO dto) { + dictService.deleteAll(dto.getIds()); + return new DataResponseBody(); + } + + @ApiOperation("根据名称查询字典详情") + @GetMapping(value = "/{name}") + @PreAuthorize(Permissions.DICT) + public DataResponseBody getDict(@PathVariable String name) { + return DataResponseFactory.success(dictService.findByName(name)); + } +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/rest/DictDetailController.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/rest/DictDetailController.java new file mode 100644 index 0000000..54a0a32 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/rest/DictDetailController.java @@ -0,0 +1,96 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.rest; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.dubhe.admin.domain.dto.DictDetailCreateDTO; +import org.dubhe.admin.domain.dto.DictDetailDeleteDTO; +import org.dubhe.admin.domain.dto.DictDetailQueryDTO; +import org.dubhe.admin.domain.dto.DictDetailUpdateDTO; +import org.dubhe.admin.service.DictDetailService; +import org.dubhe.biz.base.constant.Permissions; +import org.dubhe.biz.base.dto.DictDetailQueryByLabelNameDTO; +import org.dubhe.biz.base.vo.DataResponseBody; +import org.dubhe.biz.base.vo.DictDetailVO; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import javax.validation.Valid; +import java.util.List; + +/** + * @description 字典详情管理 控制器 + * @date 2020-06-01 + */ +@Api(tags = "系统:字典详情管理") +@RestController +@RequestMapping("/dictDetail") +public class DictDetailController { + + @Autowired + private DictDetailService dictDetailService; + + @ApiOperation("查询字典详情") + @GetMapping + @PreAuthorize(Permissions.DICT) + public DataResponseBody getDictDetails(DictDetailQueryDTO resources, Page page) { + return new DataResponseBody(dictDetailService.queryAll(resources, page)); + } + + + @ApiOperation("新增字典详情") + @PostMapping + @PreAuthorize(Permissions.DICT_DETAIL_CREATE) + public DataResponseBody create(@Valid @RequestBody DictDetailCreateDTO resources) { + return new DataResponseBody(dictDetailService.create(resources)); + } + + + @ApiOperation("修改字典详情") + @PutMapping + @PreAuthorize(Permissions.DICT_DETAIL_EDIT) + public DataResponseBody update(@Valid @RequestBody DictDetailUpdateDTO resources) { + dictDetailService.update(resources); + return new DataResponseBody(); + } + + @ApiOperation("删除字典详情") + @DeleteMapping + @PreAuthorize(Permissions.DICT_DETAIL_DELETE) + public DataResponseBody delete(@Valid @RequestBody DictDetailDeleteDTO dto) { + dictDetailService.delete(dto.getIds()); + return new DataResponseBody(); + } + + @ApiOperation("根据名称查询字典详情") + @GetMapping("/getDictDetails") + @PreAuthorize(Permissions.DICT) + public DataResponseBody> findDictDetailByName(@Validated DictDetailQueryByLabelNameDTO dictDetailQueryByLabelNameDTO) { + return new DataResponseBody(dictDetailService.getDictName(dictDetailQueryByLabelNameDTO)); + } + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/rest/ForwardController.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/rest/ForwardController.java new file mode 100644 index 0000000..d826675 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/rest/ForwardController.java @@ -0,0 +1,126 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.rest; + +import cn.hutool.core.util.StrUtil; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.client.RestTemplate; + +import javax.servlet.http.HttpServletRequest; +import java.net.URI; +import java.net.URISyntaxException; + +/** + * @description 代理转发 + * @date 2020-06-23 + */ +@RestController +public class ForwardController { + @Value("${dubhe-proxy.visual.keyword}") + private String visual; + @Value("${dubhe-proxy.visual.server}") + private String visualServer; + @Value("${dubhe-proxy.visual.port}") + private String visualPort; + @Value("${dubhe-proxy.refine.keyword}") + private String refine; + @Value("${dubhe-proxy.refine.server}") + private String refineServer; + @Value("${dubhe-proxy.refine.port}") + private String refinePort; + + RestTemplate restTemplate = new RestTemplate(); + + /** + * 根据不同的请求拼上对应的转发路径 + * + * @param request http请求 + * @return URI 用于restTemplate的请求路径 + **/ + private URI getURI(HttpServletRequest request) throws URISyntaxException { + String requestURI = request.getRequestURI(); + String server = null; + String prefix = ""; + int port = 0; + if (requestURI.startsWith(StrUtil.SLASH + visual)) { + prefix = visual; + server = visualServer; + port = Integer.parseInt(visualPort); + } else if (requestURI.startsWith(StrUtil.SLASH + refine)) { + prefix = refine; + server = refineServer; + port = Integer.parseInt(refinePort); + } + + return new URI("http", null, server, port, requestURI.substring(prefix.length() + 1), request.getQueryString(), null); + } + + /** + * 获取请求中的Cookie + * + * @param request http请求 + * @return HttpHeaders 用于restTemplate的header + **/ + private HttpHeaders getHeader(HttpServletRequest request) { + String cookie = request.getHeader("Cookie"); + HttpHeaders httpHeaders = new HttpHeaders(); + if (null != cookie) { + httpHeaders.set("Cookie", cookie); + } + return httpHeaders; + } + + /** + * 转发get请求 + * + * @param request http请求 + * @return ResponseEntity 返回给前端的响应实体 + **/ + @GetMapping({StrUtil.SLASH + "${dubhe-proxy.visual.keyword}" + StrUtil.SLASH + "**", StrUtil.SLASH + "${dubhe-proxy.refine.keyword}" + StrUtil.SLASH + "**"}) + @ResponseBody + public ResponseEntity mirrorRest(HttpServletRequest request) throws URISyntaxException { + URI uri = getURI(request); + HttpHeaders httpHeaders = getHeader(request); + ResponseEntity responseEntity = + restTemplate.exchange(uri, HttpMethod.GET, new HttpEntity(httpHeaders), String.class); + return responseEntity; + } + + /** + * 转发get请求 + * + * @param request http请求 + * @param method 请求方法 + * @param body 请求体 + * @return ResponseEntity 返回给前端的响应实体 + **/ + @RequestMapping({StrUtil.SLASH + "${dubhe-proxy.visual.keyword}" + StrUtil.SLASH + "**", StrUtil.SLASH + "${dubhe-proxy.refine.keyword}" + StrUtil.SLASH + "**"}) + @ResponseBody + public ResponseEntity mirrorRest(HttpMethod method, HttpServletRequest request, @RequestBody String body) throws URISyntaxException { + URI uri = getURI(request); + HttpHeaders httpHeaders = getHeader(request); + ResponseEntity responseEntity = + restTemplate.exchange(uri, method, new HttpEntity(body, httpHeaders), String.class); + return responseEntity; + } +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/rest/LogController.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/rest/LogController.java new file mode 100644 index 0000000..089557d --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/rest/LogController.java @@ -0,0 +1,112 @@ +/** + * Copyright 2019-2020 Zheng Jie + * + * Licensed 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 org.dubhe.admin.rest; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.dubhe.admin.domain.dto.LogQueryDTO; +import org.dubhe.admin.service.LogService; +import org.dubhe.biz.base.constant.Permissions; +import org.dubhe.cloud.authconfig.utils.JwtUtils; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; +import springfox.documentation.annotations.ApiIgnore; + +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +/** + * @description 日志管理 控制器 + * @date 2020-06-01 + */ +@Api(tags = "监控:日志管理") +@ApiIgnore +@RestController +@RequestMapping("/logs") +public class LogController { + + private final LogService logService; + + public LogController(LogService logService) { + this.logService = logService; + } + + @ApiOperation("导出数据") + @GetMapping(value = "/download") + @PreAuthorize(Permissions.SYSTEM_LOG) + public void download(HttpServletResponse response, LogQueryDTO criteria) throws IOException { + criteria.setLogType("INFO"); + logService.download(logService.queryAll(criteria), response); + } + + @ApiOperation("导出错误数据") + @GetMapping(value = "/error/download") + @PreAuthorize(Permissions.SYSTEM_LOG) + public void errorDownload(HttpServletResponse response, LogQueryDTO criteria) throws IOException { + criteria.setLogType("ERROR"); + logService.download(logService.queryAll(criteria), response); + } + + @GetMapping + @ApiOperation("日志查询") + @PreAuthorize(Permissions.SYSTEM_LOG) + public ResponseEntity getLogs(LogQueryDTO criteria, Page pageable) { + criteria.setLogType("INFO"); + return new ResponseEntity<>(logService.queryAll(criteria, pageable), HttpStatus.OK); + } + + @GetMapping(value = "/user") + @ApiOperation("用户日志查询") + public ResponseEntity getUserLogs(LogQueryDTO criteria, Page page) { + criteria.setLogType("INFO"); + criteria.setBlurry(JwtUtils.getCurUser().getUsername()); + return new ResponseEntity<>(logService.queryAllByUser(criteria, page), HttpStatus.OK); + } + + @GetMapping(value = "/error") + @ApiOperation("错误日志查询") + @PreAuthorize(Permissions.SYSTEM_LOG) + public ResponseEntity getErrorLogs(LogQueryDTO criteria, Page page) { + criteria.setLogType("ERROR"); + return new ResponseEntity<>(logService.queryAll(criteria, page), HttpStatus.OK); + } + + @GetMapping(value = "/error/{id}") + @ApiOperation("日志异常详情查询") + @PreAuthorize(Permissions.SYSTEM_LOG) + public ResponseEntity getErrorLogs(@PathVariable Long id) { + return new ResponseEntity<>(logService.findByErrDetail(id), HttpStatus.OK); + } + + @DeleteMapping(value = "/del/error") + @ApiOperation("删除所有ERROR日志") + @PreAuthorize(Permissions.SYSTEM_LOG) + public ResponseEntity delAllByError() { + logService.delAllByError(); + return new ResponseEntity<>(HttpStatus.OK); + } + + @DeleteMapping(value = "/del/info") + @ApiOperation("删除所有INFO日志") + @PreAuthorize(Permissions.SYSTEM_LOG) + public ResponseEntity delAllByInfo() { + logService.delAllByInfo(); + return new ResponseEntity<>(HttpStatus.OK); + } +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/rest/LoginController.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/rest/LoginController.java new file mode 100644 index 0000000..6d9d37d --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/rest/LoginController.java @@ -0,0 +1,175 @@ +/** + * Copyright 2019-2020 Zheng Jie + * + * Licensed 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 org.dubhe.admin.rest; + +import cn.hutool.core.util.IdUtil; +import com.wf.captcha.SpecCaptcha; +import com.wf.captcha.base.Captcha; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import lombok.extern.slf4j.Slf4j; +import org.dubhe.admin.domain.dto.AuthUserDTO; +import org.dubhe.admin.domain.dto.UserRegisterDTO; +import org.dubhe.admin.domain.dto.UserRegisterMailDTO; +import org.dubhe.admin.domain.dto.UserResetPasswordDTO; +import org.dubhe.admin.service.UserService; +import org.dubhe.biz.base.constant.UserConstant; +import org.dubhe.biz.base.utils.DateUtil; +import org.dubhe.biz.base.vo.DataResponseBody; +import org.dubhe.biz.redis.utils.RedisUtils; +import org.dubhe.cloud.authconfig.dto.JwtUserDTO; +import org.dubhe.cloud.authconfig.utils.JwtUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import javax.validation.Valid; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.TimeUnit; + +/** + * @description 系统登录 控制器 + * @date 2020-06-01 + */ +@Api(tags = "系统登录") +@RestController +@RequestMapping("/auth") +@Slf4j +@SuppressWarnings("unchecked") +public class LoginController { + + @Value("${rsa.public_key}") + private String publicKey; + + @Value("${loginCode.expiration}") + private Long expiration; + + @Value("${loginCode.width}") + private Integer width; + + @Value("${loginCode.height}") + private Integer height; + + @Value("${loginCode.length}") + private Integer length; + + @Value("${loginCode.codeKey}") + private String codeKey; + + @Autowired + private RedisUtils redisUtils; + + @Autowired + private UserService userService; + + + @ApiOperation("登录") + @PostMapping(value = "/login") + public DataResponseBody> login(@Validated @RequestBody AuthUserDTO authUserDTO) { + return userService.login(authUserDTO); + } + + @ApiOperation("获取验证码") + @GetMapping(value = "/code") + public DataResponseBody getCode() { + Captcha captcha = new SpecCaptcha(width, height, length); + String createText = captcha.text(); + String uuid = codeKey + IdUtil.simpleUUID(); + // 保存 + redisUtils.set(uuid, createText, expiration, TimeUnit.MINUTES); + // 验证码信息 + Map imgResult = new HashMap(4) {{ + put("img", captcha.toBase64()); + put("uuid", uuid); + }}; + return new DataResponseBody(imgResult); + } + + + @ApiOperation("退出登录") + @DeleteMapping(value = "/logout") + public DataResponseBody logout(@RequestHeader("Authorization") String accessToken) { + return userService.logout(accessToken); + } + + @ApiOperation("获取用户信息") + @GetMapping(value = "/info") + public DataResponseBody info() { + JwtUserDTO curUser = JwtUtils.getCurUser(); + Set permissions = userService.queryPermissionByUserId(curUser.getCurUserId()); + Map authInfo = new HashMap(2) {{ + put("user", curUser.getUser()); + put("permissions", permissions); + }}; + return new DataResponseBody(authInfo); + } + + + @ApiOperation("用户注册信息") + @PostMapping(value = "/userRegister") + public DataResponseBody userRegister(@Valid @RequestBody UserRegisterDTO userRegisterDTO) { + return userService.userRegister(userRegisterDTO); + } + + + @ApiOperation("用户忘记密码") + @PostMapping(value = "/resetPassword") + public DataResponseBody resetPassword(@Valid @RequestBody UserResetPasswordDTO userResetPasswordDTO) { + return userService.resetPassword(userResetPasswordDTO); + } + + + @ApiOperation("获取code通过发送邮件") + @PostMapping(value = "/getCodeBySentEmail") + public DataResponseBody getCodeBySentEmail(@Valid @RequestBody UserRegisterMailDTO userRegisterMailDTO) { + return userService.getCodeBySentEmail(userRegisterMailDTO); + } + + + @ApiOperation("获取公钥") + @GetMapping(value = "/getPublicKey") + public DataResponseBody getPublicKey() { + return new DataResponseBody(publicKey); + } + + @ApiOperation(value = "获取用户信息 供第三方平台使用", notes = "获取用户信息 供第三方平台使用") + @GetMapping("/userinfo") + public Map userinfo() { + return userService.userinfo(); + } + + /** + * 限制登录失败次数 + * + * @param username + */ + private boolean limitLoginCount(final String username) { + String concat = UserConstant.USER_LOGIN_LIMIT_COUNT.concat(username); + double count = redisUtils.hincr(UserConstant.USER_LOGIN_LIMIT_COUNT.concat(username), concat, 1); + if (count > UserConstant.COUNT_LOGIN_FAIL) { + return false; + } else { + // 验证码次数凌晨清除 + long afterSixHourTime = DateUtil.getAfterSixHourTime(); + redisUtils.hset(concat, concat, afterSixHourTime); + } + return true; + } + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/rest/MailController.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/rest/MailController.java new file mode 100644 index 0000000..97e4879 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/rest/MailController.java @@ -0,0 +1,50 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.rest; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.dubhe.admin.service.MailService; +import org.dubhe.biz.base.vo.DataResponseBody; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import javax.annotation.Resource; +import javax.mail.MessagingException; + +/** + * @description 邮件服务 + * @date 2021-01-21 + */ +@Api(tags = "系统:邮件服务") +@RestController +@RequestMapping("/mail") +public class MailController { + + @Resource + private MailService mailService; + + @ApiOperation("发送html邮件") + @PostMapping(value = "/sendHtmlMail") + public DataResponseBody sendHtmlMail(@RequestParam(value = "to") String to, @RequestParam(value = "subject") String subject, @RequestParam("content") String content) throws MessagingException { + mailService.sendHtmlMail(to, subject, content); + return new DataResponseBody(); + } + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/rest/MenuController.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/rest/MenuController.java new file mode 100644 index 0000000..0d9d26c --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/rest/MenuController.java @@ -0,0 +1,110 @@ +/** + * Copyright 2019-2020 Zheng Jie + * + * Licensed 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 org.dubhe.admin.rest; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.dubhe.admin.domain.dto.MenuCreateDTO; +import org.dubhe.admin.domain.dto.MenuDTO; +import org.dubhe.admin.domain.dto.MenuDeleteDTO; +import org.dubhe.admin.domain.dto.MenuQueryDTO; +import org.dubhe.admin.domain.dto.MenuUpdateDTO; +import org.dubhe.admin.domain.entity.Menu; +import org.dubhe.admin.service.MenuService; +import org.dubhe.biz.base.constant.Permissions; +import org.dubhe.biz.base.vo.DataResponseBody; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import javax.servlet.http.HttpServletResponse; +import javax.validation.Valid; +import java.io.IOException; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +/** + * @description 菜单管理 控制器 + * @date 2020-06-01 + */ +@Api(tags = "系统:菜单管理") +@RestController +@RequestMapping("/menus") +@SuppressWarnings("unchecked") +public class MenuController { + + + @Autowired + private MenuService menuService; + + @ApiOperation("导出菜单数据") + @GetMapping(value = "/download") + @PreAuthorize(Permissions.MENU_DOWNLOAD) + public void download(HttpServletResponse response, MenuQueryDTO criteria) throws IOException { + menuService.download(menuService.queryAll(criteria), response); + } + + @ApiOperation("返回全部的菜单") + @GetMapping(value = "/tree") + public DataResponseBody getMenuTree() { + return new DataResponseBody(menuService.getMenuTree(menuService.findByPid(0L))); + } + + @ApiOperation("查询菜单") + @GetMapping + @PreAuthorize(Permissions.MENU) + public DataResponseBody getMenus(MenuQueryDTO criteria) { + List menuDtoList = menuService.queryAll(criteria); + return new DataResponseBody(menuService.buildTree(menuDtoList)); + } + + @ApiOperation("新增菜单") + @PostMapping + @PreAuthorize(Permissions.MENU_CREATE) + public DataResponseBody create(@Valid @RequestBody MenuCreateDTO resources) { + return new DataResponseBody(menuService.create(resources)); + } + + @ApiOperation("修改菜单") + @PutMapping + @PreAuthorize(Permissions.MENU_EDIT) + public DataResponseBody update(@Valid @RequestBody MenuUpdateDTO resources) { + menuService.update(resources); + return new DataResponseBody(); + } + + @ApiOperation("删除菜单") + @DeleteMapping + @PreAuthorize(Permissions.MENU_DELETE) + public DataResponseBody delete(@Valid @RequestBody MenuDeleteDTO deleteDTO) { + Set menuSet = new HashSet<>(); + Set ids = deleteDTO.getIds(); + for (Long id : ids) { + List menuList = menuService.findByPid(id); + menuSet.add(menuService.findOne(id)); + menuSet = menuService.getDeleteMenus(menuList, menuSet); + } + menuService.delete(menuSet); + return new DataResponseBody(); + } +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/rest/PermissionController.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/rest/PermissionController.java new file mode 100644 index 0000000..1621cc2 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/rest/PermissionController.java @@ -0,0 +1,89 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.rest; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.dubhe.admin.domain.dto.PermissionCreateDTO; +import org.dubhe.admin.domain.dto.PermissionDeleteDTO; +import org.dubhe.admin.domain.dto.PermissionQueryDTO; +import org.dubhe.admin.domain.dto.PermissionUpdateDTO; +import org.dubhe.admin.service.PermissionService; +import org.dubhe.biz.base.constant.Permissions; +import org.dubhe.biz.base.vo.DataResponseBody; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +/** + * @description 操作权限控制器 + * @date 2021-04-26 + */ +@Api(tags = "系统:操作权限") +@RestController +@RequestMapping("/permission") +public class PermissionController { + + @Autowired + private PermissionService permissionService; + + @ApiOperation("返回全部的操作权限") + @GetMapping(value = "/tree") + public DataResponseBody getPermissionTree() { + return new DataResponseBody(permissionService.getPermissionTree(permissionService.findByPid(0L))); + } + + @ApiOperation("查询权限") + @GetMapping + @PreAuthorize(Permissions.AUTH_CODE) + public DataResponseBody queryAll(PermissionQueryDTO queryDTO) { + return new DataResponseBody(permissionService.queryAll(queryDTO)); + } + + @ApiOperation("新增权限") + @PostMapping + @PreAuthorize(Permissions.PERMISSION_CREATE) + public DataResponseBody create(@Validated @RequestBody PermissionCreateDTO permissionCreateDTO) { + permissionService.create(permissionCreateDTO); + return new DataResponseBody(); + } + + @ApiOperation("修改权限") + @PutMapping + @PreAuthorize(Permissions.PERMISSION_EDIT) + public DataResponseBody update(@Validated @RequestBody PermissionUpdateDTO permissionUpdateDTO) { + permissionService.update(permissionUpdateDTO); + return new DataResponseBody(); + } + + @ApiOperation("删除权限") + @DeleteMapping + @PreAuthorize(Permissions.PERMISSION_DELETE) + public DataResponseBody delete(@RequestBody PermissionDeleteDTO permissionDeleteDTO) { + permissionService.delete(permissionDeleteDTO); + return new DataResponseBody(); + } + + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/rest/RecycleTaskController.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/rest/RecycleTaskController.java new file mode 100644 index 0000000..9d595d7 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/rest/RecycleTaskController.java @@ -0,0 +1,79 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.rest; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.dubhe.admin.service.RecycleTaskService; +import org.dubhe.biz.base.vo.DataResponseBody; +import org.dubhe.biz.dataresponse.factory.DataResponseFactory; +import org.dubhe.recycle.domain.dto.RecycleTaskDeleteDTO; +import org.dubhe.recycle.domain.dto.RecycleTaskQueryDTO; +import org.dubhe.recycle.enums.RecycleModuleEnum; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +/** + * @description 回收任务 + * @date 2020-09-23 + */ +@Api(tags = "系统:回收任务") +@RestController +@RequestMapping("/recycleTask") +public class RecycleTaskController { + + @Autowired + private RecycleTaskService recycleTaskService; + + @ApiOperation("查询回收任务列表") + @GetMapping + public DataResponseBody getRecycleTaskList(RecycleTaskQueryDTO recycleTaskQueryDTO) { + return DataResponseFactory.success(recycleTaskService.getRecycleTasks(recycleTaskQueryDTO)); + } + + @ApiOperation("(批量)立即删除") + @DeleteMapping + public DataResponseBody recycleTaskResources(@Validated @RequestBody RecycleTaskDeleteDTO recycleTaskDeleteDTO) { + for (long taskId:recycleTaskDeleteDTO.getRecycleTaskIdList()){ + recycleTaskService.recycleTaskResources(taskId); + } + return DataResponseFactory.successWithMsg("资源删除中"); + } + + @ApiOperation("获取模块代号,名称映射") + @GetMapping("/recycleModuleMap") + public DataResponseBody recycleModuleMap() { + return DataResponseFactory.success(RecycleModuleEnum.RECYCLE_MODULE_MAP); + } + + @ApiOperation("立即还原") + @PutMapping + public DataResponseBody restore(@RequestParam(required = true) long taskId) { + recycleTaskService.restore(taskId); + return DataResponseFactory.successWithMsg("还原成功"); + } + + + @ApiOperation("实时删除完整路径无效文件") + @DeleteMapping("/delTemp") + public DataResponseBody delTempInvalidResources(@RequestParam(required = true) String sourcePath) { + recycleTaskService.delTempInvalidResources(sourcePath); + return DataResponseFactory.successWithMsg("删除临时目录文件成功"); + } + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/rest/ResourceSpecsController.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/rest/ResourceSpecsController.java new file mode 100644 index 0000000..b445977 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/rest/ResourceSpecsController.java @@ -0,0 +1,82 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.rest; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.dubhe.admin.domain.dto.ResourceSpecsCreateDTO; +import org.dubhe.admin.domain.dto.ResourceSpecsDeleteDTO; +import org.dubhe.admin.domain.dto.ResourceSpecsQueryDTO; +import org.dubhe.admin.domain.dto.ResourceSpecsUpdateDTO; +import org.dubhe.admin.service.ResourceSpecsService; +import org.dubhe.biz.base.constant.Permissions; +import org.dubhe.biz.base.dto.QueryResourceSpecsDTO; +import org.dubhe.biz.base.vo.DataResponseBody; +import org.dubhe.biz.base.vo.QueryResourceSpecsVO; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +import javax.validation.Valid; + +/** + * @description CPU, GPU, 内存等资源规格管理 + * @date 2021-05-27 + */ +@Api(tags = "系统:资源规格管理") +@RestController +@RequestMapping("/resourceSpecs") +public class ResourceSpecsController { + + @Autowired + private ResourceSpecsService resourceSpecsService; + + @ApiOperation("查询资源规格") + @GetMapping + public DataResponseBody getResourceSpecs(ResourceSpecsQueryDTO resourceSpecsQueryDTO) { + return new DataResponseBody(resourceSpecsService.getResourceSpecs(resourceSpecsQueryDTO)); + } + + @ApiOperation("查询资源规格(远程调用)") + @GetMapping("/queryResourceSpecs") + public DataResponseBody queryResourceSpecs(QueryResourceSpecsDTO queryResourceSpecsDTO) { + return new DataResponseBody(resourceSpecsService.queryResourceSpecs(queryResourceSpecsDTO)); + } + + @ApiOperation("新增资源规格") + @PostMapping + @PreAuthorize(Permissions.SPECS_CREATE) + public DataResponseBody create(@Valid @RequestBody ResourceSpecsCreateDTO resourceSpecsCreateDTO) { + return new DataResponseBody(resourceSpecsService.create(resourceSpecsCreateDTO)); + } + + @ApiOperation("修改资源规格") + @PutMapping + @PreAuthorize(Permissions.SPECS_EDIT) + public DataResponseBody update(@Valid @RequestBody ResourceSpecsUpdateDTO resourceSpecsUpdateDTO) { + return new DataResponseBody(resourceSpecsService.update(resourceSpecsUpdateDTO)); + } + + @ApiOperation("删除资源规格") + @DeleteMapping + @PreAuthorize(Permissions.SPECS_DELETE) + public DataResponseBody delete(@Valid @RequestBody ResourceSpecsDeleteDTO resourceSpecsDeleteDTO) { + resourceSpecsService.delete(resourceSpecsDeleteDTO); + return new DataResponseBody(); + } + +} \ No newline at end of file diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/rest/RoleController.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/rest/RoleController.java new file mode 100644 index 0000000..6099ad9 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/rest/RoleController.java @@ -0,0 +1,142 @@ +/** + * Copyright 2019-2020 Zheng Jie + * + * Licensed 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 org.dubhe.admin.rest; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.dubhe.admin.domain.dto.RoleAuthUpdateDTO; +import org.dubhe.admin.domain.dto.RoleCreateDTO; +import org.dubhe.admin.domain.dto.RoleDTO; +import org.dubhe.admin.domain.dto.RoleDeleteDTO; +import org.dubhe.admin.domain.dto.RoleQueryDTO; +import org.dubhe.admin.domain.dto.RoleUpdateDTO; +import org.dubhe.admin.service.AuthCodeService; +import org.dubhe.admin.service.RoleService; +import org.dubhe.biz.base.constant.Permissions; +import org.dubhe.biz.base.vo.DataResponseBody; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import javax.servlet.http.HttpServletResponse; +import javax.validation.Valid; +import java.io.IOException; +import java.util.Objects; + + +/** + * @description 角色管理 控制器 + * @date 2020-06-01 + */ +@Api(tags = "系统:角色管理") +@RestController +@RequestMapping("/roles") +public class RoleController { + + private final RoleService roleService; + + @Autowired + private AuthCodeService authCodeService; + + public RoleController(RoleService roleService) { + this.roleService = roleService; + } + + @ApiOperation("查询角色") + @GetMapping + @PreAuthorize(Permissions.ROLE) + public DataResponseBody getRoles(RoleQueryDTO criteria, Page page) { + return new DataResponseBody(roleService.queryAll(criteria, page)); + } + + @ApiOperation("返回全部的角色") + @GetMapping(value = "/all") + @PreAuthorize(Permissions.ROLE) + public DataResponseBody getAll(RoleQueryDTO criteria) { + return new DataResponseBody(roleService.queryAllSmall(criteria)); + } + + @ApiOperation("获取单个role") + @GetMapping(value = "/{id}") + @PreAuthorize(Permissions.ROLE) + public DataResponseBody getRoles(@PathVariable Long id) { + return new DataResponseBody(roleService.findById(id)); + } + + @ApiOperation("新增角色") + @PostMapping + @PreAuthorize(Permissions.ROLE_CREATE) + public DataResponseBody create(@Valid @RequestBody RoleCreateDTO resources) { + return new DataResponseBody(roleService.create(resources)); + } + + @ApiOperation("修改角色") + @PutMapping + @PreAuthorize(Permissions.ROLE_EDIT) + public DataResponseBody update(@Valid @RequestBody RoleUpdateDTO resources) { + roleService.update(resources); + return new DataResponseBody(); + } + + @ApiOperation("修改角色菜单") + @PutMapping(value = "/menu") + @PreAuthorize(Permissions.ROLE_MENU) + public DataResponseBody updateMenu(@Valid @RequestBody RoleUpdateDTO resources) { + RoleDTO role = roleService.findById(resources.getId()); + if (Objects.isNull(role)) { + throw new BadCredentialsException("请选择角色信息"); + } + roleService.updateMenu(resources, role); + return new DataResponseBody(); + } + + @ApiOperation("修改角色权限") + @PutMapping(value = "/auth") + @PreAuthorize(Permissions.ROLE_AUTH) + public DataResponseBody updateAuth(@Valid @RequestBody RoleAuthUpdateDTO roleAuthUpdateDTO) { + RoleDTO role = roleService.findById(roleAuthUpdateDTO.getRoleId()); + if (Objects.isNull(role)) { + throw new BadCredentialsException("请选择角色信息"); + } + authCodeService.updateRoleAuth(roleAuthUpdateDTO); + return new DataResponseBody(); + } + + @ApiOperation("删除角色") + @DeleteMapping + @PreAuthorize(Permissions.ROLE_DELETE) + public DataResponseBody delete(@RequestBody RoleDeleteDTO deleteDTO) { + roleService.delete(deleteDTO.getIds()); + return new DataResponseBody(); + } + + @ApiOperation("导出角色数据") + @GetMapping(value = "/download") + @PreAuthorize(Permissions.ROLE_DWONLOAD) + public void download(HttpServletResponse response, RoleQueryDTO criteria) throws IOException { + roleService.download(roleService.queryAll(criteria), response); + } + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/rest/TeamController.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/rest/TeamController.java new file mode 100644 index 0000000..ac072bd --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/rest/TeamController.java @@ -0,0 +1,96 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.rest; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.dubhe.admin.domain.dto.TeamCreateDTO; +import org.dubhe.admin.domain.dto.TeamQueryDTO; +import org.dubhe.admin.domain.dto.TeamUpdateDTO; +import org.dubhe.admin.service.TeamService; +import org.dubhe.biz.base.vo.DataResponseBody; +import org.dubhe.biz.base.constant.Permissions; +import org.springframework.data.domain.Sort; +import org.springframework.data.web.PageableDefault; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; +import springfox.documentation.annotations.ApiIgnore; + +import javax.servlet.http.HttpServletResponse; +import javax.validation.Valid; +import java.io.IOException; + +/** + * @description 团队管理 控制器 + * @date 2020-06-01 + */ +@Api(tags = "系统:团队管理") +@ApiIgnore +@RestController +@RequestMapping("/teams") +public class TeamController { + private final TeamService teamService; + + public TeamController(TeamService teamService) { + this.teamService = teamService; + } + + @ApiOperation("获取单个团队信息") + @GetMapping(value = "/{id}") + @PreAuthorize(Permissions.SYSTEM_TEAM) + public DataResponseBody getTeam(@PathVariable Long id) { + return new DataResponseBody(teamService.findById(id)); + } + + @ApiOperation("导出团队数据") + @GetMapping(value = "/download") + @PreAuthorize(Permissions.SYSTEM_TEAM) + public void download(HttpServletResponse response, TeamQueryDTO criteria) throws IOException { + teamService.download(teamService.queryAll(criteria), response); + } + + @ApiOperation("返回全部的团队") + @GetMapping(value = "/all") + @PreAuthorize(Permissions.SYSTEM_TEAM) + public DataResponseBody getAll(@PageableDefault(value = 2000, sort = {"level"}, direction = Sort.Direction.ASC) Page page) { + return new DataResponseBody(teamService.queryAll(page)); + } + + @ApiOperation("查询团队") + @GetMapping + @PreAuthorize(Permissions.SYSTEM_TEAM) + public DataResponseBody getTeams(TeamQueryDTO criteria, Page page) { + System.out.println("com here"); + return new DataResponseBody(teamService.queryAll(criteria, page)); + } + + @ApiOperation("新增团队") + @PostMapping + @PreAuthorize(Permissions.SYSTEM_TEAM) + public DataResponseBody create(@Valid @RequestBody TeamCreateDTO resources) { + return new DataResponseBody(teamService.create(resources)); + } + + @ApiOperation("修改团队") + @PutMapping + @PreAuthorize(Permissions.SYSTEM_TEAM) + public DataResponseBody update(@Valid @RequestBody TeamUpdateDTO resources) { + teamService.update(resources); + return new DataResponseBody(); + } +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/rest/UserCenterController.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/rest/UserCenterController.java new file mode 100644 index 0000000..2188eae --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/rest/UserCenterController.java @@ -0,0 +1,140 @@ +/** + * Copyright 2019-2020 Zheng Jie + * + * Licensed 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 org.dubhe.admin.rest; + +import cn.hutool.crypto.asymmetric.KeyType; +import cn.hutool.crypto.asymmetric.RSA; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.dubhe.admin.domain.dto.*; +import org.dubhe.admin.service.DictService; +import org.dubhe.admin.service.MenuService; +import org.dubhe.admin.service.RoleService; +import org.dubhe.admin.service.UserService; +import org.dubhe.biz.base.context.UserContext; +import org.dubhe.biz.base.exception.BusinessException; +import org.dubhe.biz.base.service.UserContextService; +import org.dubhe.biz.base.vo.DataResponseBody; +import org.dubhe.cloud.authconfig.factory.PasswordEncoderFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.web.bind.annotation.*; + +import javax.validation.Valid; +import java.util.List; + +/** + * @description 个人中心 控制器 + * @date 2020-06-01 + */ +@Api(tags = "系统:个人中心") +@RestController +@RequestMapping("/user") +public class UserCenterController { + + @Autowired + private UserService userService; + + @Autowired + private RoleService roleService; + + @Autowired + private MenuService menuService; + + @Autowired + private DictService dictService; + + @Autowired + private UserContextService userContextService; + + @Value("${rsa.private_key}") + private String privateKey; + + + @ApiOperation("用户团队") + @GetMapping(value = "/teams") + public DataResponseBody getTeams() { + return new DataResponseBody(userService.queryTeams(userContextService.getCurUserId())); + } + + @ApiOperation("获取前端所需菜单") + @GetMapping(value = "/menus") + public DataResponseBody menus() { + Long curUserId = userContextService.getCurUserId(); + List roles = roleService.getRoleByUserId(curUserId); + List menuDtoList = menuService.findByRoles(roles); + List menuDtos = (List) menuService.buildTree(menuDtoList).get("result"); + + return new DataResponseBody(menuService.buildMenus(menuDtos)); + } + + @ApiOperation("用户查询字典详情") + @GetMapping(value = "/dict/{name}") + public DataResponseBody getDict(@PathVariable String name) { + return new DataResponseBody(dictService.findByName(name)); + } + + @ApiOperation("个人中心") + @GetMapping(value = "info") + public DataResponseBody getInfo() { + return new DataResponseBody(userContextService.getCurUser()); + } + + @ApiOperation("修改用户:个人中心") + @PutMapping(value = "info") + public DataResponseBody info(@Valid @RequestBody UserCenterUpdateDTO resources) { + Long curUserId = userContextService.getCurUserId(); + if (!resources.getId().equals(curUserId)) { + throw new BusinessException("不能修改他人资料"); + } + userService.updateCenter(resources); + return new DataResponseBody(userService.findById(curUserId)); + } + + @ApiOperation("修改密码") + @PostMapping(value = "/updatePass") + public DataResponseBody updatePass(@Valid @RequestBody UserPassUpdateDTO passUpdateDTO) { + PasswordEncoder passwordEncoder = PasswordEncoderFactory.getPasswordEncoder(); + // 密码解密 + RSA rsa = new RSA(privateKey, null); + String oldPass = new String(rsa.decrypt(passUpdateDTO.getOldPass(), KeyType.PrivateKey)); + String newPass = new String(rsa.decrypt(passUpdateDTO.getNewPass(), KeyType.PrivateKey)); + UserContext curUser = userContextService.getCurUser(); + if (!passwordEncoder.matches(oldPass, curUser.getPassword())) { + throw new BusinessException("修改失败,旧密码错误"); + } + if (passwordEncoder.matches(newPass, curUser.getPassword())) { + throw new BusinessException("新密码不能与旧密码相同"); + } + userService.updatePass(curUser.getUsername(), passwordEncoder.encode(newPass)); + return new DataResponseBody(); + } + + @ApiOperation("修改头像") + @PostMapping(value = "/updateAvatar") + public DataResponseBody updateAvatar(@Valid @RequestBody UserAvatarUpdateDTO avatarUpdateDTO) { + userService.updateAvatar(avatarUpdateDTO.getRealName(), avatarUpdateDTO.getPath()); + return new DataResponseBody(); + } + + + @ApiOperation("修改邮箱接口") + @PostMapping(value = "/resetEmail") + public DataResponseBody resetEmail(@RequestBody UserEmailUpdateDTO userEmailUpdateDTO) { + return userService.resetEmail(userEmailUpdateDTO); + } +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/rest/UserController.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/rest/UserController.java new file mode 100644 index 0000000..ef70bda --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/rest/UserController.java @@ -0,0 +1,118 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.rest; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.dubhe.admin.domain.dto.UserCreateDTO; +import org.dubhe.admin.domain.dto.UserDeleteDTO; +import org.dubhe.admin.domain.dto.UserQueryDTO; +import org.dubhe.admin.domain.dto.UserUpdateDTO; +import org.dubhe.admin.service.UserService; +import org.dubhe.biz.base.constant.Permissions; +import org.dubhe.biz.base.context.UserContext; +import org.dubhe.biz.base.dto.UserDTO; +import org.dubhe.biz.base.vo.DataResponseBody; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletResponse; +import javax.validation.Valid; +import java.io.IOException; +import java.util.List; + +/** + * @description 用户管理 + * @date 2020-11-03 + */ +@Api(tags = "系统:用户管理") +@RestController +@RequestMapping("/users") +public class UserController { + + @Autowired + private UserService userService; + + @ApiOperation("导出用户数据") + @GetMapping(value = "/download") + @PreAuthorize(Permissions.USER_DOWNLOAD) + public void download(HttpServletResponse response, UserQueryDTO criteria) throws IOException { + userService.download(userService.queryAll(criteria), response); + } + + @ApiOperation("查询用户") + @GetMapping + public DataResponseBody getUsers(UserQueryDTO criteria, Page page) { + return new DataResponseBody(userService.queryAll(criteria, page)); + } + + @ApiOperation("新增用户") + @PostMapping + @PreAuthorize(Permissions.USER_CREATE) + public DataResponseBody create(@Valid @RequestBody UserCreateDTO userCreateDTO) { + return new DataResponseBody(userService.create(userCreateDTO)); + } + + @ApiOperation("修改用户") + @PutMapping + @PreAuthorize(Permissions.USER_EDIT) + public DataResponseBody update(@Valid @RequestBody UserUpdateDTO resources) { + return new DataResponseBody(userService.update(resources)); + } + + @ApiOperation("删除用户") + @DeleteMapping + @PreAuthorize(Permissions.USER_DELETE) + public DataResponseBody delete(@Valid @RequestBody UserDeleteDTO userDeleteDTO) { + userService.delete(userDeleteDTO.getIds()); + return new DataResponseBody(); + } + + /** + * 此接口提供给Auth模块获取用户信息使用 + * 因Auth获取用户信息在登录时是未登录状态,请不要在此添加权限校验 + * @param username + * @return + */ + @ApiOperation("根据用户名称查找用户") + @GetMapping(value = "/findUserByUsername") + public DataResponseBody findUserByUsername(@RequestParam(value = "username") String username) { + DataResponseBody userContextDataResponseBody = userService.findUserByUsername(username); + return userContextDataResponseBody; + } + + + @ApiOperation("根据用户ID查询用户信息(服务内部访问)") + @GetMapping(value = "/findById") + public DataResponseBody getUsers(@RequestParam(value = "userId") Long userId) { + return new DataResponseBody(userService.findById(userId)); + } + + @ApiOperation("根据用户昵称搜索用户列表") + @GetMapping(value = "/findByNickName") + public DataResponseBody> findByNickName(@RequestParam(value = "nickName",required = false) String nickName) { + return new DataResponseBody(userService.findByNickName(nickName)); + } + + @ApiOperation("根据用户ID批量查询用户信息(服务内部访问)") + @GetMapping(value = "/findByIds") + public DataResponseBody> getUserList(@RequestParam(value = "ids") List ids) { + return new DataResponseBody(userService.getUserList(ids)); + } +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/rest/UserGroupController.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/rest/UserGroupController.java new file mode 100644 index 0000000..65d2759 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/rest/UserGroupController.java @@ -0,0 +1,133 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.rest; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.dubhe.admin.domain.dto.UserGroupDTO; +import org.dubhe.admin.domain.dto.UserGroupDeleteDTO; +import org.dubhe.admin.domain.dto.UserGroupQueryDTO; +import org.dubhe.admin.domain.dto.UserGroupUpdDTO; +import org.dubhe.admin.domain.dto.UserRoleUpdateDTO; +import org.dubhe.admin.domain.dto.UserStateUpdateDTO; +import org.dubhe.admin.service.UserGroupService; +import org.dubhe.biz.base.constant.Permissions; +import org.dubhe.biz.base.vo.DataResponseBody; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +/** + * @description 用户组管理 控制器 + * @date 2021-05-10 + */ +@Api(tags = "系统:用户组管理") +@RestController +@RequestMapping("/group") +public class UserGroupController { + + @Autowired + private UserGroupService userGroupService; + + @GetMapping + @ApiOperation("获取用户组列表") + public DataResponseBody queryAll(UserGroupQueryDTO queryDTO) { + return new DataResponseBody(userGroupService.queryAll(queryDTO)); + } + + @PostMapping + @ApiOperation("创建用户组") + @PreAuthorize(Permissions.USER_GROUP_CREATE) + public DataResponseBody create(@Validated @RequestBody UserGroupDTO groupCreateDTO) { + return new DataResponseBody(userGroupService.create(groupCreateDTO)); + } + + @PutMapping + @ApiOperation("修改用户组信息") + @PreAuthorize(Permissions.USER_GROUP_EDIT) + public DataResponseBody update(@Validated @RequestBody UserGroupDTO groupUpdateDTO) { + userGroupService.update(groupUpdateDTO); + return new DataResponseBody(); + } + + @DeleteMapping + @ApiOperation("删除用户组") + @PreAuthorize(Permissions.USER_GROUP_DELETE) + public DataResponseBody delete(@RequestBody UserGroupDeleteDTO groupDeleteDTO) { + userGroupService.delete(groupDeleteDTO.getIds()); + return new DataResponseBody(); + } + + @PostMapping("/updateUser") + @ApiOperation("修改组成员") + @PreAuthorize(Permissions.USER_GROUP_EDIT_USER) + public DataResponseBody updUserWithGroup(@Validated @RequestBody UserGroupUpdDTO userGroupUpdDTO) { + userGroupService.updUserWithGroup(userGroupUpdDTO); + return new DataResponseBody(); + } + + @DeleteMapping("/deleteUser") + @ApiOperation("移除组成员") + @PreAuthorize(Permissions.USER_GROUP_EDIT_USER) + public DataResponseBody delUserWithGroup(@Validated @RequestBody UserGroupUpdDTO userGroupDelDTO) { + userGroupService.delUserWithGroup(userGroupDelDTO); + return new DataResponseBody(); + } + + @GetMapping("/findUser") + @ApiOperation("获取没有归属组的用户") + public DataResponseBody findUserWithOutGroup() { + return new DataResponseBody(userGroupService.findUserWithOutGroup()); + } + + @GetMapping("/byGroupId") + @ApiOperation("获取某个用户组的成员") + public DataResponseBody queryUserByGroupId(Long groupId) { + return new DataResponseBody(userGroupService.queryUserByGroupId(groupId)); + } + + @PutMapping("/userState") + @ApiOperation("批量修改组用户的状态(激活/锁定)") + @PreAuthorize(Permissions.USER_GROUP_EDIT_USER_STATE) + public DataResponseBody updateUserState(@Validated @RequestBody UserStateUpdateDTO userStateUpdateDTO) { + userGroupService.updateUserState(userStateUpdateDTO); + return new DataResponseBody(); + } + + @DeleteMapping("/delete") + @ApiOperation("批量删除组用户") + @PreAuthorize(Permissions.USER_GROUP_DELETE_USER) + public DataResponseBody delUser(@Validated @RequestBody UserGroupUpdDTO userGroupUpdDTO) { + userGroupService.delUser(userGroupUpdDTO); + return new DataResponseBody(); + } + + @PutMapping("/userRoles") + @ApiOperation("批量修改组成员角色") + @PreAuthorize(Permissions.USER_GROUP_EDIT_USER_ROLE) + public DataResponseBody updateUserRole(@Validated @RequestBody UserRoleUpdateDTO userRoleUpdateDTO) { + userGroupService.updateUserRole(userRoleUpdateDTO); + return new DataResponseBody(); + } +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/service/AuthCodeService.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/AuthCodeService.java new file mode 100644 index 0000000..77c22f4 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/AuthCodeService.java @@ -0,0 +1,80 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import org.dubhe.admin.domain.dto.AuthCodeCreateDTO; +import org.dubhe.admin.domain.dto.AuthCodeQueryDTO; +import org.dubhe.admin.domain.dto.AuthCodeUpdateDTO; +import org.dubhe.admin.domain.dto.RoleAuthUpdateDTO; +import org.dubhe.admin.domain.entity.Auth; +import org.dubhe.admin.domain.vo.AuthVO; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * @description 权限组服务类 + * @date 2021-05-14 + */ +public interface AuthCodeService extends IService { + + /** + * 分页查询权限组信息 + * + * @param authCodeQueryDTO 分页查询实例 + * @return Map 权限组分页信息 + */ + Map queryAll(AuthCodeQueryDTO authCodeQueryDTO); + + /** + * 创建权限组 + * + * @param authCodeCreateDTO 创建权限组DTO实例 + */ + void create(AuthCodeCreateDTO authCodeCreateDTO); + + /** + * 修改权限组信息 + * + * @param authCodeUpdateDTO 修改权限组信息DTO实例 + */ + void update(AuthCodeUpdateDTO authCodeUpdateDTO); + + /** + * 批量删除权限组 + * + * @param ids 权限组id集合 + */ + void delete(Set ids); + + /** + * 修改角色-权限组绑定关系 + * + * @param roleAuthUpdateDTO 角色-权限组关系映射DTO实例 + */ + void updateRoleAuth(RoleAuthUpdateDTO roleAuthUpdateDTO); + + /** + * 获取权限组列表 + * + * @return List 权限组列表信息 + */ + List getAuthCodeList(); + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/service/DataSequenceService.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/DataSequenceService.java new file mode 100644 index 0000000..3860a48 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/DataSequenceService.java @@ -0,0 +1,60 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.service; + +import org.dubhe.admin.domain.entity.DataSequence; + +/** + * @description 获取序列服务接口 + * @date 2020-09-23 + */ +public interface DataSequenceService { + /** + * 根据业务编码获取序列号 + * @param businessCode 业务编码 + * @return DataSequence 序列实体 + */ + DataSequence getSequence(String businessCode); + /** + * 根据业务编码更新起点 + * @param businessCode 业务编码 + * @return DataSequence 序列实体 + */ + int updateSequenceStart(String businessCode); + + /** + * 检查表是否存在 + * @param tableName 表名 + * @return boolean 是否存在标识 + */ + boolean checkTableExist(String tableName); + + /** + * 执行存储过程创建表 + * @param tableId 表名 + */ + void createTable(String tableId); + + /** + * 扩容可用数量 + * + * @param businessCode 业务编码 + * @return DataSequence 数据ID序列 + */ + DataSequence expansionUsedNumber(String businessCode); +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/service/DictDetailService.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/DictDetailService.java new file mode 100644 index 0000000..3489cab --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/DictDetailService.java @@ -0,0 +1,89 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.service; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.dubhe.admin.domain.dto.*; +import org.dubhe.admin.domain.entity.DictDetail; +import org.dubhe.biz.base.dto.DictDetailQueryByLabelNameDTO; +import org.dubhe.biz.base.vo.DictDetailVO; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * @description 字典详情服务 Service + * @date 2020-06-01 + */ +public interface DictDetailService { + + /** + * 根据ID查询 + * + * @param id 字典Id + * @return 字典详情DTO + */ + DictDetailDTO findById(Long id); + + /** + * 创建 + * + * @param resources 字典详情创建实体 + * @return 字典详情实体 + */ + DictDetailDTO create(DictDetailCreateDTO resources); + + /** + * 编辑 + * + * @param resources 字典详情修改实体 + */ + void update(DictDetailUpdateDTO resources); + + /** + * 删除 + * + * @param ids 字典详情ids + */ + void delete(Set ids); + + /** + * 分页查询 + * + * @param criteria 条件 + * @param page 分页参数 + * @return 字典分页列表数据 + */ + Map queryAll(DictDetailQueryDTO criteria, Page page); + + /** + * 查询全部数据 + * + * @param criteria 字典查询实体 + * @return 字典列表数据 + */ + List queryAll(DictDetailQueryDTO criteria); + + /** + * 根据名称查询字典详情 + * + * @param dictDetailQueryByLabelNameDTO 字典名称 + * @return List 字典集合 + */ + List getDictName(DictDetailQueryByLabelNameDTO dictDetailQueryByLabelNameDTO); +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/service/DictService.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/DictService.java new file mode 100644 index 0000000..5f2b148 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/DictService.java @@ -0,0 +1,101 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.service; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.dubhe.admin.domain.dto.DictCreateDTO; +import org.dubhe.admin.domain.dto.DictDTO; +import org.dubhe.admin.domain.dto.DictQueryDTO; +import org.dubhe.admin.domain.dto.DictUpdateDTO; +import org.dubhe.admin.domain.entity.Dict; + +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * @description 字典服务 Service + * @date 2020-06-01 + */ +public interface DictService { + + /** + * 分页查询 + * + * @param criteria 条件 + * @param page 分页参数 + * @return / + */ + Map queryAll(DictQueryDTO criteria, Page page); + + /** + * 按条件查询字典列表 + * + * @param criteria 字典查询实体 + * @return java.util.List 字典实例 + */ + List queryAll(DictQueryDTO criteria); + + /** + * 通过ID查询字典详情 + * + * @param id 字典ID + * @return org.dubhe.domain.dto.DictDTO 字典实例 + */ + DictDTO findById(Long id); + + /** + * 通过Name查询字典详情 + * + * @param name 字典名称 + * @return org.dubhe.domain.dto.DictDTO 字典实例 + */ + DictDTO findByName(String name); + + /** + * 新增字典 + * + * @param resources 字典新增实体 + * @return org.dubhe.domain.dto.DictDTO 字典实例 + */ + DictDTO create(DictCreateDTO resources); + + /** + * 字典修改 + * + * @param resources 字典修改实体 + */ + void update(DictUpdateDTO resources); + + /** + * 字典批量删除 + * + * @param ids 字典ID + */ + void deleteAll(Set ids); + + /** + * 导出数据 + * + * @param queryAll 待导出的数据 + * @param response 导出http响应 + * @throws IOException 导出异常 + */ + void download(List queryAll, HttpServletResponse response) throws IOException; +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/service/LogService.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/LogService.java new file mode 100644 index 0000000..8c1fcbd --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/LogService.java @@ -0,0 +1,95 @@ +/** + * Copyright 2019-2020 Zheng Jie + * + * Licensed 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 org.dubhe.admin.service; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.dubhe.admin.domain.dto.LogQueryDTO; +import org.dubhe.admin.domain.entity.Log; + +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.List; + +/** + * @description 日志服务 Service + * @date 2020-06-01 + */ +public interface LogService { + + /** + * 分页查询 + * + * @param criteria 查询条件 + * @param page 分页参数 + * @return Object 分页查询响应 + */ + Object queryAll(LogQueryDTO criteria, Page page); + + /** + * 查询全部数据 + * + * @param criteria 查询条件 + * @return 日志列表 + */ + List queryAll(LogQueryDTO criteria); + + /** + * 查询用户日志 + * + * @param criteria 查询条件 + * @param page 分页参数 + * @return 日志 + */ + Object queryAllByUser(LogQueryDTO criteria, Page page); + + /** + * 保存日志数据 + * @param username 用户 + * @param browser 浏览器 + * @param ip 请求IP + * @param joinPoint / + * @param log 日志实体 + */ + //@Async + //void save(String username, String browser, String ip, ProceedingJoinPoint joinPoint, Log log); + + /** + * 查询异常详情 + * + * @param id 日志ID + * @return Object 日志详情 + */ + Object findByErrDetail(Long id); + + /** + * 导出日志 + * + * @param logs 待导出的数据 + * @param response 导出http响应 + * @throws IOException 导出异常 + */ + void download(List logs, HttpServletResponse response) throws IOException; + + /** + * 删除所有错误日志 + */ + void delAllByError(); + + /** + * 删除所有INFO日志 + */ + void delAllByInfo(); +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/service/MailService.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/MailService.java new file mode 100644 index 0000000..52a1c5c --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/MailService.java @@ -0,0 +1,74 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.service; + +import javax.mail.MessagingException; + +/** + * @description 邮箱服务 Service + * @date 2020-06-01 + */ +public interface MailService { + + /** + * 简单文本邮件 + * + * @param to 接收者邮件 + * @param subject 邮件主题 + * @param contnet 邮件内容 + */ + void sendSimpleMail(String to, String subject, String contnet); + + /** + * HTML 文本邮件 + * + * @param to 接收者邮件 + * @param subject 邮件主题 + * @param content HTML内容 + * @throws MessagingException + */ + void sendHtmlMail(String to, String subject, String content) throws MessagingException; + + /** + * 附件邮件 + * + * @param to 接收者邮件 + * @param subject 邮件主题 + * @param content HTML内容 + * @param filePath 附件路径 + * @throws MessagingException + */ + void sendAttachmentsMail(String to, String subject, String content, + String filePath) throws MessagingException; + + + + /** + * 图片邮件 + * + * @param to 接收者邮件 + * @param subject 邮件主题 + * @param content HTML内容 + * @param rscPath 图片路径 + * @param rscId 图片ID + * @throws MessagingException + */ + void sendLinkResourceMail(String to, String subject, String content, + String rscPath, String rscId); + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/service/MenuService.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/MenuService.java new file mode 100644 index 0000000..90bd1ba --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/MenuService.java @@ -0,0 +1,136 @@ +/** + * Copyright 2019-2020 Zheng Jie + * + * Licensed 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 org.dubhe.admin.service; + +import org.dubhe.admin.domain.dto.*; +import org.dubhe.admin.domain.entity.Menu; + +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * @description 菜单服务 Service + * @date 2020-06-01 + */ +public interface MenuService { + + /** + * 按条件查询菜单列表 + * + * @param criteria 菜单请求实体 + * @return java.util.List 菜单返回实例 + */ + List queryAll(MenuQueryDTO criteria); + + /** + * 根据id查询菜单信息 + * + * @param id 菜单id + * @return org.dubhe.domain.dto.MenuDTO 菜单返回实例 + */ + MenuDTO findById(long id); + + /** + * 新增菜单 + * + * @param resources 菜单新增请求实体 + * @return org.dubhe.domain.dto.MenuDTO 菜单返回实例 + */ + MenuDTO create(MenuCreateDTO resources); + + /** + * 修改菜单 + * + * @param resources 菜单修改请求实体 + */ + void update(MenuUpdateDTO resources); + + /** + * 查询可删除的菜单 + * + * @param menuList + * @param menuSet + * @return java.util.Set + */ + Set getDeleteMenus(List menuList, Set menuSet); + + /** + * 获取菜单树 + * + * @param menus 菜单列表 + * @return java.lang.Object 菜单树结构列表 + */ + Object getMenuTree(List menus); + + /** + * 根据ID获取菜单列表 + * + * @param pid id + * @return java.util.List 菜单返回列表 + */ + List findByPid(long pid); + + /** + * 构建菜单树 + * + * @param menuDtos 菜单请求实体 + * @return java.util.Map 菜单树结构 + */ + Map buildTree(List menuDtos); + + /** + * 根据角色查询菜单列表 + * + * @param roles 角色 + * @return java.util.List 菜单返回实例 + */ + List findByRoles(List roles); + + /** + * 构建菜单树 + * + * @param menuDtos 菜单请求实体 + * @return java.util.List 菜单树返回实例 + */ + Object buildMenus(List menuDtos); + + /** + * 获取菜单 + * + * @param id id + * @return org.dubhe.domain.entity.Menu 菜单返回实例 + */ + Menu findOne(Long id); + + /** + * 删除菜单 + * + * @param menuSet 删除菜单请求集合 + */ + void delete(Set menuSet); + + /** + * 导出 + * + * @param queryAll 待导出的数据 + * @param response 导出http响应 + * @throws IOException 导出异常 + */ + void download(List queryAll, HttpServletResponse response) throws IOException; +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/service/PermissionService.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/PermissionService.java new file mode 100644 index 0000000..cffe68b --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/PermissionService.java @@ -0,0 +1,83 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import org.dubhe.admin.domain.dto.PermissionCreateDTO; +import org.dubhe.admin.domain.dto.PermissionDeleteDTO; +import org.dubhe.admin.domain.dto.PermissionQueryDTO; +import org.dubhe.admin.domain.dto.PermissionUpdateDTO; +import org.dubhe.admin.domain.entity.Permission; + +import java.util.List; +import java.util.Map; + +/** + * @description 操作权限服务 + * @date 2021-04-28 + */ +public interface PermissionService extends IService { + + + /** + * 根据ID获取权限列表 + * + * @param pid id + * @return java.util.List 权限返回列表 + */ + List findByPid(long pid); + + /** + * 获取权限树 + * + * @param permissions 权限列表 + * @return java.lang.Object 权限树树结构列表 + */ + Object getPermissionTree(List permissions); + + + /** + * 获取权限列表 + * + * @param permissionQueryDTO 权限查询DTO + * @return Map + */ + Map queryAll(PermissionQueryDTO permissionQueryDTO); + + /** + * 新增权限 + * + * @param permissionCreateDTO 新增权限DTO + */ + void create(PermissionCreateDTO permissionCreateDTO); + + /** + * 修改权限 + * + * @param permissionUpdateDTO 修改权限DTO + */ + void update(PermissionUpdateDTO permissionUpdateDTO); + + /** + * 删除权限 + * + * @param permissionDeleteDTO 删除权限DTO + */ + void delete(PermissionDeleteDTO permissionDeleteDTO); + + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/service/RecycleTaskService.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/RecycleTaskService.java new file mode 100644 index 0000000..fe8f8f7 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/RecycleTaskService.java @@ -0,0 +1,84 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.service; + +import org.dubhe.recycle.domain.dto.RecycleTaskQueryDTO; +import org.dubhe.recycle.domain.entity.Recycle; + +import java.util.List; +import java.util.Map; + +/** + * @description 垃圾回收 + * @date 2021-02-23 + */ +public interface RecycleTaskService { + + + /** + * 查询回收任务列表 + * + * @param recycleTaskQueryDTO 查询任务列表条件 + * @return Map 可回收任务列表 + */ + Map getRecycleTasks(RecycleTaskQueryDTO recycleTaskQueryDTO); + + + /** + * 获取垃圾回收任务列表 + * 资源回收单次执行任务数量限制(默认10000) + * @return List 垃圾回收任务列表 + */ + List getRecycleTaskList(); + + /** + * 执行回收任务(单个) + * @param recycle 回收实体类 + * @param userId 当前操作用户 + */ + void recycleTask(Recycle recycle,long userId); + + + /** + * 实时删除临时目录无效文件 + * + * @param sourcePath 删除路径 + */ + void delTempInvalidResources(String sourcePath); + + /** + * 立即执行回收任务 + * + * @param taskId 回收任务ID + */ + void recycleTaskResources(long taskId); + + /** + * 还原回收任务 + * + * @param taskId 回收任务ID + */ + void restore(long taskId); + + /** + * 根据路径回收无效文件 + * + * @param sourcePath 文件路径 + */ + void deleteInvalidResourcesByCMD(String sourcePath); + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/service/ResourceSpecsService.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/ResourceSpecsService.java new file mode 100644 index 0000000..998d387 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/ResourceSpecsService.java @@ -0,0 +1,65 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.service; + +import org.dubhe.admin.domain.dto.*; +import org.dubhe.biz.base.vo.QueryResourceSpecsVO; +import org.dubhe.biz.base.dto.QueryResourceSpecsDTO; + +import java.util.List; +import java.util.Map; + +/** + * @description CPU, GPU, 内存等资源规格管理 + * @date 2021-05-27 + */ +public interface ResourceSpecsService { + + /** + * 查询资源规格 + * @param resourceSpecsQueryDTO 查询资源规格请求实体 + * @return List resourceSpecs 资源规格列表 + */ + Map getResourceSpecs(ResourceSpecsQueryDTO resourceSpecsQueryDTO); + + /** + * 新增资源规格 + * @param resourceSpecsCreateDTO 新增资源规格实体 + * @return List 新增资源规格id + */ + List create(ResourceSpecsCreateDTO resourceSpecsCreateDTO); + + /** + * 修改资源规格 + * @param resourceSpecsUpdateDTO 修改资源规格实体 + * @return List 修改资源规格id + */ + List update(ResourceSpecsUpdateDTO resourceSpecsUpdateDTO); + + /** + * 资源规格删除 + * @param resourceSpecsDeleteDTO 资源规格删除id集合 + */ + void delete(ResourceSpecsDeleteDTO resourceSpecsDeleteDTO); + + /** + * 查询资源规格 + * @param queryResourceSpecsDTO 查询资源规格请求实体 + * @return QueryResourceSpecsVO 资源规格返回结果实体类 + */ + QueryResourceSpecsVO queryResourceSpecs(QueryResourceSpecsDTO queryResourceSpecsDTO); +} \ No newline at end of file diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/service/RoleService.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/RoleService.java new file mode 100644 index 0000000..2000e30 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/RoleService.java @@ -0,0 +1,141 @@ +/** + * Copyright 2019-2020 Zheng Jie + * + * Licensed 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 org.dubhe.admin.service; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.IService; +import org.dubhe.admin.domain.dto.*; +import org.dubhe.admin.domain.dto.RoleDTO; +import org.dubhe.admin.domain.entity.Role; + +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.List; +import java.util.Set; + +/** + * @description 角色服务 Service + * @date 2020-06-01 + */ +public interface RoleService extends IService { + + /** + * 根据ID查询角色信息 + * + * @param id id + * @return org.dubhe.domain.dto.RoleDTO 角色信息 + */ + RoleDTO findById(long id); + + /** + * 新增角色 + * + * @param resources 角色新增请求实体 + * @return org.dubhe.domain.dto.RoleDTO 角色返回实例 + */ + RoleDTO create(RoleCreateDTO resources); + + /** + * 修改角色 + * + * @param resources 角色修改请求实体 + * @return void + */ + void update(RoleUpdateDTO resources); + + /** + * 批量删除角色 + * + * @param ids 角色ids + */ + void delete(Set ids); + + + /** + * 修改角色菜单 + * + * @param resources 角色菜单请求实体 + * @param roleDTO 角色请求实体 + */ + void updateMenu(RoleUpdateDTO resources, RoleDTO roleDTO); + + + /** + * 删除角色菜单 + * + * @param id 角色id + */ + void untiedMenu(Long id); + + /** + * 按条件查询角色信息 + * + * @param criteria 角色查询条件 + * @return java.util.List 角色信息返回实例 + */ + List queryAllSmall(RoleQueryDTO criteria); + + /** + * 分页查询角色列表 + * + * @param criteria 角色查询条件 + * @param page 分页实体 + * @return java.lang.Object 角色信息返回实例 + */ + Object queryAll(RoleQueryDTO criteria, Page page); + + /** + * 按条件查询角色列表 + * + * @param criteria 角色查询条件 + * @return java.util.List 角色信息返回实例 + */ + List queryAll(RoleQueryDTO criteria); + + /** + * 导出角色信息 + * + * @param roles 角色列表 + * @param response 导出http响应 + */ + void download(List roles, HttpServletResponse response) throws IOException; + + /** + * 根据用户ID获取角色信息 + * + * @param userId 用户ID + * @return java.util.List 角色列表 + */ + List getRoleByUserId( Long userId); + + /** + * 获取角色列表 + * + * @param userId 用户ID + * @param teamId 团队ID + * @return java.util.List 角色列表 + */ + List getRoleByUserIdAndTeamId( Long userId,Long teamId); + + + /** + * 新增角色菜单 + * + * @param roleId 角色ID + * @param menuId 菜单ID + */ + void tiedRoleMenu(Long roleId, Long menuId); +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/service/TeamService.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/TeamService.java new file mode 100644 index 0000000..560dab1 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/TeamService.java @@ -0,0 +1,102 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.service; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.dubhe.admin.domain.dto.TeamCreateDTO; +import org.dubhe.biz.base.dto.TeamDTO; +import org.dubhe.admin.domain.dto.TeamQueryDTO; +import org.dubhe.admin.domain.dto.TeamUpdateDTO; + +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.List; +import java.util.Set; + +/** + * @description 团队服务 Service + * @date 2020-06-01 + */ +public interface TeamService { + + /** + * 获取团队列表 + * + * @param criteria 查询团队列表条件 + * @return java.util.List 团队列表条件 + */ + List queryAll(TeamQueryDTO criteria); + + /** + * 查询团队列表 + * + * @param page 分页请求实体 + * @return java.util.List 团队列表 + */ + List queryAll(Page page); + + /** + * 分页查询团队列表 + * + * @param criteria 查询请求条件 + * @param page 分页实体 + * @return java.lang.Object 团队列表 + */ + Object queryAll(TeamQueryDTO criteria, Page page); + + /** + * 根据ID插叙团队信息 + * + * @param id id + * @return org.dubhe.domain.dto.TeamDTO 团队返回实例 + */ + TeamDTO findById(Long id); + + /** + * 新增团队信息 + * + * @param resources 团队新增请求实体 + * @return org.dubhe.domain.dto.TeamDTO 团队返回实例 + */ + TeamDTO create(TeamCreateDTO resources); + + /** + * 修改团队 + * + * @param resources 团队修改请求实体 + */ + void update(TeamUpdateDTO resources); + + /** + * 团队删除 + * + * @param deptDtos 团队删除列表 + */ + void delete(Set deptDtos); + + + + /** + * 团队信息导出 + * + * @param teamDtos 团队列表 + * @param response 导出http响应 + */ + void download(List teamDtos, HttpServletResponse response) throws IOException; + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/service/UserGroupService.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/UserGroupService.java new file mode 100644 index 0000000..b89f466 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/UserGroupService.java @@ -0,0 +1,112 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.service; + +import org.dubhe.admin.domain.dto.*; +import org.dubhe.admin.domain.entity.Group; +import org.dubhe.admin.domain.entity.User; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * @description 用户组服务类 + * @date 2021-05-06 + */ +public interface UserGroupService { + + + /** + * 分页查询用户组列表 + * + * @param queryDTO 查询实体DTO + * @return Map 用户组及分页信息 + */ + Map queryAll(UserGroupQueryDTO queryDTO); + + /** + * 新增用户组 + * + * @param groupCreateDTO 新增用户组实体DTO + */ + Group create(UserGroupDTO groupCreateDTO); + + /** + * 修改用户组信息 + * + * @param groupUpdateDTO 修改用户组实体DTO + */ + void update(UserGroupDTO groupUpdateDTO); + + /** + * 删除用户组 + * + * @param ids 用户组ids + */ + void delete(Set ids); + + /** + * 修改用户组成员 + * + * @param userGroupUpdDTO 新增组用户DTO实体 + */ + void updUserWithGroup(UserGroupUpdDTO userGroupUpdDTO); + + /** + * 删除用户组成员 + * + * @param userGroupDelDTO 删除用户组成员 + */ + void delUserWithGroup(UserGroupUpdDTO userGroupDelDTO); + + /** + * 获取没有归属组的用户 + * + * @return List 没有归属组的用户 + */ + List findUserWithOutGroup(); + + /** + * 获取用户组成员信息 + * + * @param groupId 用户组id + * @return List 用户列表 + */ + List queryUserByGroupId(Long groupId); + + /** + * 批量修改用户组成员的状态 + * + * @param userStateUpdateDTO 实体DTO + */ + void updateUserState(UserStateUpdateDTO userStateUpdateDTO); + + /** + * 批量删除用户组用户 + * + * @param userGroupUpdDTO 批量删除用户组用户DTO + */ + void delUser(UserGroupUpdDTO userGroupUpdDTO); + + /** + * 批量修改用户组用户的角色 + * + * @param userRoleUpdateDTO + */ + void updateUserRole(UserRoleUpdateDTO userRoleUpdateDTO); +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/service/UserService.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/UserService.java new file mode 100644 index 0000000..b73b0f2 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/UserService.java @@ -0,0 +1,224 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.service; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.IService; +import org.dubhe.admin.domain.dto.*; +import org.dubhe.admin.domain.entity.User; +import org.dubhe.biz.base.dto.TeamDTO; +import org.dubhe.biz.base.dto.UserDTO; +import org.dubhe.biz.base.vo.DataResponseBody; +import org.dubhe.cloud.authconfig.service.AdminUserService; + +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * @description Demo服务接口 + * @date 2020-11-26 + */ +public interface UserService extends AdminUserService, IService { + + + /** + * 根据ID获取用户信息 + * + * @param id 用户Id + * @return org.dubhe.domain.dto.UserDTO 用户信息返回实例 + */ + UserDTO findById(long id); + + /** + * 新增用户 + * + * @param resources 用户新增实体 + * @return org.dubhe.domain.dto.UserDTO 用户信息返回实例 + */ + UserDTO create(UserCreateDTO resources); + + /** + * 修改用户 + * + * @param resources 用户修改请求实例 + * @return org.dubhe.domain.dto.UserDTO 用户信息返回实例 + */ + UserDTO update(UserUpdateDTO resources); + + /** + * 批量删除用户信息 + * + * @param ids 用户ID列表 + */ + void delete(Set ids); + + /** + * 根据用户名称获取用户信息 + * + * @param userName 用户名称 + * @return org.dubhe.domain.dto.UserDTO 用户信息返回实例 + */ + UserDTO findByName(String userName); + + /** + * 修改用户密码 + * + * @param username 账号 + * @param encryptPassword 密码 + * @return void + */ + void updatePass(String username, String encryptPassword); + + /** + * 修改头像 + * + * @param realName 文件名 + * @param path 文件路径 + */ + void updateAvatar(String realName, String path); + + /** + * 修改邮箱 + * + * @param username 用户名 + * @param email 邮箱 + */ + void updateEmail(String username, String email); + + /** + * 分页查询用户列表 + * + * @param criteria 查询条件 + * @param page 分页请求实体 + * @return java.lang.Object 用户列表返回实例 + */ + Object queryAll(UserQueryDTO criteria, Page page); + + /** + * 查询用户列表 + * + * @param criteria 用户查询条件 + * @return java.util.List 用户列表返回实例 + */ + List queryAll(UserQueryDTO criteria); + + /** + * 根据用户ID查询团队列表 + * + * @param userId 用户ID + * @return java.util.List 团队列表信息 + */ + List queryTeams(Long userId); + + /** + * 导出数据 + * + * @param queryAll 待导出的数据 + * @param response 导出http响应 + * @throws IOException 导出异常 + */ + void download(List queryAll, HttpServletResponse response) throws IOException; + + /** + * 修改用户个人中心信息 + * + * @param resources 个人用户信息修改请求实例 + */ + void updateCenter(UserCenterUpdateDTO resources); + + /** + * 查询用户ID权限 + * + * @param id 用户ID + * @return java.util.Set 权限列表 + */ + Set queryPermissionByUserId(Long id); + + /** + * 用户注册信息 + * + * @param userRegisterDTO 用户注册请求实体 + * @return org.dubhe.base.DataResponseBody 注册返回结果集 + */ + DataResponseBody userRegister(UserRegisterDTO userRegisterDTO); + + + /** + * 获取code通过发送邮件 + * + * @param userRegisterMailDTO 用户发送邮件请求实体 + * @return org.dubhe.base.DataResponseBody 发送邮件返回结果集 + */ + DataResponseBody getCodeBySentEmail(UserRegisterMailDTO userRegisterMailDTO); + + + /** + * 邮箱修改 + * + * @param userEmailUpdateDTO 修改邮箱请求实体 + * @return org.dubhe.base.DataResponseBody 修改邮箱返回结果集 + */ + DataResponseBody resetEmail(UserEmailUpdateDTO userEmailUpdateDTO); + + /** + * 获取用户信息 + * + * @return java.util.Map 用户信息结果集 + */ + Map userinfo(); + + /** + * 密码重置接口 + * + * @param userResetPasswordDTO 密码修改请求参数 + * @return org.dubhe.base.DataResponseBody 密码修改结果集 + */ + DataResponseBody resetPassword(UserResetPasswordDTO userResetPasswordDTO); + + /** + * 登录 + * + * @param authUserDTO 登录请求实体 + */ + DataResponseBody> login(AuthUserDTO authUserDTO); + + /** + * 退出登录 + * + * @param accessToken token + */ + DataResponseBody logout(String accessToken); + + /** + * 根据用户昵称获取用户信息 + * + * @param nickName 用户昵称 + * @return org.dubhe.domain.dto.UserDTO 用户信息DTO集合 + */ + List findByNickName(String nickName); + + /** + * 根据用户id批量查询用户信息 + * + * @param ids 用户id集合 + * @return org.dubhe.domain.dto.UserDTO 用户信息DTO集合 + */ + List getUserList(List ids); +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/service/convert/DictConvert.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/convert/DictConvert.java new file mode 100644 index 0000000..9c3f52a --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/convert/DictConvert.java @@ -0,0 +1,33 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.service.convert; + +import org.dubhe.admin.domain.dto.DictDTO; +import org.dubhe.admin.domain.entity.Dict; +import org.dubhe.biz.db.base.BaseConvert; +import org.mapstruct.Mapper; +import org.mapstruct.ReportingPolicy; + + +/** + * @description 字典 转换类 + * @date 2020-06-01 + */ +@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE) +public interface DictConvert extends BaseConvert { + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/service/convert/DictDetailConvert.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/convert/DictDetailConvert.java new file mode 100644 index 0000000..41fe4ae --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/convert/DictDetailConvert.java @@ -0,0 +1,31 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.service.convert; + +import org.dubhe.biz.db.base.BaseConvert; +import org.dubhe.admin.domain.entity.DictDetail; +import org.dubhe.admin.domain.dto.DictDetailDTO; +import org.mapstruct.Mapper; +import org.mapstruct.ReportingPolicy; + +/** + * @description 字典详情 转换类 + * @date 2020-06-01 + */ +@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE) +public interface DictDetailConvert extends BaseConvert { +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/service/convert/DictSmallConvert.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/convert/DictSmallConvert.java new file mode 100644 index 0000000..9a19560 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/convert/DictSmallConvert.java @@ -0,0 +1,32 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.service.convert; + +import org.dubhe.biz.db.base.BaseConvert; +import org.dubhe.admin.domain.dto.DictSmallQueryDTO; +import org.dubhe.admin.domain.entity.Dict; +import org.mapstruct.Mapper; +import org.mapstruct.ReportingPolicy; + +/** + * @description 字典详情 转换类 + * @date 2020-06-01 + */ +@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE) +public interface DictSmallConvert extends BaseConvert { + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/service/convert/LogConvert.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/convert/LogConvert.java new file mode 100644 index 0000000..f88fcd3 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/convert/LogConvert.java @@ -0,0 +1,32 @@ +/** + * Copyright 2019-2020 Zheng Jie + * + * Licensed 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 org.dubhe.admin.service.convert; + +import org.dubhe.admin.domain.dto.LogDTO; +import org.dubhe.admin.domain.entity.Log; +import org.dubhe.biz.db.base.BaseConvert; +import org.mapstruct.Mapper; +import org.mapstruct.ReportingPolicy; + +/** + * @description 日志 转换类 + * @date 2020-06-01 + */ +@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE) +public interface LogConvert extends BaseConvert { + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/service/convert/MenuConvert.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/convert/MenuConvert.java new file mode 100644 index 0000000..0f8e52a --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/convert/MenuConvert.java @@ -0,0 +1,32 @@ +/** + * Copyright 2019-2020 Zheng Jie + * + * Licensed 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 org.dubhe.admin.service.convert; + + +import org.dubhe.admin.domain.dto.MenuDTO; +import org.dubhe.biz.db.base.BaseConvert; +import org.dubhe.admin.domain.entity.Menu; +import org.mapstruct.Mapper; +import org.mapstruct.ReportingPolicy; + +/** + * @description 菜单 转换类 + * @date 2020-06-01 + */ +@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE) +public interface MenuConvert extends BaseConvert { + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/service/convert/PermissionConvert.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/convert/PermissionConvert.java new file mode 100644 index 0000000..8a82aa9 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/convert/PermissionConvert.java @@ -0,0 +1,31 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.service.convert; + +import org.dubhe.admin.domain.entity.Permission; +import org.dubhe.admin.domain.vo.PermissionVO; +import org.dubhe.biz.db.base.BaseConvert; +import org.mapstruct.Mapper; +import org.mapstruct.ReportingPolicy; + +/** + * @description permission转换器 + * @date 2021-05-31 + */ +@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE) +public interface PermissionConvert extends BaseConvert { +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/service/convert/RoleConvert.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/convert/RoleConvert.java new file mode 100644 index 0000000..d1112a2 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/convert/RoleConvert.java @@ -0,0 +1,30 @@ +/** + * Copyright 2019-2020 Zheng Jie + * + * Licensed 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 org.dubhe.admin.service.convert; + +import org.dubhe.admin.domain.dto.RoleDTO; +import org.dubhe.biz.db.base.BaseConvert; +import org.dubhe.admin.domain.entity.Role; +import org.mapstruct.Mapper; +import org.mapstruct.ReportingPolicy; + +/** + * @description 角色 转换类 + * @date 2020-06-01 + */ +@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE) +public interface RoleConvert extends BaseConvert { +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/service/convert/RoleSmallConvert.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/convert/RoleSmallConvert.java new file mode 100644 index 0000000..3fd21ee --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/convert/RoleSmallConvert.java @@ -0,0 +1,31 @@ +/** + * Copyright 2019-2020 Zheng Jie + * + * Licensed 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 org.dubhe.admin.service.convert; + +import org.dubhe.admin.domain.dto.RoleSmallDTO; +import org.dubhe.biz.db.base.BaseConvert; +import org.dubhe.admin.domain.entity.Role; +import org.mapstruct.Mapper; +import org.mapstruct.ReportingPolicy; + +/** + * @description 角色 转换类 + * @date 2020-06-01 + */ +@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE) +public interface RoleSmallConvert extends BaseConvert { + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/service/convert/TeamConvert.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/convert/TeamConvert.java new file mode 100644 index 0000000..767ea07 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/convert/TeamConvert.java @@ -0,0 +1,33 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.service.convert; + +import org.dubhe.biz.base.dto.TeamDTO; +import org.dubhe.biz.db.base.BaseConvert; +import org.dubhe.admin.domain.entity.Team; +import org.mapstruct.Mapper; +import org.mapstruct.ReportingPolicy; + +/** + * @description 团队 转换类 + * @date 2020-06-01 + */ +@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE) +public interface TeamConvert extends BaseConvert { + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/service/convert/TeamSmallConvert.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/convert/TeamSmallConvert.java new file mode 100644 index 0000000..ee2b2fe --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/convert/TeamSmallConvert.java @@ -0,0 +1,32 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.service.convert; + +import org.dubhe.biz.base.dto.TeamSmallDTO; +import org.dubhe.biz.db.base.BaseConvert; +import org.dubhe.admin.domain.entity.Team; +import org.mapstruct.Mapper; +import org.mapstruct.ReportingPolicy; + +/** + * @description 团队 转换类 + * @date 2020-06-01 + */ +@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE) +public interface TeamSmallConvert extends BaseConvert { +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/service/convert/UserConvert.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/convert/UserConvert.java new file mode 100644 index 0000000..ff77543 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/convert/UserConvert.java @@ -0,0 +1,31 @@ +/** + * Copyright 2019-2020 Zheng Jie + * + * Licensed 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 org.dubhe.admin.service.convert; + +import org.dubhe.biz.base.dto.UserDTO; +import org.dubhe.biz.db.base.BaseConvert; +import org.dubhe.admin.domain.entity.User; +import org.mapstruct.Mapper; +import org.mapstruct.ReportingPolicy; + +/** + * @description 用户 转换类 + * @date 2020-06-01 + */ +@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE) +public interface UserConvert extends BaseConvert { + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/service/impl/AuthCodeServiceImpl.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/impl/AuthCodeServiceImpl.java new file mode 100644 index 0000000..758d57b --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/impl/AuthCodeServiceImpl.java @@ -0,0 +1,236 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.service.impl; + +import cn.hutool.core.bean.BeanUtil; +import cn.hutool.core.collection.CollUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import org.dubhe.admin.dao.AuthCodeMapper; +import org.dubhe.admin.domain.dto.AuthCodeCreateDTO; +import org.dubhe.admin.domain.dto.AuthCodeQueryDTO; +import org.dubhe.admin.domain.dto.AuthCodeUpdateDTO; +import org.dubhe.admin.domain.dto.RoleAuthUpdateDTO; +import org.dubhe.admin.domain.entity.Auth; +import org.dubhe.admin.domain.entity.AuthPermission; +import org.dubhe.admin.domain.entity.Permission; +import org.dubhe.admin.domain.entity.RoleAuth; +import org.dubhe.admin.domain.vo.AuthVO; +import org.dubhe.admin.service.AuthCodeService; +import org.dubhe.biz.base.constant.StringConstant; +import org.dubhe.biz.base.exception.BusinessException; +import org.dubhe.biz.base.service.UserContextService; +import org.dubhe.biz.base.utils.ReflectionUtils; +import org.dubhe.biz.base.utils.StringUtils; +import org.dubhe.biz.db.utils.PageUtil; +import org.springframework.beans.BeanUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.*; +import java.util.stream.Collectors; + +/** + * @description 权限组服务实现类 + * @date 2021-05-14 + */ +@Service +public class AuthCodeServiceImpl extends ServiceImpl implements AuthCodeService { + + @Autowired + private AuthCodeMapper authCodeMapper; + + @Autowired + private UserContextService userContextService; + + public final static List FIELD_NAMES; + + static { + FIELD_NAMES = ReflectionUtils.getFieldNames(AuthVO.class); + } + + /** + * 分页查询权限组信息 + * + * @param authCodeQueryDTO 分页查询实例 + * @return Map 权限组分页信息 + */ + @Override + public Map queryAll(AuthCodeQueryDTO authCodeQueryDTO) { + + Page page = authCodeQueryDTO.toPage(); + QueryWrapper queryWrapper = new QueryWrapper<>(); + + if (StringUtils.isNotEmpty(authCodeQueryDTO.getAuthCode())) { + queryWrapper.and(x -> x.eq("id", authCodeQueryDTO.getAuthCode()).or().like("authCOde", authCodeQueryDTO.getAuthCode())); + } + + //排序 + IPage groupList; + try { + if (authCodeQueryDTO.getSort() != null && FIELD_NAMES.contains(authCodeQueryDTO.getSort())) { + if (StringConstant.SORT_ASC.equalsIgnoreCase(authCodeQueryDTO.getOrder())) { + queryWrapper.orderByAsc(StringUtils.humpToLine(authCodeQueryDTO.getSort())); + } else { + queryWrapper.orderByDesc(StringUtils.humpToLine(authCodeQueryDTO.getSort())); + } + } else { + queryWrapper.orderByDesc(StringConstant.ID); + } + groupList = authCodeMapper.selectPage(page, queryWrapper); + } catch (Exception e) { + throw new BusinessException("查询权限组列表展示异常"); + } + List authResult = groupList.getRecords().stream().map(x -> { + AuthVO authVO = new AuthVO(); + BeanUtils.copyProperties(x, authVO); + List permissions = authCodeMapper.getPermissionByAuthId(x.getId()); + authVO.setPermissions(permissions); + return authVO; + }).collect(Collectors.toList()); + return PageUtil.toPage(page, authResult); + } + + /** + * 创建权限组 + * + * @param authCodeCreateDTO 创建权限组DTO实例 + */ + @Transactional(rollbackFor = Exception.class) + @Override + public void create(AuthCodeCreateDTO authCodeCreateDTO) { + //获取当前用户id + Long curUserId = userContextService.getCurUserId(); + Auth auth = new Auth(); + BeanUtil.copyProperties(authCodeCreateDTO, auth); + checkAuthCodeIsExist(auth); + auth.setCreateUserId(curUserId); + authCodeMapper.insert(auth); + tiedWithPermission(auth.getId(), authCodeCreateDTO.getPermissions()); + } + + /** + * 修改权限组信息 + * + * @param authCodeUpdateDTO 修改权限组信息DTO实例 + */ + @Transactional(rollbackFor = Exception.class) + @Override + public void update(AuthCodeUpdateDTO authCodeUpdateDTO) { + //获取当前用户id + Long curUserId = userContextService.getCurUserId(); + Auth auth = new Auth(); + BeanUtil.copyProperties(authCodeUpdateDTO, auth); + checkAuthCodeIsExist(auth); + auth.setUpdateUserId(curUserId); + authCodeMapper.updateById(auth); + if (CollUtil.isNotEmpty(authCodeUpdateDTO.getPermissions())) { + authCodeMapper.untiedWithPermission(authCodeUpdateDTO.getId()); + tiedWithPermission(auth.getId(), authCodeUpdateDTO.getPermissions()); + } + } + + /** + * 批量删除权限组 + * + * @param ids 权限组id集合 + */ + @Override + public void delete(Set ids) { + //删除权限组数据 + removeByIds(ids); + //清除权限组和权限映射关系 + for (Long id : ids) { + authCodeMapper.untiedWithPermission(id); + } + } + + + private void tiedWithPermission(Long authId, Set permissionIds) { + List list = new ArrayList<>(); + for (Long id : permissionIds) { + AuthPermission authPermission = new AuthPermission(); + authPermission.setAuthId(authId); + authPermission.setPermissionId(id); + list.add(authPermission); + } + authCodeMapper.tiedWithPermission(list); + } + + /** + * 修改角色权限 + * + * @param roleAuthUpdateDTO + * @return + */ + @Override + public void updateRoleAuth(RoleAuthUpdateDTO roleAuthUpdateDTO) { + authCodeMapper.untiedRoleAuthByRoleId(roleAuthUpdateDTO.getRoleId()); + List roleAuths = new ArrayList<>(); + if(CollUtil.isNotEmpty(roleAuthUpdateDTO.getAuthIds())) { + for (Long authId : roleAuthUpdateDTO.getAuthIds()) { + RoleAuth roleAuth = new RoleAuth(); + roleAuth.setRoleId(roleAuthUpdateDTO.getRoleId()); + roleAuth.setAuthId(authId); + roleAuths.add(roleAuth); + } + authCodeMapper.tiedRoleAuth(roleAuths); + } + } + + /** + * 获取权限组tree + * + * @return List 权限组tree + */ + @Override + public List getAuthCodeList() { + List authList = authCodeMapper.selectList(new LambdaQueryWrapper<>()); + List resultList = new ArrayList<>(); + if (CollUtil.isNotEmpty(authList)) { + for (Auth auth : authList) { + AuthVO authVO = new AuthVO(); + BeanUtils.copyProperties(auth, authVO); + List permissions = authCodeMapper.getPermissionByAuthId(authVO.getId()); + authVO.setPermissions(permissions); + resultList.add(authVO); + } + } + return resultList; + } + + /** + * 根据authCode获取权限组 + * + * @param auth 权限组名称 + * @return List 权限组列表 + */ + private void checkAuthCodeIsExist(Auth auth) { + List authList = authCodeMapper.selectList(new LambdaQueryWrapper() + .eq(Auth::getAuthCode, auth.getAuthCode())); + for (Auth authObj : authList) { + if (Objects.equals(auth.getAuthCode(), authObj.getAuthCode()) && + !Objects.equals(auth.getId(), authObj.getId())) { + throw new BusinessException("权限组名称不能重复"); + } + } + } +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/service/impl/DataSequenceServiceImpl.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/impl/DataSequenceServiceImpl.java new file mode 100644 index 0000000..2f33451 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/impl/DataSequenceServiceImpl.java @@ -0,0 +1,102 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.service.impl; + +import org.dubhe.admin.dao.DataSequenceMapper; +import org.dubhe.admin.domain.entity.DataSequence; +import org.dubhe.biz.base.exception.DataSequenceException; +import org.dubhe.admin.service.DataSequenceService; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + + +/** + * @description 获取序列服务接口实现 + * @date 2020-09-23 + */ +@Service +public class DataSequenceServiceImpl implements DataSequenceService { + + @Autowired + private DataSequenceMapper dataSequenceMapper; + + @Override + public DataSequence getSequence(String businessCode) { + return dataSequenceMapper.selectByBusiness(businessCode); + } + + /** + * 修改步长 + * + * @param businessCode 业务编码 + * @return + */ + @Override + public int updateSequenceStart(String businessCode) { + return dataSequenceMapper.updateStartByBusinessCode(businessCode); + } + + /** + * 检查表是否存在 + * + * @param tableName 表名 + * @return 是否存在标识 + */ + @Override + public boolean checkTableExist(String tableName) { + try { + dataSequenceMapper.checkTableExist(tableName); + return true; + }catch (Exception e){ + LogUtil.info(LogEnum.DATA_SEQUENCE,"表不存在"); + return false; + } + } + + /** + * 创建表 + * + * @param tableName 表名 + */ + @Override + public void createTable(String tableName) { + String oldTableName = tableName.substring(0,tableName.lastIndexOf("_")); + dataSequenceMapper.createNewTable(tableName,oldTableName); + } + + /** + * 扩容可用数量 + * + * @param businessCode 业务编码 + * @return DataSequence 数据ID序列 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public DataSequence expansionUsedNumber(String businessCode) { + DataSequence dataSequenceNew = getSequence(businessCode); + if (dataSequenceNew == null || dataSequenceNew.getStart() == null || dataSequenceNew.getStep() == null) { + throw new DataSequenceException("配置出错,请检查data_sequence表配置"); + } + updateSequenceStart(businessCode); + return dataSequenceNew; + } + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/service/impl/DictDetailServiceImpl.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/impl/DictDetailServiceImpl.java new file mode 100644 index 0000000..0683e73 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/impl/DictDetailServiceImpl.java @@ -0,0 +1,168 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.service.impl; + +import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.dubhe.admin.dao.DictDetailMapper; +import org.dubhe.admin.domain.dto.DictDetailCreateDTO; +import org.dubhe.admin.domain.dto.DictDetailDTO; +import org.dubhe.admin.domain.dto.DictDetailQueryDTO; +import org.dubhe.admin.domain.dto.DictDetailUpdateDTO; +import org.dubhe.admin.domain.entity.DictDetail; +import org.dubhe.admin.service.DictDetailService; +import org.dubhe.admin.service.convert.DictDetailConvert; +import org.dubhe.biz.base.dto.DictDetailQueryByLabelNameDTO; +import org.dubhe.biz.base.exception.BusinessException; +import org.dubhe.biz.base.vo.DictDetailVO; +import org.dubhe.biz.db.utils.PageUtil; +import org.dubhe.biz.db.utils.WrapperHelp; +import org.springframework.beans.BeanUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.CollectionUtils; + +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * @description 字典详情服务 实现类 + * @date 2020-06-01 + */ +@Service +public class DictDetailServiceImpl implements DictDetailService { + + @Autowired + private DictDetailMapper dictDetailMapper; + + @Autowired + private DictDetailConvert dictDetailConvert; + + /** + * 分页查询字典详情 + * + * @param criteria 字典详情查询实体 + * @param page 分页实体 + * @return java.util.Map 字典详情分页实例 + */ + @Override + public Map queryAll(DictDetailQueryDTO criteria, Page page) { + IPage dictDetails = dictDetailMapper.selectPage(page, WrapperHelp.getWrapper(criteria)); + return PageUtil.toPage(dictDetails, dictDetailConvert::toDto); + } + + + /** + * 按条件查询字典列表 + * + * @param criteria 字典详情查询实体 + * @return java.util.List 字典详情实例 + */ + @Override + public List queryAll(DictDetailQueryDTO criteria) { + List list = dictDetailMapper.selectList(WrapperHelp.getWrapper(criteria)); + return dictDetailConvert.toDto(list); + } + + + /** + * 根据ID查询字典详情 + * + * @param id 字典详情ID + * @return org.dubhe.domain.dto.DictDetailDTO 字典详情实例 + */ + @Override + public DictDetailDTO findById(Long id) { + DictDetail dictDetail = dictDetailMapper.selectById(id); + return dictDetailConvert.toDto(dictDetail); + } + + /** + * 新增字典性情 + * + * @param resources 字典详情新增实体 + * @return org.dubhe.domain.dto.DictDetailDTO 字典详情实例 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public DictDetailDTO create(DictDetailCreateDTO resources) { + if (!ObjectUtil.isNull(dictDetailMapper.selectByDictIdAndLabel(resources.getDictId(), resources.getLabel()))) { + throw new BusinessException("字典标签已存在"); + } + DictDetail dictDetail = DictDetail.builder().build(); + BeanUtils.copyProperties(resources, dictDetail); + dictDetailMapper.insert(dictDetail); + return dictDetailConvert.toDto(dictDetail); + } + + /** + * 修改字典详情 + * + * @param resources 字典详情修改实体 + * @return void + */ + @Override + @Transactional(rollbackFor = Exception.class) + public void update(DictDetailUpdateDTO resources) { + DictDetail detail = dictDetailMapper.selectByDictIdAndLabel(resources.getDictId(), resources.getLabel()); + if (detail != null && !detail.getId().equals(resources.getId())) { + throw new BusinessException("字典标签已存在"); + } + DictDetail dbDetail = DictDetail.builder().build(); + BeanUtils.copyProperties(resources, dbDetail); + dictDetailMapper.updateById(dbDetail); + } + + /** + * 删除字典详情 + * + * @param ids 字典详情ID + * @return void + */ + @Override + @Transactional(rollbackFor = Exception.class) + public void delete(Set ids) { + dictDetailMapper.deleteBatchIds(ids); + } + + /** + * + * @param dictDetailQueryByLabelNameDTO 字典名称 + * @return List 字典集合 + */ + @Override + public List getDictName(DictDetailQueryByLabelNameDTO dictDetailQueryByLabelNameDTO) { + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<>(); + lambdaQueryWrapper.eq(DictDetail::getLabel, dictDetailQueryByLabelNameDTO.getName()); + List dictDetails = dictDetailMapper.selectList(lambdaQueryWrapper); + List DictDetailVOS = null; + if (!CollectionUtils.isEmpty(dictDetails)) { + DictDetailVOS = dictDetails.stream().map(x -> { + DictDetailVO dictDetailVO = new DictDetailVO(); + BeanUtils.copyProperties(x, dictDetailVO); + return dictDetailVO; + }).collect(Collectors.toList()); + } + return DictDetailVOS; + } + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/service/impl/DictServiceImpl.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/impl/DictServiceImpl.java new file mode 100644 index 0000000..55b387c --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/impl/DictServiceImpl.java @@ -0,0 +1,208 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.service.impl; + +import cn.hutool.core.collection.CollectionUtil; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.dubhe.admin.dao.DictDetailMapper; +import org.dubhe.admin.dao.DictMapper; +import org.dubhe.admin.domain.dto.*; +import org.dubhe.admin.domain.entity.Dict; +import org.dubhe.admin.service.DictService; +import org.dubhe.admin.service.convert.DictConvert; +import org.dubhe.biz.base.exception.BusinessException; +import org.dubhe.biz.db.utils.PageUtil; +import org.dubhe.biz.db.utils.WrapperHelp; +import org.dubhe.biz.file.utils.DubheFileUtil; +import org.springframework.beans.BeanUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.*; + +/** + * @description 字典服务 实现类 + * @date 2020-06-01 + */ +@Service +public class DictServiceImpl implements DictService { + + @Autowired + private DictMapper dictMapper; + + @Autowired + private DictDetailMapper dictDetailMapper; + + @Autowired + private DictConvert dictConvert; + + + /** + * 分页查询字典信息 + * + * @param criteria 字典查询实体 + * @param page 分页实体 + * @return java.util.Map 字典分页实例 + */ + @Override + public Map queryAll(DictQueryDTO criteria, Page page) { + IPage dicts = dictMapper.selectCollPage(page, WrapperHelp.getWrapper(criteria)); + return PageUtil.toPage(dicts, dictConvert::toDto); + } + + + /** + * 按条件查询字典列表 + * + * @param criteria 字典查询实体 + * @return java.util.List 字典实例 + */ + @Override + public List queryAll(DictQueryDTO criteria) { + List list = dictMapper.selectCollList(WrapperHelp.getWrapper(criteria)); + return dictConvert.toDto(list); + } + + /** + * 通过ID查询字典详情 + * + * @param id 字典ID + * @return org.dubhe.domain.dto.DictDTO 字典实例 + */ + @Override + public DictDTO findById(Long id) { + Dict dict = dictMapper.selectCollById(id); + return dictConvert.toDto(dict); + } + + /** + * 通过Name查询字典详情 + * + * @param name 字典名称 + * @return org.dubhe.domain.dto.DictDTO 字典实例 + */ + @Override + public DictDTO findByName(String name) { + Dict dict = dictMapper.selectCollByName(name); + return dictConvert.toDto(dict); + } + + /** + * 新增字典 + * + * @param resources 字典新增实体 + * @return org.dubhe.domain.dto.DictDTO 字典实例 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public DictDTO create(DictCreateDTO resources) { + if (dictMapper.selectCollByName(resources.getName()) != null) { + throw new BusinessException("字典名称已存在"); + } + Dict dict = Dict.builder().build(); + BeanUtils.copyProperties(resources, dict); + dictMapper.insert(dict); + // 级联保存子表 + resources.getDictDetails().forEach(detail -> { + detail.setDictId(dict.getId()); + dictDetailMapper.insert(detail); + }); + return dictConvert.toDto(dict); + } + + /** + * 字典修改 + * + * @param resources 字典修改实体 + * @return void + */ + @Override + @Transactional(rollbackFor = Exception.class) + public void update(DictUpdateDTO resources) { + Dict dict = dictMapper.selectCollByName(resources.getName()); + if (dict != null && !dict.getId().equals(resources.getId())) { + throw new BusinessException("字典名称已存在"); + } + Dict dbDict = Dict.builder().build(); + BeanUtils.copyProperties(resources, dbDict); + dictMapper.updateById(dbDict); + //级联保存子表 + resources.getDictDetails().forEach(detail -> { + detail.setDictId(dbDict.getId()); + if (detail.getId() == null) { + dictDetailMapper.insert(detail); + } else { + dictDetailMapper.updateById(detail); + } + + }); + } + + + /** + * 字典批量删除 + * + * @param ids 字典ID + * @return void + */ + @Override + @Transactional(rollbackFor = Exception.class) + public void deleteAll(Set ids) { + for (Long id : ids) { + dictMapper.deleteById(id); + dictDetailMapper.deleteByDictId(id); + } + } + + /** + * 字典导出 + * + * @param dictDtos 字典导出实体 + * @param response + * @return void + */ + @Override + public void download(List dictDtos, HttpServletResponse response) throws IOException { + List> list = new ArrayList<>(); + for (DictDTO dictDTO : dictDtos) { + if (CollectionUtil.isNotEmpty(dictDTO.getDictDetails())) { + for (DictDetailDTO dictDetail : dictDTO.getDictDetails()) { + Map map = new LinkedHashMap<>(); + map.put("字典名称", dictDTO.getName()); + map.put("字典描述", dictDTO.getRemark()); + map.put("字典标签", dictDetail.getLabel()); + map.put("字典值", dictDetail.getValue()); + map.put("创建日期", dictDetail.getCreateTime()); + list.add(map); + } + } else { + Map map = new LinkedHashMap<>(); + map.put("字典名称", dictDTO.getName()); + map.put("字典描述", dictDTO.getRemark()); + map.put("字典标签", null); + map.put("字典值", null); + map.put("创建日期", dictDTO.getCreateTime()); + list.add(map); + } + } + DubheFileUtil.downloadExcel(list, response); + } +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/service/impl/LogServiceImpl.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/impl/LogServiceImpl.java new file mode 100644 index 0000000..9ac6125 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/impl/LogServiceImpl.java @@ -0,0 +1,148 @@ +/** + * Copyright 2019-2020 Zheng Jie + * + * Licensed 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 org.dubhe.admin.service.impl; + +import cn.hutool.core.lang.Dict; +import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.dubhe.admin.dao.LogMapper; +import org.dubhe.admin.domain.dto.LogQueryDTO; +import org.dubhe.admin.domain.entity.Log; +import org.dubhe.admin.service.LogService; +import org.dubhe.admin.service.convert.LogConvert; +import org.dubhe.biz.db.utils.PageUtil; +import org.dubhe.biz.db.utils.WrapperHelp; +import org.dubhe.biz.file.utils.DubheFileUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * @description 日志 实现类 + * @date 2020-06-01 + */ +@Service +public class LogServiceImpl implements LogService { + + @Autowired + private LogConvert logConvert; + + @Autowired + private LogMapper logMapper; + + /** + * 分页查询日志 + * + * @param criteria 日志查询实体 + * @param page 分页实体 + * @return java.lang.Object 日志返回实例 + */ + @Override + public Object queryAll(LogQueryDTO criteria, Page page) { + IPage dicts = logMapper.selectPage(page, WrapperHelp.getWrapper(criteria)); + String status = "ERROR"; + if (status.equals(criteria.getLogType())) { + return PageUtil.toPage(dicts, logConvert::toDto); + } + return page; + } + + /** + * 查询日志列表 + * + * @param criteria 日志查询条件 + * @return java.util.List 日志返回实例 + */ + @Override + public List queryAll(LogQueryDTO criteria) { + return logMapper.selectList(WrapperHelp.getWrapper(criteria)); + } + + /** + * 分页查询日志 + * + * @param criteria 日志查询实体 + * @param page 分页实体 + * @return java.lang.Object 日志返回实例 + */ + @Override + public Object queryAllByUser(LogQueryDTO criteria, Page page) { + Page logs = logMapper.selectPage(page, WrapperHelp.getWrapper(criteria)); + return PageUtil.toPage(logs, logConvert::toDto); + } + + /** + * 根据id查询错误日志 + * + * @param id + * @return java.lang.Object + */ + @Override + public Object findByErrDetail(Long id) { + Log log = logMapper.selectById(id); + byte[] details = log.getExceptionDetail(); + return Dict.create().set("exception", new String(ObjectUtil.isNotNull(details) ? details : "".getBytes())); + } + + /** + * 日志信息导出 + * + * @param logs 日志导出列表 + * @param response + */ + @Override + public void download(List logs, HttpServletResponse response) throws IOException { + List> list = new ArrayList<>(); + for (Log log : logs) { + Map map = new LinkedHashMap<>(); + map.put("用户名", log.getUsername()); + map.put("IP", log.getRequestIp()); + map.put("描述", log.getDescription()); + map.put("浏览器", log.getBrowser()); + map.put("请求耗时/毫秒", log.getTime()); + map.put("异常详情", new String(ObjectUtil.isNotNull(log.getExceptionDetail()) ? log.getExceptionDetail() : "".getBytes())); + map.put("创建日期", log.getCreateTime()); + list.add(map); + } + DubheFileUtil.downloadExcel(list, response); + } + + /** + * 删除所有error日志 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public void delAllByError() { + logMapper.deleteByLogType("ERROR"); + } + + /** + * 删除所有info日志 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public void delAllByInfo() { + logMapper.deleteByLogType("INFO"); + } +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/service/impl/MailServiceImpl.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/impl/MailServiceImpl.java new file mode 100644 index 0000000..541408e --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/impl/MailServiceImpl.java @@ -0,0 +1,150 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.service.impl; + +import org.dubhe.admin.service.MailService; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.io.FileSystemResource; +import org.springframework.mail.SimpleMailMessage; +import org.springframework.mail.javamail.JavaMailSender; +import org.springframework.mail.javamail.MimeMessageHelper; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import javax.mail.MessagingException; +import javax.mail.internet.MimeMessage; +import java.io.File; + +/** + * @description 邮件服务 实现类 + * @date 2020-06-01 + */ +@Service +public class MailServiceImpl implements MailService { + + + @Value("${spring.mail.username}") + private String from; + + @Resource + private JavaMailSender mailSender; + + /** + * 简单文本邮件 + * + * @param to 接收者邮件 + * @param subject 邮件主题 + * @param contnet 邮件内容 + */ + @Override + public void sendSimpleMail(String to, String subject, String contnet) { + + SimpleMailMessage message = new SimpleMailMessage(); + message.setTo(to); + message.setSubject(subject); + message.setText(contnet); + message.setFrom(from); + + mailSender.send(message); + } + + /** + * HTML 文本邮件 + * + * @param to 接收者邮件 + * @param subject 邮件主题 + * @param contnet HTML内容 + * @throws MessagingException + */ + @Override + public void sendHtmlMail(String to, String subject, String contnet) throws MessagingException { + MimeMessage message = mailSender.createMimeMessage(); + + MimeMessageHelper helper = new MimeMessageHelper(message, true); + helper.setTo(to); + helper.setSubject(subject); + helper.setText(contnet, true); + helper.setFrom(from); + + mailSender.send(message); + } + + + /** + * 附件邮件 + * + * @param to 接收者邮件 + * @param subject 邮件主题 + * @param contnet HTML内容 + * @param filePath 附件路径 + * @throws MessagingException + */ + @Override + public void sendAttachmentsMail(String to, String subject, String contnet, + String filePath) throws MessagingException { + MimeMessage message = mailSender.createMimeMessage(); + + MimeMessageHelper helper = new MimeMessageHelper(message, true); + helper.setTo(to); + helper.setSubject(subject); + helper.setText(contnet, true); + helper.setFrom(from); + + FileSystemResource file = new FileSystemResource(new File(filePath)); + String fileName = file.getFilename(); + helper.addAttachment(fileName, file); + + mailSender.send(message); + } + + /** + * 图片邮件 + * + * @param to 接收者邮件 + * @param subject 邮件主题 + * @param content HTML内容 + * @param rscPath 图片路径 + * @param rscId 图片ID + */ + @Override + public void sendLinkResourceMail(String to, String subject, String content, + String rscPath, String rscId) { + MimeMessage message = mailSender.createMimeMessage(); + MimeMessageHelper helper = null; + + try { + + helper = new MimeMessageHelper(message, true); + helper.setTo(to); + helper.setSubject(subject); + helper.setText(content, true); + helper.setFrom(from); + + FileSystemResource res = new FileSystemResource(new File(rscPath)); + helper.addInline(rscId, res); + mailSender.send(message); + + } catch (MessagingException e) { + LogUtil.info(LogEnum.BIZ_SYS,"发送静态邮件失败: {}", e); + } + + } + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/service/impl/MenuServiceImpl.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/impl/MenuServiceImpl.java new file mode 100644 index 0000000..908ee3a --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/impl/MenuServiceImpl.java @@ -0,0 +1,437 @@ +/** + * Copyright 2019-2020 Zheng Jie + * + * Licensed 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 org.dubhe.admin.service.impl; + +import cn.hutool.core.util.ObjectUtil; +import cn.hutool.core.util.StrUtil; +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import org.dubhe.admin.dao.MenuMapper; +import org.dubhe.admin.domain.dto.ExtConfigDTO; +import org.dubhe.admin.domain.dto.MenuCreateDTO; +import org.dubhe.admin.domain.dto.MenuDTO; +import org.dubhe.admin.domain.dto.MenuQueryDTO; +import org.dubhe.admin.domain.dto.MenuUpdateDTO; +import org.dubhe.admin.domain.dto.RoleSmallDTO; +import org.dubhe.admin.domain.entity.Menu; +import org.dubhe.admin.domain.vo.MenuMetaVo; +import org.dubhe.admin.domain.vo.MenuVo; +import org.dubhe.admin.enums.MenuTypeEnum; +import org.dubhe.admin.service.MenuService; +import org.dubhe.admin.service.RoleService; +import org.dubhe.admin.service.convert.MenuConvert; +import org.dubhe.biz.base.enums.SwitchEnum; +import org.dubhe.biz.base.exception.BusinessException; +import org.dubhe.biz.base.utils.StringUtils; +import org.dubhe.biz.db.constant.PermissionConstant; +import org.dubhe.biz.db.utils.WrapperHelp; +import org.dubhe.biz.file.utils.DubheFileUtil; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * @description 菜单服务 实现类 + * @date 2020-06-01 + */ +@Service +public class MenuServiceImpl implements MenuService { + + @Autowired + private MenuMapper menuMapper; + + @Autowired + private MenuConvert menuConvert; + + @Autowired + private RoleService roleService; + + /** + * 按条件查询菜单列表 + * + * @param criteria 菜单请求实体 + * @return java.util.List 菜单返回实例 + */ + @Override + public List queryAll(MenuQueryDTO criteria) { + List menus = menuMapper.selectList(WrapperHelp.getWrapper(criteria)); + return menuConvert.toDto(menus); + } + + + /** + * 根据id查询菜单信息 + * + * @param id 菜单id + * @return org.dubhe.domain.dto.MenuDTO 菜单返回实例 + */ + @Override + public MenuDTO findById(long id) { + + Menu menu = menuMapper.selectOne( + new LambdaQueryWrapper().eq(Menu::getId, id).eq(Menu::getDeleted, + SwitchEnum.getBooleanValue(SwitchEnum.OFF.getValue())) + ); + return menuConvert.toDto(menu); + } + + /** + * 根据角色查询菜单列表 + * + * @param roles 角色 + * @return java.util.List 菜单返回实例 + */ + @Override + public List findByRoles(List roles) { + Set roleIds = roles.stream().map(RoleSmallDTO::getId).collect(Collectors.toSet()); + List menus = menuMapper.findByRolesIdInAndTypeNotOrderBySortAsc(roleIds, 2); + return menus.stream().map(menuConvert::toDto).collect(Collectors.toList()); + } + + /** + * 新增菜单 + * + * @param resources 菜单新增请求实体 + * @return org.dubhe.domain.dto.MenuDTO 菜单返回实例 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public MenuDTO create(MenuCreateDTO resources) { + if (StringUtils.isNotBlank(resources.getComponentName())) { + if (menuMapper.findByComponentName(resources.getComponentName()) != null) { + throw new BusinessException("路由名称已存在"); + } + } + if (MenuTypeEnum.LINK_TYPE.getValue().equals(resources.getType())) { + String http = "http://", https = "https://"; + if (!(resources.getPath().toLowerCase().startsWith(http) || resources.getPath().toLowerCase().startsWith(https))) { + throw new BusinessException("外链必须以http://或者https://开头"); + } + } + Menu menu = Menu.builder() + .component(resources.getComponent()) + .cache(resources.getCache()) + .componentName(resources.getComponentName()) + .hidden(resources.getHidden()) + .layout(resources.getLayout()) + .icon(resources.getIcon()) + .name(resources.getName()) + .path(resources.getPath()) + .pid(resources.getPid()) + .permission(resources.getPermission()) + .sort(resources.getSort()) + .type(resources.getType()) + .build(); + if(MenuTypeEnum.PAGE_TYPE.getValue().equals(resources.getType())){ + menu.setBackTo(resources.getBackTo()); + menu.setExtConfig(resources.getExtConfig()); + } + menuMapper.insert(menu); + //管理员新增默认权限 + roleService.tiedRoleMenu(PermissionConstant.ADMIN_ROLE_ID,menu.getId()); + + return menuConvert.toDto(menu); + } + + /** + * 修改菜单 + * + * @param resources 菜单修改请求实体 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public void update(MenuUpdateDTO resources) { + if (resources.getId().equals(resources.getPid())) { + throw new BusinessException("上级不能为自己"); + } + Menu menu = menuMapper.selectOne( + new LambdaQueryWrapper() + .eq(Menu::getId, resources.getId()) + .eq(Menu::getDeleted, SwitchEnum.getBooleanValue(SwitchEnum.OFF.getValue())) + ); + if (MenuTypeEnum.LINK_TYPE.getValue().equals(resources.getType())) { + String http = "http://", https = "https://"; + if (!(resources.getPath().toLowerCase().startsWith(http) || resources.getPath().toLowerCase().startsWith(https))) { + throw new BusinessException("外链必须以http://或者https://开头"); + } + } + + if (StringUtils.isNotBlank(resources.getComponentName())) { + Menu dbMenu = menuMapper.findByComponentName(resources.getComponentName()); + if (dbMenu != null && !dbMenu.getId().equals(menu.getId())) { + throw new BusinessException("路由名称已存在"); + } + } + menu.setName(resources.getName()); + menu.setComponent(resources.getComponent()); + menu.setPath(resources.getPath()); + menu.setIcon(resources.getIcon()); + menu.setType(resources.getType()); + menu.setLayout(resources.getLayout()); + menu.setPid(resources.getPid()); + menu.setSort(resources.getSort()); + menu.setCache(resources.getCache()); + menu.setHidden(resources.getHidden()); + menu.setComponentName(resources.getComponentName()); + menu.setPermission(resources.getPermission()); + if(MenuTypeEnum.PAGE_TYPE.getValue().equals(resources.getType())){ + ExtConfigDTO extConfigDTO = analyzeBackToValue(resources.getExtConfig()); + menu.setBackTo(Objects.isNull(extConfigDTO)?null:extConfigDTO.getBackTo()); + menu.setExtConfig(resources.getExtConfig()); + } + menuMapper.updateById(menu); + } + + + /** + * 解析扩展配置中 backTO 属性值 + * + * @param extConfig 扩展配置 + * @return ExtConfigDTO扩展配置 + */ + private ExtConfigDTO analyzeBackToValue(String extConfig){ + ExtConfigDTO dto = ExtConfigDTO.builder().build(); + try { + if(!Objects.isNull(extConfig)){ + dto = JSONObject.parseObject(extConfig, ExtConfigDTO.class); + } + }catch (Exception e){ + LogUtil.error(LogEnum.SYS_ERR,"analyzeBackToValue error, params:{} , error:{}",JSONObject.toJSONString(extConfig),e); + } + return dto; + } + + /** + * 查询可删除的菜单 + * + * @param menuList + * @param menuSet + * @return java.util.Set + */ + @Override + public Set getDeleteMenus(List menuList, Set menuSet) { + // 递归找出待删除的菜单 + for (Menu menu1 : menuList) { + menuSet.add(menu1); + List menus = menuMapper.findByPid(menu1.getId()); + if (menus != null && menus.size() != 0) { + getDeleteMenus(menus, menuSet); + } + } + return menuSet; + } + + /** + * 删除菜单 + * + * @param menuSet 删除菜单请求集合 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public void delete(Set menuSet) { + for (Menu menu : menuSet) { + roleService.untiedMenu(menu.getId()); + menuMapper.updateById( + Menu.builder() + .id(menu.getId()) + .deleted(SwitchEnum.getBooleanValue(SwitchEnum.ON.getValue())).build() + ); + } + } + + /** + * 获取菜单树 + * + * @param menus 菜单列表 + * @return java.lang.Object 菜单树结构列表 + */ + @Override + public Object getMenuTree(List menus) { + List> list = new LinkedList<>(); + menus.forEach(menu -> { + if (menu != null) { + List menuList = menuMapper.findByPid(menu.getId()); + Map map = new HashMap<>(16); + map.put("id", menu.getId()); + map.put("label", menu.getName()); + if (menuList != null && menuList.size() != 0) { + map.put("children", getMenuTree(menuList)); + } + list.add(map); + } + } + ); + return list; + } + + /** + * 根据ID获取菜单列表 + * + * @param pid id + * @return java.util.List 菜单返回列表 + */ + @Override + public List findByPid(long pid) { + return menuMapper.findByPid(pid); + } + + + /** + * 构建菜单树 + * + * @param menuDtos 菜单请求实体 + * @return java.util.Map 菜单树结构 + */ + @Override + public Map buildTree(List menuDtos) { + List trees = new ArrayList<>(); + Set ids = new HashSet<>(); + for (MenuDTO menuDTO : menuDtos) { + if (menuDTO.getPid() == 0) { + trees.add(menuDTO); + } + for (MenuDTO it : menuDtos) { + if (it.getPid().equals(menuDTO.getId())) { + if (menuDTO.getChildren() == null) { + menuDTO.setChildren(new ArrayList<>()); + } + menuDTO.getChildren().add(it); + ids.add(it.getId()); + } + } + } + Map map = new HashMap<>(2); + if (trees.size() == 0) { + trees = menuDtos.stream().filter(s -> !ids.contains(s.getId())).collect(Collectors.toList()); + } + // MenuTree 不分页,结构保持一致 + Map page = new HashMap<>(2); + page.put("current", 1); + page.put("size", menuDtos.size()); + page.put("total", menuDtos.size()); + + map.put("result", trees); + map.put("page", page); + + return map; + } + + + /** + * 构建菜单树 + * + * @param menuDtos 菜单请求实体 + * @return java.util.List 菜单树返回实例 + */ + @Override + public List buildMenus(List menuDtos) { + List list = new LinkedList<>(); + menuDtos.forEach(menuDTO -> { + if (menuDTO != null) { + List menuDtoList = menuDTO.getChildren(); + MenuVo menuVo = new MenuVo(); + menuVo.setName(ObjectUtil.isNotEmpty(menuDTO.getComponentName()) ? menuDTO.getComponentName() : menuDTO.getName()); + // 一级目录需要加斜杠,不然会报警告 + menuVo.setPath(menuDTO.getPid() == 0 ? "/" + menuDTO.getPath() : menuDTO.getPath()); + menuVo.setHidden(menuDTO.getHidden()); + // 如果不是外链 + if (MenuTypeEnum.LINK_TYPE.getValue().compareTo(menuDTO.getType()) != 0) { + if (menuDTO.getPid() == 0) { + menuVo.setComponent(StrUtil.isEmpty(menuDTO.getComponent()) ? "Layout" : menuDTO.getComponent()); + } else if (!StrUtil.isEmpty(menuDTO.getComponent())) { + menuVo.setComponent(menuDTO.getComponent()); + } + } + menuVo.setMeta(new MenuMetaVo(menuDTO.getName(), menuDTO.getIcon(), menuDTO.getLayout(), !menuDTO.getCache())); + if (menuDtoList != null && menuDtoList.size() != 0) { + menuVo.setChildren(buildMenus(menuDtoList)); + // 处理是一级菜单并且没有子菜单的情况 + } else if (menuDTO.getPid() == 0) { + MenuVo menuVo1 = new MenuVo(); + menuVo1.setMeta(menuVo.getMeta()); + // 非外链 + if (MenuTypeEnum.LINK_TYPE.getValue().compareTo(menuDTO.getType()) != 0) { + menuVo1.setPath(menuVo.getPath()); + menuVo1.setName(menuVo.getName()); + menuVo1.setComponent(menuVo.getComponent()); + } else { + menuVo1.setPath(menuDTO.getPath()); + } + menuVo.setName(null); + menuVo.setMeta(null); + menuVo.setComponent("Layout"); + List list1 = new ArrayList<>(); + list1.add(menuVo1); + menuVo.setChildren(list1); + } + list.add(menuVo); + } + } + ); + return list; + } + + + /** + * 获取菜单 + * + * @param id 菜单id + * @return org.dubhe.domain.entity.Menu 菜单返回实例 + */ + @Override + public Menu findOne(Long id) { + Menu menu = menuMapper.selectById(id); + return menu; + } + + + /** + * 导出菜单 + * + * @param menuDtos 菜单列表 + * @param response + */ + @Override + public void download(List menuDtos, HttpServletResponse response) throws IOException { + List> list = new ArrayList<>(); + for (MenuDTO menuDTO : menuDtos) { + Map map = new LinkedHashMap<>(); + map.put("菜单名称", menuDTO.getName()); + map.put("菜单类型", MenuTypeEnum.getEnumValue(menuDTO.getType()).getDesc()); + map.put("权限标识", menuDTO.getPermission()); + map.put("菜单可见", menuDTO.getHidden() ? "否" : "是"); + map.put("是否缓存", menuDTO.getCache() ? "是" : "否"); + map.put("创建日期", menuDTO.getCreateTime()); + list.add(map); + } + DubheFileUtil.downloadExcel(list, response); + } +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/service/impl/PermissionServiceImpl.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/impl/PermissionServiceImpl.java new file mode 100644 index 0000000..a1bb2e0 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/impl/PermissionServiceImpl.java @@ -0,0 +1,216 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.service.impl; + +import cn.hutool.core.collection.CollUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import org.dubhe.admin.dao.AuthCodeMapper; +import org.dubhe.admin.dao.PermissionMapper; +import org.dubhe.admin.domain.dto.PermissionCreateDTO; +import org.dubhe.admin.domain.dto.PermissionDeleteDTO; +import org.dubhe.admin.domain.dto.PermissionQueryDTO; +import org.dubhe.admin.domain.dto.PermissionUpdateDTO; +import org.dubhe.admin.domain.entity.Permission; +import org.dubhe.admin.domain.vo.PermissionVO; +import org.dubhe.admin.service.PermissionService; +import org.dubhe.admin.service.convert.PermissionConvert; +import org.dubhe.biz.base.context.UserContext; +import org.dubhe.biz.base.exception.BusinessException; +import org.dubhe.biz.base.service.UserContextService; +import org.dubhe.biz.base.utils.StringUtils; +import org.springframework.beans.BeanUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.*; +import java.util.stream.Collectors; + +/** + * @description 操作权限服务实现类 + * @date 2021-04-28 + */ +@Service +public class PermissionServiceImpl extends ServiceImpl implements PermissionService { + + @Autowired + private PermissionMapper permissionMapper; + + @Autowired + private UserContextService userContextService; + + @Autowired + private PermissionConvert permissionConvert; + + @Autowired + private AuthCodeMapper authCodeMapper; + + /** + * + * 获取权限列表 + * @param pid 权限父id + * @return java.util.List 权限列表 + */ + @Override + public List findByPid(long pid) { + return permissionMapper.findByPid(pid); + } + + /** + * 获取权限树 + * + * @param permissions 权限列表 + * @return Object 权限树列表结构 + */ + @Override + public Object getPermissionTree(List permissions) { + List> list = new LinkedList<>(); + permissions.forEach(permission -> { + if (permission != null) { + List authList = permissionMapper.findByPid(permission.getId()); + Map map = new HashMap<>(16); + map.put("id", permission.getId()); + map.put("permission", permission.getPermission()); + map.put("label", permission.getName()); + if (CollUtil.isNotEmpty(authList)) { + map.put("children", getPermissionTree(authList)); + } + list.add(map); + } + } + ); + return list; + } + + /** + * 获取权限列表 + * + * @param permissionQueryDTO 权限查询DTO + * @return Map + */ + @Override + public Map queryAll(PermissionQueryDTO permissionQueryDTO) { + LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(); + if (StringUtils.isNotEmpty(permissionQueryDTO.getKeyword())) { + queryWrapper.and(x -> x.like(Permission::getName, permissionQueryDTO.getKeyword()).or().like(Permission::getPermission, permissionQueryDTO.getKeyword())); + } + queryWrapper.orderByDesc(Permission::getCreateTime); + List permissions = permissionMapper.selectList(queryWrapper); + return buildTree(permissionConvert.toDto(permissions)); + } + + private Map buildTree(List permissions) { + List trees = new ArrayList<>(); + Set ids = new HashSet<>(); + for (PermissionVO permissionVO : permissions) { + if (permissionVO.getPid() == 0) { + trees.add(permissionVO); + } + for (PermissionVO vo : permissions) { + if (vo.getPid().equals(permissionVO.getId())) { + if (CollUtil.isEmpty(permissionVO.getChildren())) { + permissionVO.setChildren(new ArrayList<>()); + } + permissionVO.getChildren().add(vo); + ids.add(vo.getId()); + } + } + + } + + Map map = new HashMap<>(2); + if (trees.size() == 0) { + permissions.stream().filter(x -> !ids.contains(x.getId())).collect(Collectors.toList()); + } + + Map page = new HashMap<>(3); + page.put("current", 1); + page.put("size", permissions.size()); + page.put("total", permissions.size()); + + map.put("result", trees); + map.put("page", page); + return map; + } + + /** + * 新增权限 + * + * @param permissionCreateDTO 新增权限DTO + */ + @Override + public void create(PermissionCreateDTO permissionCreateDTO) { + UserContext curUser = userContextService.getCurUser(); + List permissions = new ArrayList<>(); + for (Permission resource : permissionCreateDTO.getPermissions()) { + if (permissionMapper.findByName(resource.getName()) != null) { + throw new BusinessException("权限名称已存在"); + } + + Permission permission = new Permission(); + permission.setPid(permissionCreateDTO.getPid()) + .setName(resource.getName()) + .setPermission(resource.getPermission()) + .setCreateUserId(curUser.getId()); + permissions.add(permission); + } + saveBatch(permissions); + } + + /** + * 修改权限 + * + * @param permissionUpdateDTO 修改权限DTO + */ + @Override + public void update(PermissionUpdateDTO permissionUpdateDTO) { + UserContext curUser = userContextService.getCurUser(); + Permission permission = new Permission(); + BeanUtils.copyProperties(permissionUpdateDTO, permission); + for (Permission per : permissionUpdateDTO.getPermissions()) { + permission.setName(per.getName()); + permission.setPermission(per.getPermission()); + permission.setUpdateUserId(curUser.getId()); + permissionMapper.updateById(permission); + } + } + + /** + * 删除权限 + * + * @param permissionDeleteDTO 删除权限DTO + */ + @Override + public void delete(PermissionDeleteDTO permissionDeleteDTO) { + Set ids = new HashSet<>(); + List permissions = permissionMapper.selectList(new LambdaQueryWrapper().in(Permission::getId, permissionDeleteDTO.getIds())); + if (CollUtil.isNotEmpty(permissions)) { + for (Permission permission : permissions) { + if (permission.getPid() == 0) { + List permissionList = permissionMapper.findByPid(permission.getId()); + permissionList.forEach(x -> { + ids.add(x.getId()); + }); + } + ids.add(permission.getId()); + } + } + //解绑权限组权限 + authCodeMapper.untiedByPermissionId(ids); + permissionMapper.deleteBatchIds(ids); + } +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/service/impl/RecycleTaskServiceImpl.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/impl/RecycleTaskServiceImpl.java new file mode 100644 index 0000000..c6d3acd --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/impl/RecycleTaskServiceImpl.java @@ -0,0 +1,475 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.service.impl; + +import cn.hutool.core.collection.CollectionUtil; +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.util.RandomUtil; +import cn.hutool.core.util.StrUtil; +import cn.hutool.http.HttpStatus; +import com.alibaba.fastjson.JSON; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.dubhe.admin.service.RecycleTaskService; +import org.dubhe.biz.base.constant.MagicNumConstant; +import org.dubhe.biz.base.constant.ResponseCode; +import org.dubhe.biz.base.context.UserContext; +import org.dubhe.biz.base.exception.BusinessException; +import org.dubhe.biz.base.service.UserContextService; +import org.dubhe.biz.base.vo.DataResponseBody; +import org.dubhe.biz.db.utils.PageUtil; +import org.dubhe.biz.file.api.FileStoreApi; +import org.dubhe.biz.file.api.impl.ShellFileStoreApiImpl; +import org.dubhe.biz.file.utils.IOUtil; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.dubhe.biz.permission.base.BaseService; +import org.dubhe.recycle.config.RecycleConfig; +import org.dubhe.recycle.dao.RecycleDetailMapper; +import org.dubhe.recycle.dao.RecycleMapper; +import org.dubhe.recycle.domain.dto.RecycleCreateDTO; +import org.dubhe.recycle.domain.dto.RecycleTaskQueryDTO; +import org.dubhe.recycle.domain.entity.Recycle; +import org.dubhe.recycle.domain.entity.RecycleDetail; +import org.dubhe.recycle.enums.RecycleStatusEnum; +import org.dubhe.recycle.enums.RecycleTypeEnum; +import org.dubhe.recycle.service.RecycleService; +import org.dubhe.recycle.utils.RecycleTool; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.cloud.context.config.annotation.RefreshScope; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; +import org.springframework.web.client.RestTemplate; + +import javax.annotation.Resource; +import java.io.BufferedReader; +import java.io.File; +import java.io.InputStreamReader; +import java.util.Arrays; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.Objects; + + +/** + * @description 垃圾回收 + * @date 2021-01-20 + */ +@Service +@RefreshScope +public class RecycleTaskServiceImpl implements RecycleTaskService { + + @Autowired + private RecycleMapper recycleMapper; + + @Autowired + private RecycleDetailMapper recycleDetailMapper; + + @Autowired + private UserContextService userContextService; + + @Resource(name = "hostFileStoreApiImpl") + private FileStoreApi fileStoreApi; + + @Value("${storage.file-store}") + private String ip; + + @Value("${data.server.userName}") + private String userName; + + /** + * 资源回收单次执行任务数量限制(默认10000) + */ + @Value("${recycle.task.execute-limits:10000}") + private String taskExecuteLimits; + /** + * 资源无效文件临时存放目录(默认/tmp/tmp_) + */ + @Value("${recycle.file-tmp-path.invalid:/tmp/tmp_}") + private String invalidFileTmpPath; + /** + * 资源无效文件临时存放目录(默认/tmp/empty_) + */ + @Value("${recycle.file-tmp-path.recycle:/tmp/empty_}") + private String recycleFileTmpPath; + + @Autowired + private RecycleConfig recycleConfig; + + @Autowired + private RecycleService recycleService; + + @Autowired + private RecycleTool recycleTool; + + @Autowired + private RestTemplate restTemplate; + + /** + * 查询回收任务列表 + * + * @param recycleTaskQueryDTO 查询任务列表条件 + * @return Map 可回收任务列表 + */ + @Override + public Map getRecycleTasks(RecycleTaskQueryDTO recycleTaskQueryDTO) { + //获取当前用户信息 + Long curUserId = userContextService.getCurUserId(); + Page page = recycleTaskQueryDTO.toPage(); + LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper(); + queryWrapper.in(CollectionUtil.isNotEmpty(recycleTaskQueryDTO.getRecycleTaskIdList()), Recycle::getId, recycleTaskQueryDTO.getRecycleTaskIdList()); + queryWrapper.eq(recycleTaskQueryDTO.getRecycleStatus() != null, Recycle::getRecycleStatus, recycleTaskQueryDTO.getRecycleStatus()); + queryWrapper.eq(recycleTaskQueryDTO.getRecycleModel() != null, Recycle::getRecycleModule, recycleTaskQueryDTO.getRecycleModel()); + if (!BaseService.isAdmin()) { + queryWrapper.eq(Recycle::getCreateUserId, curUserId); + } + queryWrapper.last(" ORDER BY recycle_delay_date DESC,update_time DESC "); + List recycleList = recycleMapper.selectPage(page, queryWrapper).getRecords(); + return PageUtil.toPage(page, recycleList); + } + + /** + * 获取垃圾回收任务列表 + * 资源回收单次执行任务数量限制(默认10000) + * @return List 垃圾回收任务列表 + */ + @Override + public List getRecycleTaskList() { + List recycleTaskList = recycleMapper.selectList(new LambdaQueryWrapper() + .in(Recycle::getRecycleStatus, Arrays.asList(RecycleStatusEnum.PENDING.getCode(), RecycleStatusEnum.FAILED.getCode())) + .le(Recycle::getRecycleDelayDate, DateUtil.format(new Date(), "yyyy-MM-dd")) + .last(" limit ".concat(taskExecuteLimits)) + ); + return recycleTaskList; + } + + /** + * 执行回收任务(单个) + * @param recycle 回收实体类 + * @param userId 当前操作用户 + */ + @Override + public void recycleTask(Recycle recycle, long userId) { + if (StrUtil.isNotEmpty(recycle.getRecycleCustom())) { + // 自定义回收 + customRecycle(recycle, userId, RecycleTool.BIZ_RECYCLE); + } else { + // 默认回收0 + defaultRecycle(recycle, userId); + } + } + + /** + * 获取任务详情 + * @param recycleId 回收任务ID + * @return List + */ + private List getDetail(long recycleId) { + return recycleDetailMapper.selectList(new LambdaQueryWrapper() + .eq(RecycleDetail::getRecycleId, recycleId) + ); + } + + /** + * 自定义回收远程调用 + * + * @param recycle 回收任务 + * @param userId 用户ID + * @param biz 模块业务 + */ + private void customRecycle(Recycle recycle, long userId, String biz) { + recycle.setUpdateUserId(userId); + RecycleCreateDTO recycleCreateDTO = RecycleCreateDTO.recycleTaskCreateDTO(recycle); + recycleCreateDTO.setDetailList(getDetail(recycle.getId())); + // 远程调用 + String url = RecycleTool.getCallUrl(recycleCreateDTO.getRecycleModule(), biz); + String token = recycleTool.generateToken(); + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + headers.add(RecycleTool.RECYCLE_TOKEN, token); + HttpEntity entity = new HttpEntity<>(JSON.toJSONString(recycleCreateDTO), headers); + ResponseEntity responseEntity = null; + try { + responseEntity = restTemplate.postForEntity(url, entity, DataResponseBody.class); + } catch (Exception e) { + LogUtil.error(LogEnum.BIZ_SYS, "RecycleTaskServiceImpl customRecycle error :{}", e); + throw new BusinessException(responseEntity.getStatusCodeValue(), "自定义回收【" + biz + "】远程调用失败!"); + } + if (HttpStatus.HTTP_OK != responseEntity.getStatusCodeValue()) { + throw new BusinessException(responseEntity.getStatusCodeValue(), "自定义回收【" + biz + "】远程调用失败!"); + } + DataResponseBody dataResponseBody = responseEntity.getBody(); + if (!dataResponseBody.succeed()) { + throw new BusinessException(dataResponseBody.getCode(), dataResponseBody.getMsg()); + } + } + + /** + * 默认回收 + * (无统一事务操作) + * + * @param recycle 回收任务 + * @param userId 用户ID + */ + private void defaultRecycle(Recycle recycle, long userId) { + try { + List detailList = getDetail(recycle.getId()); + recycleService.updateRecycle(recycle, RecycleStatusEnum.DOING, null, userId); + for (RecycleDetail detail : detailList) { + if (Objects.equals(RecycleTypeEnum.FILE.getCode(), detail.getRecycleType())) { + // 文件回收 + if (!defaultRecycleFile(detail, userId)) { + recycleService.updateRecycle(recycle, RecycleStatusEnum.FAILED, "文件回收失败!" + detail.getId(), userId); + return; + } + } else { + // 其他资源(数据库资源)回收 + if (!defaultRecycleOthers(detail, userId)) { + recycleService.updateRecycle(recycle, RecycleStatusEnum.FAILED, "不支持非文件资源默认回收方式!" + detail.getId(), userId); + return; + } + } + } + recycleService.updateRecycle(recycle, RecycleStatusEnum.SUCCEEDED, null, userId); + } catch (Exception e) { + LogUtil.error(LogEnum.GARBAGE_RECYCLE, "默认回收失败!{}", e); + recycleService.updateRecycle(recycle, RecycleStatusEnum.FAILED, e.getMessage(), userId); + } + } + + + /** + * 默认方式文件回收 + * @param detail 回收任务详情 + * @param userId 用户ID + * @return true 回收成功, false 回收失败 + */ + private boolean defaultRecycleFile(RecycleDetail detail, long userId) { + if (RecycleStatusEnum.SUCCEEDED.getCode().equals(detail.getRecycleStatus())) { + // 已经删除成功,无需再执行 + return true; + } + String errMsg = deleteFileByCMD(detail.getRecycleCondition(), detail.getId().toString()); + recycleService.updateRecycleDetail(detail, + StrUtil.isEmpty(errMsg) ? RecycleStatusEnum.SUCCEEDED : RecycleStatusEnum.FAILED, + errMsg, + userId + ); + return StrUtil.isEmpty(errMsg); + } + + /** + * 默认方式回收其他资源(暂不支持) + * @param detail 回收任务详情 + * @param userId 用户ID + * @return false 回收失败 + */ + private boolean defaultRecycleOthers(RecycleDetail detail, long userId) { + LogUtil.warn(LogEnum.GARBAGE_RECYCLE, "recycle task id:{} is not support", detail.getId()); + recycleService.updateRecycleDetail(detail, RecycleStatusEnum.FAILED, "不支持非文件资源默认回收方式!", userId); + return false; + } + + + /** + * 实时删除临时目录完整路径无效文件 + * + * @param sourcePath 删除路径 + */ + @Override + public void delTempInvalidResources(String sourcePath) { + if (!BaseService.isAdmin(userContextService.getCurUser())) { + throw new BusinessException(ResponseCode.UNAUTHORIZED, "不支持普通用户操作"); + } + String resMsg = deleteFileByCMD(sourcePath, RandomUtil.randomString(MagicNumConstant.TWO)); + if (StrUtil.isNotEmpty(resMsg)) { + throw new BusinessException(ResponseCode.ERROR, resMsg); + } + } + + /** + * 回收天枢一站式平台中的无效文件资源 + * 处理方式:获取到回收任务表中的无效文件路径,通过linux命令进行具体删除 + * 文件路径必须满足格式如:/nfs/当前系统环境/具体删除的文件或文件夹(至少三层目录) + * @param recycleConditionPath 文件回收绝对路径 + * @param randomPath emptyDir目录补偿位置 + * @return String 回收任务失败返回的失败信息 + */ + private String deleteFileByCMD(String recycleConditionPath, String randomPath) { + String sourcePath = fileStoreApi.formatPath(recycleConditionPath); + //判断该路径是否存在文件或文件夹 + String nfsBucket = fileStoreApi.formatPath(fileStoreApi.getRootDir() + fileStoreApi.getBucket() + File.separator); + sourcePath = sourcePath.endsWith(File.separator) ? sourcePath : sourcePath + File.separator; + try { + //校验回收文件是否存在以及回收文件必须至少在当前环境目录下还有一层目录,如:/nfs/dubhe-test/xxxx/ + if (sourcePath.startsWith(nfsBucket) + && sourcePath.length() > nfsBucket.length()) { + if (!fileStoreApi.fileOrDirIsExist(sourcePath)) { + // 文件不存在,即认为已删除成功 + return null; + } + String emptyDir = recycleFileTmpPath + randomPath + File.separator; + LogUtil.debug(LogEnum.GARBAGE_RECYCLE, "recycle task sourcePath:{},emptyDir:{}", sourcePath, emptyDir); + Process process = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", String.format(ShellFileStoreApiImpl.DEL_COMMAND, userName, ip, emptyDir, emptyDir, sourcePath, emptyDir, sourcePath)}); + return processRecycle(process); + } else { + LogUtil.error(LogEnum.GARBAGE_RECYCLE, "file recycle is failed! sourcePath:{}", sourcePath); + return "文件资源回收失败! sourcePath:" + sourcePath; + } + } catch (Exception e) { + LogUtil.error(LogEnum.GARBAGE_RECYCLE, "file recycle is failed! Exception:{}", e); + return "文件资源回收失败! sourcePath:" + sourcePath + " Exception:" + e.getMessage(); + } + } + + /** + * 执行服务器命令 + * + * @param process Process对象 + * @return null 成功执行,其他:异常结束信息 + */ + private String processRecycle(Process process) { + InputStreamReader stream = new InputStreamReader(process.getErrorStream()); + BufferedReader reader = new BufferedReader(stream); + StringBuilder errMessage = new StringBuilder(); + try { + while (reader.read() != MagicNumConstant.NEGATIVE_ONE) { + errMessage.append(reader.readLine()); + } + int status = process.waitFor(); + if (status == 0) { + // 成功 + return null; + } else { + // 失败 + LogUtil.info(LogEnum.GARBAGE_RECYCLE, "recycleSourceIsOk is failure,errorMsg:{},processStatus:{}", errMessage.toString(), status); + return errMessage.length() > 0 ? errMessage.toString() : "文件删除失败!"; + } + } catch (Exception e) { + LogUtil.error(LogEnum.GARBAGE_RECYCLE, "recycleSourceIsOk is failure: {} ", e); + return e.getMessage(); + } finally { + IOUtil.close(reader, stream); + } + } + + /** + * 立即执行回收任务 + * + * @param taskId 回收任务ID + */ + @Override + public void recycleTaskResources(long taskId) { + //根据taskId查询回收任务 + Recycle recycle = getRecycleTask(taskId, Arrays.asList(RecycleStatusEnum.PENDING.getCode(), RecycleStatusEnum.FAILED.getCode())); + //执行回收任务 + recycleTask(recycle, recycle.getUpdateUserId()); + } + + /** + * 获取任务并校验 + * 更新修改人ID为当前操作人 + * + * @param taskId 回收任务ID + * @param statusEnumList 回收状态 + * @return Recycle + */ + private Recycle getRecycleTask(long taskId, List statusEnumList) { + //根据taskId查询回收任务 + Recycle recycle = recycleMapper.selectOne(new LambdaQueryWrapper() + .eq(Recycle::getId, taskId) + .in(CollectionUtil.isNotEmpty(statusEnumList), Recycle::getRecycleStatus, statusEnumList)); + if (recycle == null) { + throw new BusinessException("未查询到回收任务"); + } + UserContext curUser = userContextService.getCurUser(); + //只有创建该任务用户或管理员有权限实时执行回收任务 + if (!recycle.getCreateUserId().equals(curUser.getId()) && !BaseService.isAdmin(curUser)) { + throw new BusinessException("没有权限操作"); + } + recycle.setUpdateUserId(curUser.getId()); + return recycle; + } + + + /** + * 还原回收任务 + * + * @param taskId 回收任务ID + */ + @Override + public void restore(long taskId) { + //根据taskId查询回收任务 + Recycle recycle = getRecycleTask(taskId, Arrays.asList(RecycleStatusEnum.PENDING.getCode(), RecycleStatusEnum.FAILED.getCode())); + if (StrUtil.isEmpty(recycle.getRestoreCustom())) { + throw new BusinessException("仅支持自定义还原!"); + } else { + long userId = recycle.getUpdateUserId(); + // 自定义还原 + customRecycle(recycle, userId, RecycleTool.BIZ_RESTORE); + } + } + + /** + * 根据路径回收无效文件 + * + * @param sourcePath 文件路径 + */ + @Override + public void deleteInvalidResourcesByCMD(String sourcePath) { + //判断该路径是否存在文件或文件夹 + if (!fileStoreApi.fileOrDirIsExist(sourcePath)) { + return; + } + File file = new File(sourcePath); + File[] files = file.listFiles(); + if (files != null && files.length != 0) { + for (File f : files) { + //获取文件夹命名(userId) + String fileName = f.getName(); + if (!f.isDirectory()) { + continue; + } + File[] director = f.listFiles(); + if (director != null && director.length != 0) { + for (File directory : director) { + //获取文件夹命名(时间戳+4位随机数) + String directoryName = directory.getName(); + //如果文件上传时长大于最大有效时间,则删除 + if ((System.currentTimeMillis() - directory.lastModified()) >= recycleConfig.getFileValid() * MagicNumConstant.SIXTY * MagicNumConstant.SIXTY * MagicNumConstant.ONE_THOUSAND) { + try { + String delRealPath = fileStoreApi.formatPath(sourcePath + File.separator + fileName + File.separator + directoryName); + delRealPath = delRealPath.endsWith(File.separator) ? delRealPath : delRealPath + File.separator; + String emptyDir = invalidFileTmpPath + directoryName + File.separator; + Process process = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", String.format(ShellFileStoreApiImpl.DEL_COMMAND, userName, ip, emptyDir, emptyDir, delRealPath, emptyDir, delRealPath)}); + Integer deleteStatus = process.waitFor(); + LogUtil.info(LogEnum.GARBAGE_RECYCLE, "recycle resources path:{},recycle status:{}", delRealPath, deleteStatus); + } catch (Exception e) { + LogUtil.error(LogEnum.GARBAGE_RECYCLE, "recycle invalid resources error:{}", e); + } + } + } + } + } + } + } +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/service/impl/ResourceSpecsServiceImpl.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/impl/ResourceSpecsServiceImpl.java new file mode 100644 index 0000000..b3ad0da --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/impl/ResourceSpecsServiceImpl.java @@ -0,0 +1,209 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.apache.commons.collections4.CollectionUtils; +import org.dubhe.admin.dao.ResourceSpecsMapper; +import org.dubhe.admin.domain.dto.ResourceSpecsCreateDTO; +import org.dubhe.admin.domain.dto.ResourceSpecsDeleteDTO; +import org.dubhe.admin.domain.dto.ResourceSpecsQueryDTO; +import org.dubhe.admin.domain.dto.ResourceSpecsUpdateDTO; +import org.dubhe.admin.domain.entity.ResourceSpecs; +import org.dubhe.admin.domain.vo.ResourceSpecsQueryVO; +import org.dubhe.admin.service.ResourceSpecsService; +import org.dubhe.biz.base.constant.StringConstant; +import org.dubhe.biz.base.context.UserContext; +import org.dubhe.biz.base.dto.QueryResourceSpecsDTO; +import org.dubhe.biz.base.exception.BusinessException; +import org.dubhe.biz.base.service.UserContextService; +import org.dubhe.biz.base.utils.StringUtils; +import org.dubhe.biz.base.vo.QueryResourceSpecsVO; +import org.dubhe.biz.db.utils.PageUtil; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.springframework.beans.BeanUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.*; +import java.util.stream.Collectors; + +/** + * @description CPU, GPU, 内存等资源规格管理 + * @date 2021-05-27 + */ +@Service +public class ResourceSpecsServiceImpl implements ResourceSpecsService { + + @Autowired + private ResourceSpecsMapper resourceSpecsMapper; + + @Autowired + private UserContextService userContextService; + + /** + * 查询资源规格 + * @param resourceSpecsQueryDTO 查询资源规格请求实体 + * @return List resourceSpecs 资源规格列表 + */ + @Override + public Map getResourceSpecs(ResourceSpecsQueryDTO resourceSpecsQueryDTO) { + Page page = resourceSpecsQueryDTO.toPage(); + //排序字段 + String sort = null == resourceSpecsQueryDTO.getSort() ? StringConstant.CREATE_TIME_SQL : resourceSpecsQueryDTO.getSort(); + QueryWrapper queryResourceSpecsWrapper = new QueryWrapper<>(); + queryResourceSpecsWrapper.like(resourceSpecsQueryDTO.getSpecsName() != null, "specs_name", resourceSpecsQueryDTO.getSpecsName()) + .eq(resourceSpecsQueryDTO.getResourcesPoolType() != null, "resources_pool_type", resourceSpecsQueryDTO.getResourcesPoolType()) + .eq(resourceSpecsQueryDTO.getModule() != null, "module", resourceSpecsQueryDTO.getModule()); + if (StringConstant.SORT_ASC.equals(resourceSpecsQueryDTO.getOrder())) { + queryResourceSpecsWrapper.orderByAsc(StringUtils.humpToLine(sort)); + } else { + queryResourceSpecsWrapper.orderByDesc(StringUtils.humpToLine(sort)); + } + Page pageResourceSpecsResult = resourceSpecsMapper.selectPage(page, queryResourceSpecsWrapper); + //结果集处理 + //查询结果数 + page.setTotal(pageResourceSpecsResult.getTotal()); + List resourceSpecs = pageResourceSpecsResult.getRecords(); + List resourceSpecsQueryVOS = new ArrayList<>(); + if (CollectionUtils.isNotEmpty(resourceSpecs)) { + resourceSpecsQueryVOS = resourceSpecs.stream().map(x -> { + ResourceSpecsQueryVO resourceSpecsQueryVO = new ResourceSpecsQueryVO(); + BeanUtils.copyProperties(x, resourceSpecsQueryVO); + return resourceSpecsQueryVO; + }).collect(Collectors.toList()); + } + return PageUtil.toPage(page, resourceSpecsQueryVOS); + } + + /** + * 新增资源规格 + * @param resourceSpecsCreateDTO 新增资源规格实体 + * @return List 新增资源规格id + */ + @Override + @Transactional(rollbackFor = Exception.class) + public List create(ResourceSpecsCreateDTO resourceSpecsCreateDTO) { + UserContext curUser = userContextService.getCurUser(); + //规格名称校验 + QueryWrapper specsWrapper = new QueryWrapper<>(); + specsWrapper.eq("specs_name", resourceSpecsCreateDTO.getSpecsName()).eq("module", resourceSpecsCreateDTO.getModule()); + if (resourceSpecsMapper.selectCount(specsWrapper) > 0) { + LogUtil.error(LogEnum.SYS_ERR, "The module: {} resourceSpecs name ({}) already exists", resourceSpecsCreateDTO.getModule(), resourceSpecsCreateDTO.getSpecsName()); + throw new BusinessException("规格名称已存在"); + } + ResourceSpecs resourceSpecs = new ResourceSpecs(); + BeanUtils.copyProperties(resourceSpecsCreateDTO, resourceSpecs); + resourceSpecs.setCreateUserId(curUser.getId()); + if (resourceSpecsCreateDTO.getGpuNum() > 0) { + resourceSpecs.setResourcesPoolType(true); + } + try { + resourceSpecsMapper.insert(resourceSpecs); + } catch (Exception e) { + LogUtil.error(LogEnum.SYS_ERR, "The user {} saved the ResourceSpecs parameters ResourceSpecsCreateDTO: {} was not successful. Failure reason :{}", curUser, resourceSpecsCreateDTO, e); + throw new BusinessException("内部错误"); + } + return Collections.singletonList(resourceSpecs.getId()); + } + + /** + * 修改资源规格 + * @param resourceSpecsUpdateDTO 修改资源规格实体 + * @return List 修改资源规格id + */ + @Override + @Transactional(rollbackFor = Exception.class) + public List update(ResourceSpecsUpdateDTO resourceSpecsUpdateDTO) { + UserContext curUser = userContextService.getCurUser(); + ResourceSpecs resourceSpecs = new ResourceSpecs(); + resourceSpecs.setId(resourceSpecsUpdateDTO.getId()).setUpdateUserId(curUser.getId()); + if (resourceSpecsUpdateDTO.getSpecsName() != null) { + //规格名称校验 + QueryWrapper specsWrapper = new QueryWrapper<>(); + specsWrapper.eq("specs_name", resourceSpecsUpdateDTO.getSpecsName()).eq("module", resourceSpecsUpdateDTO.getModule()).ne("id", resourceSpecsUpdateDTO.getId()); + if (resourceSpecsMapper.selectCount(specsWrapper) > 0) { + LogUtil.error(LogEnum.SYS_ERR, "The module: {} resourceSpecs name ({}) already exists", resourceSpecsUpdateDTO.getModule(), resourceSpecsUpdateDTO.getSpecsName()); + throw new BusinessException("规格名称已存在"); + } + resourceSpecs.setSpecsName(resourceSpecsUpdateDTO.getSpecsName()); + } + if (resourceSpecsUpdateDTO.getCpuNum() != null) { + resourceSpecs.setCpuNum(resourceSpecsUpdateDTO.getCpuNum()); + } + if (resourceSpecsUpdateDTO.getGpuNum() != null) { + resourceSpecs.setGpuNum(resourceSpecsUpdateDTO.getGpuNum()); + if (resourceSpecsUpdateDTO.getGpuNum() > 0) { + resourceSpecs.setResourcesPoolType(true); + } else { + resourceSpecs.setResourcesPoolType(false); + } + } + if (resourceSpecsUpdateDTO.getMemNum() != null) { + resourceSpecs.setMemNum(resourceSpecsUpdateDTO.getMemNum()); + } + if (resourceSpecsUpdateDTO.getWorkspaceRequest() != null) { + resourceSpecs.setWorkspaceRequest(resourceSpecsUpdateDTO.getWorkspaceRequest()); + } + try { + resourceSpecsMapper.updateById(resourceSpecs); + } catch (Exception e) { + LogUtil.error(LogEnum.SYS_ERR, "The user {} updated the ResourceSpecs parameters resourceSpecsUpdateDTO: {} was not successful. Failure reason :{}", curUser, resourceSpecsUpdateDTO, e); + throw new BusinessException("内部错误"); + } + return Collections.singletonList(resourceSpecs.getId()); + } + + /** + * 资源规格删除 + * @param resourceSpecsDeleteDTO 资源规格删除id集合 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public void delete(ResourceSpecsDeleteDTO resourceSpecsDeleteDTO) { + UserContext curUser = userContextService.getCurUser(); + Set idList = resourceSpecsDeleteDTO.getIds(); + try { + resourceSpecsMapper.deleteBatchIds(idList); + } catch (Exception e) { + LogUtil.error(LogEnum.SYS_ERR, "The user {} Deleted the ResourceSpecs parameters resourceSpecsDeleteDTO: {} was not successful. Failure reason :{}", curUser, resourceSpecsDeleteDTO, e); + throw new BusinessException("内部错误"); + } + } + + /** + * 查询资源规格 + * @param queryResourceSpecsDTO 查询资源规格请求实体 + * @return QueryResourceSpecsVO 资源规格返回结果实体类 + */ + @Override + public QueryResourceSpecsVO queryResourceSpecs(QueryResourceSpecsDTO queryResourceSpecsDTO) { + QueryWrapper queryResourceSpecsWrapper = new QueryWrapper<>(); + queryResourceSpecsWrapper.eq("specs_name", queryResourceSpecsDTO.getSpecsName()) + .eq("module", queryResourceSpecsDTO.getModule()); + ResourceSpecs resourceSpecs = resourceSpecsMapper.selectOne(queryResourceSpecsWrapper); + if (resourceSpecs == null) { + throw new BusinessException("资源规格不存在或已被删除"); + } + QueryResourceSpecsVO queryResourceSpecsVO = new QueryResourceSpecsVO(); + BeanUtils.copyProperties(resourceSpecs, queryResourceSpecsVO); + return queryResourceSpecsVO; + } +} \ No newline at end of file diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/service/impl/RoleServiceImpl.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/impl/RoleServiceImpl.java new file mode 100644 index 0000000..df3f277 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/impl/RoleServiceImpl.java @@ -0,0 +1,276 @@ +/** + * Copyright 2019-2020 Zheng Jie + * + * Licensed 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 org.dubhe.admin.service.impl; + +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import org.dubhe.admin.dao.RoleMapper; +import org.dubhe.admin.domain.dto.RoleCreateDTO; +import org.dubhe.admin.domain.dto.RoleDTO; +import org.dubhe.admin.domain.dto.RoleQueryDTO; +import org.dubhe.admin.domain.dto.RoleSmallDTO; +import org.dubhe.admin.domain.dto.RoleUpdateDTO; +import org.dubhe.admin.domain.entity.Menu; +import org.dubhe.admin.domain.entity.Role; +import org.dubhe.admin.service.RoleService; +import org.dubhe.admin.service.convert.RoleConvert; +import org.dubhe.admin.service.convert.RoleSmallConvert; +import org.dubhe.biz.base.constant.UserConstant; +import org.dubhe.biz.base.enums.BaseErrorCodeEnum; +import org.dubhe.biz.base.enums.SwitchEnum; +import org.dubhe.biz.base.exception.BusinessException; +import org.dubhe.biz.db.utils.PageUtil; +import org.dubhe.biz.db.utils.WrapperHelp; +import org.dubhe.biz.file.utils.DubheFileUtil; +import org.springframework.beans.BeanUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.CollectionUtils; + +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; + +/** + * @description 角色服务 实现类 + * @date 2020-06-01 + */ +@Service +public class RoleServiceImpl extends ServiceImpl implements RoleService { + + @Autowired + private RoleMapper roleMapper; + + @Autowired + private RoleConvert roleConvert; + + @Autowired + private RoleSmallConvert roleSmallConvert; + + /** + * 按条件查询角色信息 + * + * @param criteria 角色查询条件 + * @return java.util.List 角色信息返回实例 + */ + @Override + public List queryAllSmall(RoleQueryDTO criteria) { + return roleSmallConvert.toDto(roleMapper.selectList((WrapperHelp.getWrapper(criteria)))); + } + + + /** + * 按条件查询角色列表 + * + * @param criteria 角色查询条件 + * @return java.util.List 角色信息返回实例 + */ + @Override + public List queryAll(RoleQueryDTO criteria) { + return roleConvert.toDto(roleMapper.selectCollList(WrapperHelp.getWrapper(criteria))); + } + + /** + * 分页查询角色列表 + * + * @param criteria 角色查询条件 + * @param page 分页实体 + * @return java.lang.Object 角色信息返回实例 + */ + @Override + public Object queryAll(RoleQueryDTO criteria, Page page) { + IPage roles = roleMapper.selectCollPage(page, WrapperHelp.getWrapper(criteria)); + return PageUtil.toPage(roles, roleConvert::toDto); + } + + /** + * 根据ID查询角色信息 + * + * @param id id + * @return org.dubhe.domain.dto.RoleDTO 角色信息 + */ + @Override + public RoleDTO findById(long id) { + Role role = roleMapper.selectCollById(id); + return roleConvert.toDto(role); + } + + /** + * 新增角色 + * + * @param resources 角色新增请求实体 + * @return org.dubhe.domain.dto.RoleDTO 角色返回实例 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public RoleDTO create(RoleCreateDTO resources) { + if (!Objects.isNull(roleMapper.findByName(resources.getName()))) { + throw new BusinessException("角色名已存在"); + } + Role role = Role.builder().build(); + BeanUtils.copyProperties(resources, role); + roleMapper.insert(role); + //新创建角色分配默认的【概览】菜单 + roleMapper.tiedRoleMenu(role.getId(), 1L); + return roleConvert.toDto(role); + } + + + /** + * 修改角色 + * + * @param resources 角色修改请求实体 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public void update(RoleUpdateDTO resources) { + + Role roleTmp = roleMapper.findByName(resources.getName()); + if (!Objects.isNull(roleTmp) && !roleTmp.getId().equals(resources.getId())) { + throw new BusinessException("角色名已存在"); + } + + Role role = Role.builder().build(); + BeanUtils.copyProperties(resources, role); + roleMapper.updateById(role); + } + + + /** + * 修改角色菜单 + * + * @param resources 角色菜单请求实体 + * @param roleDTO 角色请求实体 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public void updateMenu(RoleUpdateDTO resources, RoleDTO roleDTO) { + Role role = roleConvert.toEntity(roleDTO); + role.setMenus(resources.getMenus()); + roleMapper.untiedRoleMenuByRoleId(role.getId()); + for (Menu menu : resources.getMenus()) { + roleMapper.tiedRoleMenu(role.getId(), menu.getId()); + } + } + + /** + * 删除角色菜单 + * + * @param id 角色id + */ + @Override + @Transactional(rollbackFor = Exception.class) + public void untiedMenu(Long id) { + roleMapper.untiedRoleMenuByMenuId(id); + } + + /** + * 批量删除角色 + * + * @param ids 角色ids + */ + @Override + @Transactional(rollbackFor = Exception.class) + public void delete(Set ids) { + + if (!CollectionUtils.isEmpty(ids)) { + // admin 角色和 register 角色不可删除 + if (ids.contains(Long.valueOf(UserConstant.ADMIN_ROLE_ID)) || + ids.contains(Long.valueOf(UserConstant.REGISTER_ROLE_ID))) { + throw new BusinessException(BaseErrorCodeEnum.SYSTEM_ROLE_CANNOT_DELETE); + } + + for (Long id : ids) { + roleMapper.untiedUserRoleByRoleId(id); + roleMapper.untiedRoleMenuByRoleId(id); + roleMapper.updateById( + Role.builder() + .id(id) + .deleted(SwitchEnum.getBooleanValue(SwitchEnum.ON.getValue())).build() + ); + } + + } + + + } + + /** + * 导出角色信息 + * + * @param roles 角色列表 + * @param response + */ + @Override + public void download(List roles, HttpServletResponse response) throws IOException { + List> list = new ArrayList<>(); + for (RoleDTO role : roles) { + Map map = new LinkedHashMap<>(); + map.put("角色名称", role.getName()); + map.put("默认权限", role.getPermission()); + map.put("描述", role.getRemark()); + map.put("创建日期", role.getCreateTime()); + list.add(map); + } + DubheFileUtil.downloadExcel(list, response); + } + + + /** + * 根据用户ID获取角色信息 + * + * @param userId 用户ID + * @return java.util.List 角色列表 + */ + @Override + public List getRoleByUserId(Long userId) { + List list = roleMapper.findRolesByUserId(userId); + return roleSmallConvert.toDto(list); + } + + + /** + * 获取角色列表 + * + * @param userId 用户ID + * @param teamId 团队ID + * @return java.util.List 角色列表 + */ + @Override + public List getRoleByUserIdAndTeamId(Long userId, Long teamId) { + List list = roleMapper.findByUserIdAndTeamId(userId, teamId); + return roleSmallConvert.toDto(list); + } + + /** + * 新增角色菜单 + * + * @param roleId 角色ID + * @param menuId 菜单ID + */ + @Override + public void tiedRoleMenu(Long roleId, Long menuId) { + roleMapper.tiedRoleMenu(roleId, menuId); + } + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/service/impl/TeamServiceImpl.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/impl/TeamServiceImpl.java new file mode 100644 index 0000000..9b6f85d --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/impl/TeamServiceImpl.java @@ -0,0 +1,169 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.service.impl; + +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.dubhe.admin.dao.TeamMapper; +import org.dubhe.admin.domain.dto.TeamCreateDTO; +import org.dubhe.biz.base.dto.TeamDTO; +import org.dubhe.admin.domain.dto.TeamQueryDTO; +import org.dubhe.admin.domain.dto.TeamUpdateDTO; +import org.dubhe.admin.domain.entity.Team; +import org.dubhe.admin.service.TeamService; +import org.dubhe.admin.service.convert.TeamConvert; +import org.dubhe.biz.db.utils.PageUtil; +import org.dubhe.biz.db.utils.WrapperHelp; +import org.dubhe.biz.file.utils.DubheFileUtil; +import org.springframework.beans.BeanUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.*; + +/** + * @description 团队服务 实现类 + * @date 2020-06-01 + */ +@Service +public class TeamServiceImpl implements TeamService { + + @Autowired + private TeamMapper teamMapper; + + @Autowired + private TeamConvert teamConvert; + + + /** + * 获取团队列表 + * + * @param criteria 查询团队列表条件 + * @return java.util.List 团队列表条件 + */ + @Override + public List queryAll(TeamQueryDTO criteria) { + return teamConvert.toDto(teamMapper.selectList(WrapperHelp.getWrapper(criteria))); + } + + + /** + * 分页查询团队列表 + * + * @param criteria 查询请求条件 + * @param page 分页实体 + * @return java.lang.Object 团队列表 + */ + @Override + public Object queryAll(TeamQueryDTO criteria, Page page) { + IPage teamList = teamMapper.selectPage(page, WrapperHelp.getWrapper(criteria)); + return PageUtil.toPage(teamList, teamConvert::toDto); + } + + + /** + * 查询团队列表 + * + * @param page 分页请求实体 + * @return java.util.List 团队列表 + */ + @Override + public List queryAll(Page page) { + IPage teamList = teamMapper.selectPage(page, null); + return teamConvert.toDto(teamList.getRecords()); + } + + /** + * 根据ID插叙团队信息 + * + * @param id id + * @return org.dubhe.domain.dto.TeamDTO 团队返回实例 + */ + @Override + public TeamDTO findById(Long id) { + Team team = teamMapper.selectCollById(id); + return teamConvert.toDto(team); + } + + + /** + * 新增团队信息 + * + * @param resources 团队新增请求实体 + * @return org.dubhe.domain.dto.TeamDTO 团队返回实例 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public TeamDTO create(TeamCreateDTO resources) { + Team team = Team.builder().build(); + BeanUtils.copyProperties(resources, team); + teamMapper.insert(team); + return teamConvert.toDto(team); + } + + + /** + * 修改团队 + * + * @param resources 团队修改请求实体 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public void update(TeamUpdateDTO resources) { + Team team = Team.builder().build(); + BeanUtils.copyProperties(resources, team); + teamMapper.updateById(team); + } + + /** + * 团队删除 + * + * @param teamDtos 团队删除列表 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public void delete(Set teamDtos) { + for (TeamDTO teamDto : teamDtos) { + teamMapper.deleteById(teamDto.getId()); + } + } + + /** + * 团队信息导出 + * + * @param teamDtos 团队列表 + * @param response 导出http响应 + */ + @Override + public void download(List teamDtos, HttpServletResponse response) throws IOException { + List> list = new ArrayList<>(); + for (TeamDTO teamDTO : teamDtos) { + Map map = new LinkedHashMap<>(); + map.put("名称", teamDTO.getName()); + map.put("状态", teamDTO.getEnabled() ? "启用" : "停用"); + map.put("创建日期", teamDTO.getCreateTime()); + list.add(map); + } + DubheFileUtil.downloadExcel(list, response); + } + + +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/service/impl/UserGroupServiceImpl.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/impl/UserGroupServiceImpl.java new file mode 100644 index 0000000..8c68435 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/impl/UserGroupServiceImpl.java @@ -0,0 +1,292 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.service.impl; + +import cn.hutool.core.collection.CollUtil; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.dubhe.admin.dao.UserGroupMapper; +import org.dubhe.admin.dao.UserRoleMapper; +import org.dubhe.admin.domain.dto.*; +import org.dubhe.admin.domain.entity.Group; +import org.dubhe.admin.domain.entity.User; +import org.dubhe.admin.domain.entity.UserRole; +import org.dubhe.admin.domain.vo.UserGroupVO; +import org.dubhe.admin.service.UserGroupService; +import org.dubhe.admin.service.UserService; +import org.dubhe.biz.base.constant.StringConstant; +import org.dubhe.biz.base.context.UserContext; +import org.dubhe.biz.base.exception.BusinessException; +import org.dubhe.biz.base.service.UserContextService; +import org.dubhe.biz.base.utils.ReflectionUtils; +import org.dubhe.biz.base.utils.StringUtils; +import org.dubhe.biz.db.utils.PageUtil; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.springframework.beans.BeanUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.dao.DuplicateKeyException; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.*; +import java.util.stream.Collectors; + +/** + * @description 用户组服务实现类 + * @date 2021-05-06 + */ +@Service +public class UserGroupServiceImpl implements UserGroupService { + + @Autowired + private UserGroupMapper userGroupMapper; + + @Autowired + private UserContextService userContextService; + + @Autowired + private UserService userService; + + @Autowired + private UserRoleMapper userRoleMapper; + + public final static List FIELD_NAMES; + + static { + FIELD_NAMES = ReflectionUtils.getFieldNames(UserGroupVO.class); + } + + + /** + * 分页查询用户组列表 + * + * @param queryDTO 查询实体DTO + * @return Map 用户组及分页信息 + */ + @Override + public Map queryAll(UserGroupQueryDTO queryDTO) { + + Page page = queryDTO.toPage(); + QueryWrapper queryWrapper = new QueryWrapper<>(); + + if (StringUtils.isNotEmpty(queryDTO.getKeyword())) { + queryWrapper.and(x -> x.eq("id", queryDTO.getKeyword()).or().like("name", queryDTO.getKeyword())); + } + + //排序 + IPage groupList; + try { + if (queryDTO.getSort() != null && FIELD_NAMES.contains(queryDTO.getSort())) { + if (StringConstant.SORT_ASC.equalsIgnoreCase(queryDTO.getOrder())) { + queryWrapper.orderByAsc(StringUtils.humpToLine(queryDTO.getSort())); + } else { + queryWrapper.orderByDesc(StringUtils.humpToLine(queryDTO.getSort())); + } + } else { + queryWrapper.orderByDesc(StringConstant.ID); + } + groupList = userGroupMapper.selectPage(page, queryWrapper); + } catch (Exception e) { + LogUtil.error(LogEnum.IMAGE, "query image list display exception {}", e); + throw new BusinessException("查询用户组列表展示异常"); + } + List userGroupResult = groupList.getRecords().stream().map(x -> { + UserGroupVO userGroupVO = new UserGroupVO(); + BeanUtils.copyProperties(x, userGroupVO); + return userGroupVO; + }).collect(Collectors.toList()); + return PageUtil.toPage(page, userGroupResult); + } + + /** + * 新增用户组 + * + * @param groupCreateDTO 新增用户组实体DTO + */ + @Override + @Transactional(rollbackFor = Exception.class) + public Group create(UserGroupDTO groupCreateDTO) { + //获取当前用户 + UserContext curUser = userContextService.getCurUser(); + Group userGroup = new Group(); + try { + BeanUtils.copyProperties(groupCreateDTO, userGroup); + userGroup.setCreateUserId(curUser.getId()); + userGroupMapper.insert(userGroup); + } catch (DuplicateKeyException e) { + throw new BusinessException("用户组名称不能重复"); + } + return userGroup; + } + + /** + * 修改用户组信息 + * + * @param groupUpdateDTO 修改用户组实体DTO + */ + @Override + @Transactional(rollbackFor = Exception.class) + public void update(UserGroupDTO groupUpdateDTO) { + //获取当前用户 + UserContext curUser = userContextService.getCurUser(); + + Group userGroup = new Group(); + BeanUtils.copyProperties(groupUpdateDTO, userGroup); + userGroup.setUpdateUserId(curUser.getId()); + userGroupMapper.updateById(userGroup); + + } + + /** + * 删除用户组 + * + * @param ids 用户组ids + */ + @Override + @Transactional(rollbackFor = Exception.class) + public void delete(Set ids) { + for (Long id : ids) { + userGroupMapper.delUserByGroupId(id); + userGroupMapper.delUserGroupByGroupId(id); + } + } + + /** + * 修改用户组成员 + * + * @param userGroupUpdDTO 新增组用户DTO实体 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public void updUserWithGroup(UserGroupUpdDTO userGroupUpdDTO) { + if (userGroupUpdDTO.getGroupId() != null) { + userGroupMapper.delUserByGroupId(userGroupUpdDTO.getGroupId()); + for (Long userId : userGroupUpdDTO.getUserIds()) { + userGroupMapper.addUserWithGroup(userGroupUpdDTO.getGroupId(), userId); + } + } + } + + /** + * 删除用户组成员 + * + * @param userGroupDelDTO 删除用户组成员 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public void delUserWithGroup(UserGroupUpdDTO userGroupDelDTO) { + for (Long userId : userGroupDelDTO.getUserIds()) { + userGroupMapper.delUserWithGroup(userGroupDelDTO.getGroupId(), userId); + } + } + + + /** + * 获取没有归属组的用户 + * + * @return List 没有归属组的用户 + */ + @Override + public List findUserWithOutGroup() { + return userGroupMapper.findUserWithOutGroup(); + } + + + /** + * 获取用户组成员信息 + * + * @param groupId 用户组id + * @return List 用户列表 + */ + @Override + public List queryUserByGroupId(Long groupId) { + return userGroupMapper.queryUserByGroupId(groupId); + } + + /** + * 批量修改用户组成员的状态 + * + * @param userStateUpdateDTO 实体DTO + */ + @Override + @Transactional(rollbackFor = Exception.class) + public void updateUserState(UserStateUpdateDTO userStateUpdateDTO) { + //获取用户组的成员id + List userList = userGroupMapper.queryUserByGroupId(userStateUpdateDTO.getGroupId()); + Set ids = new HashSet<>(); + if (CollUtil.isNotEmpty(userList)) { + for (User user : userList) { + ids.add(user.getId()); + } + } + LambdaUpdateWrapper updateWrapper = new LambdaUpdateWrapper<>(); + updateWrapper.in(User::getId, ids); + updateWrapper.set(User::getEnabled, userStateUpdateDTO.isEnabled()); + userService.update(updateWrapper); + } + + /** + * 批量删除用户组用户 + * + * @param userGroupUpdDTO 批量删除用户组用户DTO + */ + @Override + public void delUser(UserGroupUpdDTO userGroupUpdDTO) { + //获取用户组的成员id + List userList = userGroupMapper.queryUserByGroupId(userGroupUpdDTO.getGroupId()); + userGroupMapper.delUserByGroupId(userGroupUpdDTO.getGroupId()); + Set ids = new HashSet<>(); + if (CollUtil.isNotEmpty(userList)) { + for (User user : userList) { + ids.add(user.getId()); + } + } + userService.delete(ids); + } + + /** + * 批量修改用户组用户的角色 + * + * @param userRoleUpdateDTO + */ + @Override + @Transactional(rollbackFor = Exception.class) + public void updateUserRole(UserRoleUpdateDTO userRoleUpdateDTO) { + //获取用户组的成员id + List userList = userGroupMapper.queryUserByGroupId(userRoleUpdateDTO.getGroupId()); + List userRoleList = new ArrayList<>(); + Set ids = new HashSet<>(); + if (CollUtil.isNotEmpty(userList)) { + for (User user : userList) { + ids.add(user.getId()); + for (Long roleId : userRoleUpdateDTO.getRoleIds()) { + UserRole userRole = new UserRole(); + userRole.setUserId(user.getId()); + userRole.setRoleId(roleId); + userRoleList.add(userRole); + } + } + } + //清空当前用户 + userRoleMapper.deleteByUserId(ids); + //添加用户的新角色 + userRoleMapper.insertBatchs(userRoleList); + } +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/service/impl/UserServiceImpl.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/impl/UserServiceImpl.java new file mode 100644 index 0000000..5fbe9d3 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/service/impl/UserServiceImpl.java @@ -0,0 +1,907 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.service.impl; + +import cn.hutool.core.util.ObjectUtil; +import cn.hutool.core.util.StrUtil; +import cn.hutool.crypto.asymmetric.KeyType; +import cn.hutool.crypto.asymmetric.RSA; +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import org.dubhe.admin.client.AuthServiceClient; +import org.dubhe.admin.dao.*; +import org.dubhe.admin.domain.dto.*; +import org.dubhe.admin.domain.entity.Role; +import org.dubhe.admin.domain.entity.User; +import org.dubhe.admin.domain.entity.UserAvatar; +import org.dubhe.admin.domain.entity.UserRole; +import org.dubhe.admin.domain.vo.EmailVo; +import org.dubhe.admin.domain.vo.UserVO; +import org.dubhe.admin.enums.UserMailCodeEnum; +import org.dubhe.admin.event.EmailEventPublisher; +import org.dubhe.admin.service.UserService; +import org.dubhe.admin.service.convert.TeamConvert; +import org.dubhe.admin.service.convert.UserConvert; +import org.dubhe.biz.base.constant.AuthConst; +import org.dubhe.biz.base.constant.ResponseCode; +import org.dubhe.biz.base.constant.UserConstant; +import org.dubhe.biz.base.context.UserContext; +import org.dubhe.biz.base.dto.*; +import org.dubhe.biz.base.enums.BaseErrorCodeEnum; +import org.dubhe.biz.base.enums.SwitchEnum; +import org.dubhe.biz.base.exception.BusinessException; +import org.dubhe.biz.base.exception.CaptchaException; +import org.dubhe.biz.base.utils.DateUtil; +import org.dubhe.biz.base.utils.Md5Util; +import org.dubhe.biz.base.utils.RandomUtil; +import org.dubhe.biz.base.utils.RsaEncrypt; +import org.dubhe.biz.base.vo.DataResponseBody; +import org.dubhe.biz.dataresponse.factory.DataResponseFactory; +import org.dubhe.biz.db.utils.PageUtil; +import org.dubhe.biz.db.utils.WrapperHelp; +import org.dubhe.biz.file.utils.DubheFileUtil; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.dubhe.biz.permission.annotation.DataPermissionMethod; +import org.dubhe.biz.redis.utils.RedisUtils; +import org.dubhe.cloud.authconfig.dto.JwtUserDTO; +import org.dubhe.cloud.authconfig.factory.PasswordEncoderFactory; +import org.dubhe.cloud.authconfig.utils.JwtUtils; +import org.springframework.beans.BeanUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.cglib.beans.BeanMap; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.CollectionUtils; + +import javax.annotation.Resource; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.*; +import java.util.stream.Collectors; + +/** + * @description Demo服务接口实现类 + * @date 2020-11-26 + */ +@Service +public class UserServiceImpl extends ServiceImpl implements UserService { + + @Value("${rsa.private_key}") + private String privateKey; + + @Value("${initial_password}") + private String initialPassword; + + @Autowired + private UserMapper userMapper; + + + @Resource + private RoleMapper roleMapper; + + @Autowired + private MenuMapper menuMapper; + + @Autowired + private TeamMapper teamMapper; + + @Autowired + private UserConvert userConvert; + + @Autowired + private TeamConvert teamConvert; + + @Autowired + private UserAvatarMapper userAvatarMapper; + + + @Autowired + private RedisUtils redisUtils; + + @Autowired + private UserRoleMapper userRoleMapper; + + @Autowired + private EmailEventPublisher publisher; + + @Autowired + private AuthServiceClient authServiceClient; + + @Autowired + private PermissionMapper permissionMapper; + + /** + * 测试标识 true:允许debug false:拒绝debug + */ + @Value("${debug.flag}") + private Boolean debugFlag; + + private final String LOCK_SEND_CODE = "LOCK_SEND_CODE"; + + /** + * 分页查询用户列表 + * + * @param criteria 查询条件 + * @param page 分页请求实体 + * @return java.lang.Object 用户列表返回实例 + */ + @Override + public Object queryAll(UserQueryDTO criteria, Page page) { + if (criteria.getRoleId() == null) { + IPage users = userMapper.selectCollPage(page, WrapperHelp.getWrapper(criteria)); + return PageUtil.toPage(users, userConvert::toDto); + } else { + IPage users = userMapper.selectCollPageByRoleId(page, WrapperHelp.getWrapper(criteria), criteria.getRoleId()); + return PageUtil.toPage(users, userConvert::toDto); + } + } + + /** + * 查询用户列表 + * + * @param criteria 用户查询条件 + * @return java.util.List 用户列表返回实例 + */ + @Override + public List queryAll(UserQueryDTO criteria) { + List users = userMapper.selectCollList(WrapperHelp.getWrapper(criteria)); + return userConvert.toDto(users); + } + + /** + * 根据用户ID查询团队列表 + * + * @param userId 用户ID + * @return java.util.List 团队列表信息 + */ + @Override + public List queryTeams(Long userId) { + + User user = userMapper.selectOne( + new LambdaQueryWrapper() + .eq(User::getId, userId) + .eq(User::getDeleted, SwitchEnum.getBooleanValue(SwitchEnum.OFF.getValue())) + ); + List teamList = teamMapper.findByUserId(user.getId()); + return teamConvert.toDto(teamList); + } + + /** + * 根据ID获取用户信息 + * + * @param id id + * @return org.dubhe.domain.dto.UserDTO 用户信息返回实例 + */ + @Override + public UserDTO findById(long id) { + User user = userMapper.selectCollById(id); + return userConvert.toDto(user); + } + + + /** + * 新增用户 + * + * @param resources 用户新增实体 + * @return org.dubhe.domain.dto.UserDTO 用户信息返回实例 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public UserDTO create(UserCreateDTO resources) { + PasswordEncoder passwordEncoder = PasswordEncoderFactory.getPasswordEncoder(); + if (!Objects.isNull(userMapper.findByUsername(resources.getUsername()))) { + throw new BusinessException("用户名已存在"); + } + if (userMapper.findByEmail(resources.getEmail()) != null) { + throw new BusinessException("邮箱已存在"); + } + resources.setPassword(passwordEncoder.encode(initialPassword)); + + User user = User.builder().build(); + BeanUtils.copyProperties(resources, user); + + userMapper.insert(user); + for (Role role : resources.getRoles()) { + roleMapper.tiedUserRole(user.getId(), role.getId()); + } + + return userConvert.toDto(user); + } + + + /** + * 修改用户 + * + * @param resources 用户修改请求实例 + * @return org.dubhe.domain.dto.UserDTO 用户信息返回实例 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public UserDTO update(UserUpdateDTO resources) { + + //修改管理员信息校验 + checkIsAdmin(resources.getId()); + + User user = userMapper.selectCollById(resources.getId()); + User userTmp = userMapper.findByUsername(resources.getUsername()); + if (userTmp != null && !user.equals(userTmp)) { + throw new BusinessException("用户名已存在"); + } + userTmp = userMapper.findByEmail(resources.getEmail()); + if (userTmp != null && !user.equals(userTmp)) { + throw new BusinessException("邮箱已存在"); + } + roleMapper.untiedUserRoleByUserId(user.getId()); + for (Role role : resources.getRoles()) { + roleMapper.tiedUserRole(user.getId(), role.getId()); + } + user.setUsername(resources.getUsername()); + user.setEmail(resources.getEmail()); + user.setEnabled(resources.getEnabled()); + user.setRoles(resources.getRoles()); + user.setPhone(resources.getPhone()); + user.setNickName(resources.getNickName()); + user.setRemark(resources.getRemark()); + user.setSex(resources.getSex()); + userMapper.updateById(user); + return userConvert.toDto(user); + } + + + /** + * 批量删除用户信息 + * + * @param ids 用户ID列表 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public void delete(Set ids) { + if (!CollectionUtils.isEmpty(ids)) { + Long adminId = Long.valueOf(UserConstant.ADMIN_USER_ID); + if (ids.contains(adminId)) { + throw new BusinessException(BaseErrorCodeEnum.SYSTEM_USER_CANNOT_DELETE); + } + ids.forEach(id -> { + userMapper.updateById( + User.builder() + .id(id) + .deleted(SwitchEnum.getBooleanValue(SwitchEnum.ON.getValue())) + .build()); + }); + } + } + + + /** + * 根据用户名称获取用户信息 + * + * @param userName 用户名称 + * @return org.dubhe.domain.dto.UserDTO 用户信息返回实例 + */ + @Override + public UserDTO findByName(String userName) { + User user = userMapper.findByUsername(userName); + if (user == null) { + LogUtil.error(LogEnum.SYS_ERR, "UserServiceImpl findByName user is null"); + throw new BusinessException("user not found"); + } + UserDTO dto = new UserDTO(); + BeanUtils.copyProperties(user, dto); + List roles = roleMapper.findRolesByUserId(user.getId()); + if (!CollectionUtils.isEmpty(roles)) { + dto.setRoles(roles.stream().map(a -> { + SysRoleDTO sysRoleDTO = new SysRoleDTO(); + sysRoleDTO.setId(a.getId()); + sysRoleDTO.setName(a.getName()); + return sysRoleDTO; + }).collect(Collectors.toList())); + } + return dto; + + } + + + /** + * 修改用户个人中心信息 + * + * @param resources 个人用户信息修改请求实例 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public void updateCenter(UserCenterUpdateDTO resources) { + User user = userMapper.selectOne( + new LambdaQueryWrapper() + .eq(User::getId, resources.getId()) + .eq(User::getDeleted, SwitchEnum.getBooleanValue(SwitchEnum.OFF.getValue())) + ); + user.setNickName(resources.getNickName()); + user.setRemark(resources.getRemark()); + user.setPhone(resources.getPhone()); + user.setSex(resources.getSex()); + userMapper.updateById(user); + if (user.getUserAvatar() != null) { + if (user.getUserAvatar().getId() != null) { + userAvatarMapper.updateById(user.getUserAvatar()); + } else { + userAvatarMapper.insert(user.getUserAvatar()); + } + } + } + + + /** + * 修改用户密码 + * + * @param username 账号 + * @param pass 密码 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public void updatePass(String username, String pass) { + userMapper.updatePass(username, pass, new Date()); + } + + + /** + * 修改用户头像 + * + * @param realName 名称 + * @param path 头像路径 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public void updateAvatar(String realName, String path) { + User user = userMapper.findByUsername(JwtUtils.getCurUser().getUsername()); + UserAvatar userAvatar = user.getUserAvatar(); + UserAvatar newAvatar = new UserAvatar(userAvatar, realName, path, null); + + if (newAvatar.getId() != null) { + userAvatarMapper.updateById(newAvatar); + } else { + userAvatarMapper.insert(newAvatar); + } + user.setAvatarId(newAvatar.getId()); + user.setUserAvatar(newAvatar); + userMapper.updateById(user); + } + + /** + * 修改用户邮箱 + * + * @param username 用户名称 + * @param email 用户邮箱 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public void updateEmail(String username, String email) { + userMapper.updateEmail(username, email); + } + + + /** + * 用户信息导出 + * + * @param queryAll 用户信息列表 + * @param response 导出http响应 + */ + @Override + public void download(List queryAll, HttpServletResponse response) throws IOException { + List> list = new ArrayList<>(); + for (UserDTO userDTO : queryAll) { + Map map = new LinkedHashMap<>(); + map.put("用户名", userDTO.getUsername()); + map.put("邮箱", userDTO.getEmail()); + map.put("状态", userDTO.getEnabled() ? "启用" : "禁用"); + map.put("手机号码", userDTO.getPhone()); + map.put("最后修改密码的时间", userDTO.getLastPasswordResetTime()); + map.put("创建日期", userDTO.getCreateTime()); + list.add(map); + } + DubheFileUtil.downloadExcel(list, response); + } + + + /** + * 查询用户ID权限 + * + * @param id 用户ID + * @return java.util.Set 权限列表 + */ + @Override + public Set queryPermissionByUserId(Long id) { + return userMapper.queryPermissionByUserId(id); + } + + /** + * 用户注册信息 + * + * @param userRegisterDTO 用户注册请求实体 + * @return org.dubhe.base.DataResponseBody 注册返回结果集 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public DataResponseBody userRegister(UserRegisterDTO userRegisterDTO) { + PasswordEncoder passwordEncoder = PasswordEncoderFactory.getPasswordEncoder(); + //用户信息校验 + checkoutUserInfo(userRegisterDTO); + String encode = passwordEncoder.encode(RsaEncrypt.decrypt(userRegisterDTO.getPassword(), privateKey)); + try { + User newUser = User.builder() + .email(userRegisterDTO.getEmail()) + .enabled(true) + .nickName(userRegisterDTO.getNickName()) + .password(encode) + .phone(userRegisterDTO.getPhone()) + .sex(SwitchEnum.ON.getValue().compareTo(userRegisterDTO.getSex()) == 0 ? UserConstant.SEX_MEN : UserConstant.SEX_WOMEN) + .username(userRegisterDTO.getUsername()).build(); + + //新增用户注册信息 + userMapper.insert(newUser); + + //绑定用户默认权限 + userRoleMapper.insert(UserRole.builder().roleId((long) UserConstant.REGISTER_ROLE_ID).userId(newUser.getId()).build()); + + } catch (Exception e) { + LogUtil.error(LogEnum.SYS_ERR, "UserServiceImpl userRegister error , param:{} error:{}", JSONObject.toJSONString(userRegisterDTO), e); + throw new BusinessException(BaseErrorCodeEnum.ERROR_SYSTEM.getCode(), BaseErrorCodeEnum.ERROR_SYSTEM.getMsg()); + } + + return new DataResponseBody(); + } + + + /** + * 获取code通过发送邮件 + * + * @param userRegisterMailDTO 用户发送邮件请求实体 + * @return org.dubhe.base.DataResponseBody 发送邮件返回结果集 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public DataResponseBody getCodeBySentEmail(UserRegisterMailDTO userRegisterMailDTO) { + String email = userRegisterMailDTO.getEmail(); + + User dbUser = userMapper.selectOne(new LambdaQueryWrapper() + .eq(User::getEmail, email) + .eq(User::getDeleted, SwitchEnum.getBooleanValue(SwitchEnum.OFF.getValue())) + ); + //校验用户是否注册(type : 1 用户注册 2 修改邮箱 ) + Boolean isRegisterOrUpdate = UserMailCodeEnum.REGISTER_CODE.getValue().compareTo(userRegisterMailDTO.getType()) == 0 || + UserMailCodeEnum.MAIL_UPDATE_CODE.getValue().compareTo(userRegisterMailDTO.getType()) == 0; + if (!Objects.isNull(dbUser) && isRegisterOrUpdate) { + LogUtil.error(LogEnum.SYS_ERR, "UserServiceImpl dbUser already register , dbUser:{} ", JSONObject.toJSONString(dbUser)); + throw new BusinessException(BaseErrorCodeEnum.SYSTEM_USER_EMAIL_ALREADY_EXISTS.getCode(), + BaseErrorCodeEnum.SYSTEM_USER_EMAIL_ALREADY_EXISTS.getMsg()); + } + + + //限制邮箱发送次数 + limitSendEmail(email); + + try { + synchronized (LOCK_SEND_CODE) { + //产生随机的验证码 + String code = RandomUtil.randomCode(); + //异步发送邮件 + publisher.sentEmailEvent( + EmailDTO.builder() + .code(code) + .subject(UserMailCodeEnum.getEnumValue(userRegisterMailDTO.getType()).getDesc()) + .type(userRegisterMailDTO.getType()) + .receiverMailAddress(email).build()); + //redis存储邮箱验证信息 + redisUtils.hset( + getSendEmailCodeRedisKeyByType(userRegisterMailDTO.getType()).concat(email), + email, + EmailVo.builder().code(code).email(email).build(), + UserConstant.DATE_SECOND); + } + + } catch (Exception e) { + redisUtils.hdel(UserConstant.USER_EMAIL_REGISTER.concat(email), email); + LogUtil.error(LogEnum.SYS_ERR, "UserServiceImpl getCodeBySentEmail error , param:{} error:{}", email, e); + throw new BusinessException(BaseErrorCodeEnum.ERROR_SYSTEM.getCode(), BaseErrorCodeEnum.ERROR_SYSTEM.getMsg()); + } + return new DataResponseBody(); + } + + + /** + * 邮箱修改 + * + * @param userEmailUpdateDTO 修改邮箱请求实体 + * @return org.dubhe.base.DataResponseBody 修改邮箱返回结果集 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public DataResponseBody resetEmail(UserEmailUpdateDTO userEmailUpdateDTO) { + //校验邮箱信息 + User dbUser = checkoutEmailInfoByReset(userEmailUpdateDTO); + + try { + //修改邮箱信息 + userMapper.updateById( + User.builder() + .id(dbUser.getId()) + .email(userEmailUpdateDTO.getEmail()).build()); + } catch (Exception e) { + LogUtil.error(LogEnum.SYS_ERR, "UserServiceImpl update email error , email:{} error:{}", userEmailUpdateDTO.getEmail(), e); + throw new BusinessException(BaseErrorCodeEnum.ERROR_SYSTEM.getCode(), + BaseErrorCodeEnum.ERROR_SYSTEM.getMsg()); + } + + return new DataResponseBody(); + } + + + /** + * 获取用户信息 + * + * @return java.util.Map 用户信息结果集 + */ + @Override + public Map userinfo() { + JwtUserDTO curUser = JwtUtils.getCurUser(); + if (Objects.isNull(curUser)) { + throw new BusinessException(BaseErrorCodeEnum.SYSTEM_USER_IS_NOT_EXISTS.getCode() + , BaseErrorCodeEnum.SYSTEM_USER_IS_NOT_EXISTS.getMsg()); + } + + //查询用户是否是管理员 + List userRoles = userRoleMapper.selectList( + new LambdaQueryWrapper() + .eq(UserRole::getUserId, curUser.getCurUserId()) + .eq(UserRole::getRoleId, Long.parseLong(String.valueOf(UserConstant.ADMIN_ROLE_ID))) + ); + UserVO vo = UserVO.builder() + .email(curUser.getUser().getEmail()) + .password(Md5Util.createMd5(Md5Util.createMd5(curUser.getUsername()).concat(initialPassword))) + .username(curUser.getUsername()) + .is_staff(!CollectionUtils.isEmpty(userRoles) ? true : false).build(); + + return BeanMap.create(vo); + } + + + /** + * 密码重置接口 + * + * @param userResetPasswordDTO 密码修改请求参数 + * @return org.dubhe.base.DataResponseBody 密码修改结果集 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public DataResponseBody resetPassword(UserResetPasswordDTO userResetPasswordDTO) { + PasswordEncoder passwordEncoder = PasswordEncoderFactory.getPasswordEncoder(); + //校验 邮箱地址 和 验证码 + checkoutEmailAndCode(userResetPasswordDTO.getCode(), userResetPasswordDTO.getEmail(), UserConstant.USER_EMAIL_RESET_PASSWORD); + + User dbUser = userMapper.selectOne(new LambdaQueryWrapper() + .eq(User::getEmail, userResetPasswordDTO.getEmail()) + .eq(User::getDeleted, SwitchEnum.getBooleanValue(SwitchEnum.OFF.getValue())) + ); + if (Objects.isNull(dbUser)) { + throw new BusinessException(BaseErrorCodeEnum.SYSTEM_USER_EMAIL_NOT_EXISTS.getCode() + , BaseErrorCodeEnum.SYSTEM_USER_EMAIL_NOT_EXISTS.getMsg()); + } + + //加密密码 + String encode = passwordEncoder.encode(RsaEncrypt.decrypt(userResetPasswordDTO.getPassword(), privateKey)); + try { + userMapper.updateById(User.builder().id(dbUser.getId()).password(encode).build()); + } catch (Exception e) { + throw new BusinessException(BaseErrorCodeEnum.ERROR_SYSTEM.getCode() + , BaseErrorCodeEnum.ERROR_SYSTEM.getMsg()); + } + return new DataResponseBody(); + } + + + /** + * 登录 + * + * @param authUserDTO 登录请求实体 + */ + @Override + @DataPermissionMethod + public DataResponseBody> login(AuthUserDTO authUserDTO) { + if (!debugFlag) { + validateCode(authUserDTO.getCode(), authUserDTO.getUuid()); + } + String password = null; + try { + RSA rsa = new RSA(privateKey, null); + password = new String(rsa.decrypt(authUserDTO.getPassword(), KeyType.PrivateKey)); + } catch (Exception e) { + LogUtil.error(LogEnum.BIZ_SYS, "rsa 密钥解析失败, originPassword:{} , 密钥:{},异常:{}", authUserDTO.getPassword(), KeyType.PrivateKey, e); + throw new BusinessException("请输入正确密码"); + } + + Map params = new HashMap<>(); + params.put("grant_type", "password"); + params.put("username", authUserDTO.getUsername()); + params.put("client_id", AuthConst.CLIENT_ID); + params.put("client_secret", AuthConst.CLIENT_SECRET); + params.put("password", password); + params.put("scope", "all"); + DataResponseBody restResult = authServiceClient.postAccessToken(params); + Map authInfo = new HashMap<>(3); + if (ResponseCode.SUCCESS.compareTo(restResult.getCode()) == 0 && !Objects.isNull(restResult.getData())) { + Oauth2TokenDTO userDto = restResult.getData(); + UserDTO user = findByName(authUserDTO.getUsername()); + Set permissions = this.queryPermissionByUserId(user.getId()); + // 返回 token 与 用户信息 + authInfo.put("token", userDto.getTokenHead() + userDto.getToken()); + authInfo.put("user", user); + authInfo.put("permissions", permissions); + } + return DataResponseFactory.success(authInfo); + } + + + /** + * 退出登录 + * + * @param accessToken token + */ + @Override + public DataResponseBody logout(String accessToken) { + return authServiceClient.logout(accessToken); + } + + /** + * 根据用户昵称获取用户信息 + * + * @param nickName 用户昵称 + * @return org.dubhe.domain.dto.UserDTO 用户信息DTO + */ + @Override + public List findByNickName(String nickName) { + List users = userMapper.selectList(new LambdaQueryWrapper() + .like(User::getNickName, nickName == null ? StrUtil.EMPTY : nickName)); + + return userConvert.toDto(users); + } + + /** + * 根据用户id批量查询用户信息 + * + * @param ids 用户id集合 + * @return org.dubhe.domain.dto.UserDTO 用户信息DTO集合 + */ + @Override + public List getUserList(List ids) { + List users = userMapper.selectBatchIds(ids); + return userConvert.toDto(users); + } + + + /** + * 校验验证码 + * + * @param loginCaptcha 验证码参数 + * @param uuid 验证码redis-key + */ + private void validateCode(String loginCaptcha, String uuid) { + // 验证码未输入 + if (loginCaptcha == null || "".equals(loginCaptcha)) { + throw new CaptchaException("验证码错误"); + } + String sessionCaptcha = (String) redisUtils.get(uuid); + + if (!loginCaptcha.equalsIgnoreCase(sessionCaptcha)) { + throw new CaptchaException("验证码错误"); + } + + } + + /** + * 修改邮箱校验邮箱信息 + * + * @param userEmailUpdateDTO 邮箱修改参数校验实体 + */ + private User checkoutEmailInfoByReset(UserEmailUpdateDTO userEmailUpdateDTO) { + PasswordEncoder passwordEncoder = PasswordEncoderFactory.getPasswordEncoder(); + String email = userEmailUpdateDTO.getEmail(); + //管理员信息校验 + checkIsAdmin(userEmailUpdateDTO.getUserId()); + + //校验用户信息是否存在 + User dbUser = userMapper.selectCollById(userEmailUpdateDTO.getUserId()); + if (ObjectUtil.isNull(dbUser)) { + LogUtil.error(LogEnum.SYS_ERR, "UserServiceImpl dbUser is null , userId:{}", userEmailUpdateDTO.getUserId()); + throw new BusinessException(BaseErrorCodeEnum.SYSTEM_USER_IS_NOT_EXISTS.getCode(), + BaseErrorCodeEnum.SYSTEM_USER_IS_NOT_EXISTS.getMsg()); + } + //校验密码是否正确 + String decryptPassword = RsaEncrypt.decrypt(userEmailUpdateDTO.getPassword(), privateKey); + if (!passwordEncoder.matches(decryptPassword, dbUser.getPassword())) { + LogUtil.error(LogEnum.SYS_ERR, "UserServiceImpl password error , webPassword:{}, dbPassword:{} ", + userEmailUpdateDTO.getPassword(), dbUser.getPassword()); + throw new BusinessException(BaseErrorCodeEnum.SYSTEM_USER_EMAIL_PASSWORD_ERROR.getCode(), + BaseErrorCodeEnum.SYSTEM_USER_EMAIL_PASSWORD_ERROR.getMsg()); + } + + //邮箱唯一性校验 + User user = userMapper.selectOne(new LambdaQueryWrapper() + .eq(User::getEmail, userEmailUpdateDTO.getEmail())); + if (!ObjectUtil.isNull(user)) { + LogUtil.error(LogEnum.SYS_ERR, "UserServiceImpl Email already exists , email:{} ", userEmailUpdateDTO.getEmail()); + throw new BusinessException(BaseErrorCodeEnum.SYSTEM_USER_EMAIL_ALREADY_EXISTS.getCode(), + BaseErrorCodeEnum.SYSTEM_USER_EMAIL_ALREADY_EXISTS.getMsg()); + } + + //校验 邮箱地址 和 验证码 + checkoutEmailAndCode(userEmailUpdateDTO.getCode(), email, UserConstant.USER_EMAIL_UPDATE); + + return dbUser; + } + + + /** + * 限制发送次数 + * + * @param receiverMailAddress 邮箱接受者地址 + */ + private void limitSendEmail(final String receiverMailAddress) { + double count = redisUtils.hincr(UserConstant.USER_EMAIL_LIMIT_COUNT.concat(receiverMailAddress), receiverMailAddress, 1); + if (count > UserConstant.COUNT_SENT_EMAIL) { + LogUtil.error(LogEnum.SYS_ERR, "Email verification code cannot exceed three times , error:{}", UserConstant.COUNT_SENT_EMAIL); + throw new BusinessException(BaseErrorCodeEnum.SYSTEM_USER_EMAIL_CODE_CANNOT_EXCEED_TIMES.getCode(), + BaseErrorCodeEnum.SYSTEM_USER_EMAIL_CODE_CANNOT_EXCEED_TIMES.getMsg()); + } else { + // 验证码次数凌晨清除 + String concat = UserConstant.USER_EMAIL_LIMIT_COUNT.concat(receiverMailAddress); + + Long secondsNextEarlyMorning = DateUtil.getSecondTime(); + + redisUtils.expire(concat, secondsNextEarlyMorning); + } + } + + + /** + * 用户信息校验 + * + * @param userRegisterDTO 用户信息校验实体 + */ + private void checkoutUserInfo(UserRegisterDTO userRegisterDTO) { + //账户唯一性校验 + User user = userMapper.selectOne(new LambdaQueryWrapper() + .eq(User::getUsername, userRegisterDTO.getUsername())); + if (!ObjectUtil.isNull(user)) { + LogUtil.error(LogEnum.SYS_ERR, "UserServiceImpl username already exists , username:{} ", userRegisterDTO.getUsername()); + throw new BusinessException(BaseErrorCodeEnum.SYSTEM_USERNAME_ALREADY_EXISTS.getCode(), + BaseErrorCodeEnum.SYSTEM_USERNAME_ALREADY_EXISTS.getMsg()); + } + //校验 邮箱地址 和 验证码 + checkoutEmailAndCode(userRegisterDTO.getCode(), userRegisterDTO.getEmail(), UserConstant.USER_EMAIL_REGISTER); + } + + /** + * 校验 邮箱地址 和 验证码 + * + * @param code 验证码 + * @param email 邮箱 + * @param codeRedisKey redis-key + */ + private void checkoutEmailAndCode(String code, String email, String codeRedisKey) { + //校验验证码是否过期 + Object emailVoObj = redisUtils.hget(codeRedisKey.concat(email), email); + if (Objects.isNull(emailVoObj)) { + LogUtil.error(LogEnum.SYS_ERR, "UserServiceImpl emailVo already expired , email:{} ", email); + throw new BusinessException(BaseErrorCodeEnum.SYSTEM_USER_REGISTER_EMAIL_INFO_EXPIRED.getCode(), + BaseErrorCodeEnum.SYSTEM_USER_REGISTER_EMAIL_INFO_EXPIRED.getMsg()); + } + + //校验邮箱和验证码 + EmailVo emailVo = (EmailVo) emailVoObj; + if (!email.equals(emailVo.getEmail()) || !code.equals(emailVo.getCode())) { + LogUtil.error(LogEnum.SYS_ERR, "UserServiceImpl email or code error , email:{} code:{}", email, code); + throw new BusinessException(BaseErrorCodeEnum.SYSTEM_USER_EMAIL_OR_CODE_ERROR.getCode(), + BaseErrorCodeEnum.SYSTEM_USER_EMAIL_OR_CODE_ERROR.getMsg()); + } + } + + + /** + * 获取 发送邮箱code 的 redis key + * + * @param type 发送邮件类型 + */ + private String getSendEmailCodeRedisKeyByType(Integer type) { + String typeKey = null; + if (UserMailCodeEnum.REGISTER_CODE.getValue().compareTo(type) == 0) { + typeKey = UserConstant.USER_EMAIL_REGISTER; + } else if (UserMailCodeEnum.MAIL_UPDATE_CODE.getValue().compareTo(type) == 0) { + typeKey = UserConstant.USER_EMAIL_UPDATE; + } else if (UserMailCodeEnum.FORGET_PASSWORD.getValue().compareTo(type) == 0) { + typeKey = UserConstant.USER_EMAIL_RESET_PASSWORD; + } else { + typeKey = UserConstant.USER_EMAIL_OTHER; + } + return typeKey; + } + + + /** + * 修改管理员信息校验 + * + * @param userId 用户ID + */ + private void checkIsAdmin(Long userId) { + //修改管理员信息校验 + if (UserConstant.ADMIN_USER_ID == userId.intValue() && + UserConstant.ADMIN_USER_ID != JwtUtils.getCurUserId().intValue()) { + throw new BusinessException(BaseErrorCodeEnum.SYSTEM_USER_CANNOT_UPDATE_ADMIN); + } + } + + + /** + * 根据用户名查询用户信息 + * + * @param username 用户名称 + * @return 用户信息 + */ + @Override + public DataResponseBody findUserByUsername(String username) { + User user = userMapper.findByUsername(username); + if (Objects.isNull(user)) { + LogUtil.error(LogEnum.SYS_ERR, "UserServiceImpl findUserByUsername user is null {}"); + throw new BusinessException("用户信息不存在!"); + } + UserContext dto = new UserContext(); + BeanUtils.copyProperties(user, dto); + if (user.getUserAvatar() != null && user.getUserAvatar().getPath() != null) { + dto.setUserAvatarPath(user.getUserAvatar().getPath()); + } + List roles = roleMapper.selectRoleByUserId(user.getId()); + if (!CollectionUtils.isEmpty(roles)) { + + List roleIds = roles.stream().map(a -> a.getId()).collect(Collectors.toList()); + //获取菜单权限 + List permissions = menuMapper.selectPermissionByRoleIds(roleIds); + //获取操作权限 + List authList = permissionMapper.selectPermissinByRoleIds(roleIds); + permissions.addAll(authList); + Map> permissionMap = new HashMap<>(permissions.size()); + if (!CollectionUtils.isEmpty(permissions)) { + permissionMap = permissions.stream().collect(Collectors.groupingBy(SysPermissionDTO::getRoleId)); + } + + Map> finalPermissionMap = permissionMap; + List roleDTOS = roles.stream().map(a -> { + SysRoleDTO sysRoleDTO = new SysRoleDTO(); + BeanUtils.copyProperties(a, sysRoleDTO); + List sysPermissionDTOS = finalPermissionMap.get(a.getId()); + sysRoleDTO.setPermissions(sysPermissionDTOS); + return sysRoleDTO; + }).collect(Collectors.toList()); + dto.setRoles(roleDTOS); + } + + + return DataResponseFactory.success(dto); + } +} diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/task/RecycleInvalidResourcesTask.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/task/RecycleInvalidResourcesTask.java new file mode 100644 index 0000000..dea14cd --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/task/RecycleInvalidResourcesTask.java @@ -0,0 +1,56 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.task; + +import org.dubhe.admin.service.RecycleTaskService; +import org.dubhe.biz.file.config.NfsConfig; +import org.dubhe.biz.log.handler.ScheduleTaskHandler; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +import java.io.File; + +/** + * @description 回收无效文件资源定时任务 + * @date 2020-09-21 + */ +@Component +public class RecycleInvalidResourcesTask { + + @Autowired + private NfsConfig nfsConfig; + + @Autowired + private RecycleTaskService recycleTaskService; + + /** + * 文件存储临时文件根目录 + */ + public static final String UPLOAD_TEMP = File.separator + "upload-temp"; + + /** + * 每天晚上12点定时回收无效文件资源 + */ + @Scheduled(cron = "0 0 0 * * ?") + public void process() { + ScheduleTaskHandler.process(() -> { + String sourcePath = nfsConfig.getRootDir() + nfsConfig.getBucket() + UPLOAD_TEMP; + recycleTaskService.deleteInvalidResourcesByCMD(sourcePath); + }); + } +} \ No newline at end of file diff --git a/dubhe-server/admin/src/main/java/org/dubhe/admin/task/RecycleResourcesTask.java b/dubhe-server/admin/src/main/java/org/dubhe/admin/task/RecycleResourcesTask.java new file mode 100644 index 0000000..442a305 --- /dev/null +++ b/dubhe-server/admin/src/main/java/org/dubhe/admin/task/RecycleResourcesTask.java @@ -0,0 +1,59 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin.task; + +import org.dubhe.admin.service.RecycleTaskService; +import org.dubhe.biz.base.constant.UserConstant; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.handler.ScheduleTaskHandler; +import org.dubhe.biz.log.utils.LogUtil; +import org.dubhe.recycle.domain.entity.Recycle; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +import java.util.List; + +/** + * @description 回收资源定时任务 + * @date 2020-09-21 + */ +@Component +public class RecycleResourcesTask { + + @Autowired + private RecycleTaskService recycleTaskService; + + /** + * 每天凌晨1点定时回收已删除资源 + */ + @Scheduled(cron = "0 0 1 * * ?") + public void process() { + ScheduleTaskHandler.process(() -> { + List recycleTaskList = recycleTaskService.getRecycleTaskList(); + for (Recycle recycle : recycleTaskList) { + // one by one + try { + recycleTaskService.recycleTask(recycle, UserConstant.ADMIN_USER_ID); + } catch (Exception e) { + LogUtil.error(LogEnum.GARBAGE_RECYCLE, "scheduled recycle task failed,exception {}", e); + } + } + }); + } + +} diff --git a/dubhe-server/admin/src/main/resources/banner.txt b/dubhe-server/admin/src/main/resources/banner.txt new file mode 100644 index 0000000..ef44bd8 --- /dev/null +++ b/dubhe-server/admin/src/main/resources/banner.txt @@ -0,0 +1,14 @@ + + + + _____ _ _ _ _ + | __ \ | | | | /\ | | (_) + | | | |_ _| |__ | |__ ___ / \ __| |_ __ ___ _ _ __ + | | | | | | | '_ \| '_ \ / _ \ / /\ \ / _` | '_ ` _ \| | '_ \ + | |__| | |_| | |_) | | | | __/ / ____ \ (_| | | | | | | | | | | + |_____/ \__,_|_.__/|_| |_|\___| /_/ \_\__,_|_| |_| |_|_|_| |_| + + + + + :: Dubhe Admin :: 0.0.1-SNAPSHOT diff --git a/dubhe-server/admin/src/main/resources/bootstrap.yml b/dubhe-server/admin/src/main/resources/bootstrap.yml new file mode 100644 index 0000000..e5b0ebc --- /dev/null +++ b/dubhe-server/admin/src/main/resources/bootstrap.yml @@ -0,0 +1,37 @@ +server: + port: 8870 + +spring: + application: + name: admin + profiles: + active: dev + cloud: + nacos: + config: + enabled: true + server-addr: 127.0.0.1:8848 + namespace: dubhe-server-cloud-prod + shared-configs[0]: + data-id: common-biz.yaml + group: dubhe + refresh: true # 是否动态刷新,默认为false + shared-configs[1]: + # 配置1 + data-id: common-k8s.yaml + group: dubhe + refresh: true + shared-configs[2]: + data-id: common-recycle.yaml + group: dubhe + refresh: true + shared-configs[3]: + data-id: admin.yaml + group: dubhe + refresh: true + discovery: + enabled: true + namespace: dubhe-server-cloud-prod + group: dubhe + server-addr: 127.0.0.1:8848 + diff --git a/dubhe-server/admin/src/main/resources/mapper/AuthMapper.xml b/dubhe-server/admin/src/main/resources/mapper/AuthMapper.xml new file mode 100644 index 0000000..af66699 --- /dev/null +++ b/dubhe-server/admin/src/main/resources/mapper/AuthMapper.xml @@ -0,0 +1,18 @@ + + + + + + insert into roles_auth(role_id,auth_id)values + + (#{item.roleId},#{item.authId}) + + + + + insert into auth_permission(auth_id,permission_id)values + + (#{item.authId},#{item.permissionId}) + + + \ No newline at end of file diff --git a/dubhe-server/admin/src/main/resources/mapper/MenuMapper.xml b/dubhe-server/admin/src/main/resources/mapper/MenuMapper.xml new file mode 100644 index 0000000..deac611 --- /dev/null +++ b/dubhe-server/admin/src/main/resources/mapper/MenuMapper.xml @@ -0,0 +1,11 @@ + + + + + + \ No newline at end of file diff --git a/dubhe-server/admin/src/main/resources/mapper/PermissionMapper.xml b/dubhe-server/admin/src/main/resources/mapper/PermissionMapper.xml new file mode 100644 index 0000000..2729dd2 --- /dev/null +++ b/dubhe-server/admin/src/main/resources/mapper/PermissionMapper.xml @@ -0,0 +1,15 @@ + + + + + + \ No newline at end of file diff --git a/dubhe-server/admin/src/main/resources/mapper/UserMapper.xml b/dubhe-server/admin/src/main/resources/mapper/UserMapper.xml new file mode 100644 index 0000000..7bd66ca --- /dev/null +++ b/dubhe-server/admin/src/main/resources/mapper/UserMapper.xml @@ -0,0 +1,16 @@ + + + + + + \ No newline at end of file diff --git a/dubhe-server/admin/src/main/resources/mapper/UserRoleMapper.xml b/dubhe-server/admin/src/main/resources/mapper/UserRoleMapper.xml new file mode 100644 index 0000000..95f5062 --- /dev/null +++ b/dubhe-server/admin/src/main/resources/mapper/UserRoleMapper.xml @@ -0,0 +1,19 @@ + + + + + + + delete from users_roles where user_id in + + #{item} + + + + + insert into users_roles (user_id,role_id)values + + (#{item.userId}, #{item.roleId}) + + + \ No newline at end of file diff --git a/dubhe-server/admin/src/test/java/org/dubhe/admin/AdminApplicationTests.java b/dubhe-server/admin/src/test/java/org/dubhe/admin/AdminApplicationTests.java new file mode 100644 index 0000000..b145a05 --- /dev/null +++ b/dubhe-server/admin/src/test/java/org/dubhe/admin/AdminApplicationTests.java @@ -0,0 +1,70 @@ +package org.dubhe.admin; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.dubhe.admin.domain.dto.DictCreateDTO; +import org.dubhe.admin.domain.dto.DictDetailDTO; +import org.dubhe.admin.domain.dto.DictDetailQueryDTO; +import org.dubhe.admin.domain.entity.DictDetail; +import org.dubhe.admin.rest.DictController; +import org.dubhe.admin.service.DictDetailService; +import org.dubhe.biz.base.utils.DateUtil; +import org.dubhe.biz.base.vo.DataResponseBody; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +import java.util.ArrayList; +import java.util.List; + +/** + * @description Admin启动类单元测试 + * @date: 2020-12-02 + */ +@SpringBootTest +public class AdminApplicationTests { + + @Autowired + private DictController dictController; + @Autowired + private DictDetailService dictDetailService; + + /** + * 字典分页查询 + */ + @Test + public void demo01() { + + Page page = new Page<>(); + page.setCurrent(1); + page.setSize(5); + DictDetailQueryDTO dictQueryDTO = new DictDetailQueryDTO(); + dictQueryDTO.setDictId(3L); + List dictDetailDTOS = dictDetailService.queryAll(dictQueryDTO); + System.out.println(dictDetailDTOS.size()); + + } + + /** + * 字典创建 + */ + @Test + public void demo02() { + DictCreateDTO dict = new DictCreateDTO(); + dict.setName("测试"); + dict.setCreateTime(DateUtil.getCurrentTimestamp()); + dict.setRemark("观点"); + List dictDetails = new ArrayList<>(); + DictDetail dictDetail = new DictDetail(); + dictDetail.setCreateTime(DateUtil.getCurrentTimestamp()); + dictDetail.setId(2222L); + dictDetail.setLabel("开发"); + dictDetail.setSort("9"); + dictDetail.setValue("1"); + dictDetails.add(dictDetail); + dict.setDictDetails(dictDetails); + DataResponseBody dataResponseBody = dictController.create(dict); + System.out.println(dataResponseBody.getData()); + + } + +} diff --git a/dubhe-server/admin/src/test/java/org/dubhe/admin/DictControllerTest.java b/dubhe-server/admin/src/test/java/org/dubhe/admin/DictControllerTest.java new file mode 100644 index 0000000..6a3ae9c --- /dev/null +++ b/dubhe-server/admin/src/test/java/org/dubhe/admin/DictControllerTest.java @@ -0,0 +1,43 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.admin; + +import org.dubhe.biz.base.constant.AuthConst; +import org.dubhe.cloud.unittest.base.BaseTest; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; + +/** + * @description 实体类 + * @date 2020-03-25 + */ +@RunWith(SpringRunner.class) +@SpringBootTest +public class DictControllerTest extends BaseTest { + + @Test + public void whenQueryUserAll() throws Exception { + String accessToken = obtainAccessToken(); + mockMvcWithNoRequestBody(mockMvc.perform(MockMvcRequestBuilders.get("/api/dict/all").header(AuthConst.AUTHORIZATION, AuthConst.ACCESS_TOKEN_PREFIX + accessToken)) + .andExpect(MockMvcResultMatchers.status().isOk()).andReturn().getResponse(), 200); + } +} diff --git a/dubhe-server/auth/pom.xml b/dubhe-server/auth/pom.xml new file mode 100644 index 0000000..81fee47 --- /dev/null +++ b/dubhe-server/auth/pom.xml @@ -0,0 +1,92 @@ + + + 4.0.0 + + org.dubhe + server + 0.0.1-SNAPSHOT + + auth + 0.0.1-SNAPSHOT + 授权中心 + Dubhe Authentication + + + + + org.dubhe.biz + data-response + ${org.dubhe.biz.data-response.version} + + + + org.dubhe.cloud + auth-config + ${org.dubhe.cloud.auth-config.version} + + + + org.dubhe.cloud + remote-call + ${org.dubhe.cloud.remote-call.version} + + + + org.dubhe.cloud + registration + ${org.dubhe.cloud.registration.version} + + + + org.dubhe.cloud + configuration + ${org.dubhe.cloud.configuration.version} + + + + org.dubhe.cloud + swagger + ${org.dubhe.cloud.swagger.version} + + + + org.dubhe.biz + data-permission + ${org.dubhe.biz.data-permission.version} + + + + org.dubhe.biz + log + ${org.dubhe.biz.log.version} + + + org.springframework.boot + spring-boot-starter-web + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + false + true + exec + + + + + org.apache.maven.plugins + maven-surefire-plugin + + true + + + + + + diff --git a/dubhe-server/auth/src/main/java/org/dubhe/auth/AuthApplication.java b/dubhe-server/auth/src/main/java/org/dubhe/auth/AuthApplication.java new file mode 100644 index 0000000..a02a707 --- /dev/null +++ b/dubhe-server/auth/src/main/java/org/dubhe/auth/AuthApplication.java @@ -0,0 +1,33 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.auth; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +/** + * @description Auth启动类 + * @date 2020-12-02 + */ +@SpringBootApplication(scanBasePackages = "org.dubhe") +public class AuthApplication { + + public static void main(String[] args) { + SpringApplication.run(AuthApplication.class, args); + } + +} diff --git a/dubhe-server/auth/src/main/java/org/dubhe/auth/config/AuthorizationServerConfig.java b/dubhe-server/auth/src/main/java/org/dubhe/auth/config/AuthorizationServerConfig.java new file mode 100644 index 0000000..3ed70ab --- /dev/null +++ b/dubhe-server/auth/src/main/java/org/dubhe/auth/config/AuthorizationServerConfig.java @@ -0,0 +1,100 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.auth.config; + +import org.dubhe.cloud.authconfig.factory.PasswordEncoderFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; +import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; +import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; +import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; +import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; +import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator; +import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore; +import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; + +import javax.sql.DataSource; + +/** + * @description 授权配置 + * @date 2020-11-05 + */ +@EnableAuthorizationServer +@Configuration +public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter{ + + @Autowired + private AuthenticationManager authenticationManager; + + @Autowired + private DataSource dataSource; + + @Autowired + private UserDetailsService userDetailsService; + + @Autowired + private JdbcTokenStore tokenStore; + + @Autowired + private JwtAccessTokenConverter accessTokenConverter; + + @Autowired + @Qualifier("customerOauthWebResponseExceptionTranslator") + private WebResponseExceptionTranslator webResponseExceptionTranslator; + + @Override + public void configure(ClientDetailsServiceConfigurer clients) throws Exception { + clients + .jdbc(dataSource) + .passwordEncoder(PasswordEncoderFactory.getPasswordEncoder()) + ; + } + + + @Override + public void configure(AuthorizationServerEndpointsConfigurer endpoints) { + endpoints + .tokenStore(tokenStore) + .accessTokenConverter(accessTokenConverter) + .authenticationManager(authenticationManager) + // 刷新token必须设置userDetailsService + .userDetailsService(userDetailsService) + .exceptionTranslator(webResponseExceptionTranslator)//认证异常处理器 + // 重用刷新token + .reuseRefreshTokens(true); + } + + + /** + * 允许所有人请求令牌 + * 已验证的可客户端才能请求check_token端点 + * @param security + * @throws Exception + */ + @Override + public void configure(AuthorizationServerSecurityConfigurer security) { + security + .passwordEncoder(PasswordEncoderFactory.getPasswordEncoder()) + .tokenKeyAccess("permitAll()") + .checkTokenAccess("isAuthenticated()") + .allowFormAuthenticationForClients(); + } +} diff --git a/dubhe-server/auth/src/main/java/org/dubhe/auth/config/SecurityConfig.java b/dubhe-server/auth/src/main/java/org/dubhe/auth/config/SecurityConfig.java new file mode 100644 index 0000000..56abcf2 --- /dev/null +++ b/dubhe-server/auth/src/main/java/org/dubhe/auth/config/SecurityConfig.java @@ -0,0 +1,83 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.auth.config; + +import org.dubhe.cloud.authconfig.factory.PasswordEncoderFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.AuthenticationProvider; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.crypto.password.PasswordEncoder; + +/** + * @description 安全配置 + * @date 2020-11-05 + */ +@Configuration +@EnableWebSecurity +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + + @Autowired + @Qualifier("authenticationProviderImpl") + private AuthenticationProvider authenticationProvider; + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.authenticationProvider(authenticationProvider); + } + + @Bean + public PasswordEncoder passwordEncoder(){ + return PasswordEncoderFactory.getPasswordEncoder(); + } + + + @Bean + @Override + public AuthenticationManager authenticationManagerBean() throws Exception { + return super.authenticationManagerBean(); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + // 允许访问/oauth 授权接口 + http.csrf().disable() + .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED) + .and() + .requestMatchers().anyRequest() + .and() + .authorizeRequests() + .antMatchers("/oauth/*").permitAll() + // swagger + .antMatchers("/swagger**/**").permitAll() + .antMatchers("/webjars/**").permitAll() + .antMatchers("/v2/api-docs/**").permitAll() + // 其他所有请求需要身份认证 + .anyRequest().authenticated(); + + } + +} diff --git a/dubhe-server/auth/src/main/java/org/dubhe/auth/exception/AuthenticationProviderImpl.java b/dubhe-server/auth/src/main/java/org/dubhe/auth/exception/AuthenticationProviderImpl.java new file mode 100644 index 0000000..e47ef5d --- /dev/null +++ b/dubhe-server/auth/src/main/java/org/dubhe/auth/exception/AuthenticationProviderImpl.java @@ -0,0 +1,76 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.auth.exception; + +import org.apache.commons.lang3.StringUtils; +import org.dubhe.biz.base.exception.FeignException; +import org.dubhe.cloud.authconfig.dto.JwtUserDTO; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.security.authentication.AuthenticationProvider; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.stereotype.Service; + +import java.util.Objects; + + +/** + * @description 抛出自定义中文错误信息 + * @date 2020-12-21 + */ +@Service +public class AuthenticationProviderImpl implements AuthenticationProvider { + @Autowired + @Qualifier("userDetailsServiceImpl") + private UserDetailsService userDetailsService; + + @Override + public Authentication authenticate(Authentication authentication) throws AuthenticationException { + String username = authentication.getName(); + String password = authentication.getCredentials().toString(); + JwtUserDTO userDTO; + try { + userDTO = (JwtUserDTO) userDetailsService.loadUserByUsername(username); + } catch (Exception e) { + if (StringUtils.isNotBlank(e.getMessage()) && e.getMessage().contains("Load balancer does not have available server for client")) { + throw new BadCredentialsException("用户服务不可用!", e); + } else if (e instanceof FeignException) { + throw new BadCredentialsException("用户服务" + ((FeignException) e).getResponseBody().getMsg(), e); + } else { + throw new BadCredentialsException("用户信息不存在!", e); + } + } + if (!Objects.isNull(userDTO.getUser()) && !userDTO.getUser().getEnabled()) { + throw new BadCredentialsException("帐号已锁定!"); + } + if (!new BCryptPasswordEncoder().matches(password, userDTO.getPassword())) { + throw new BadCredentialsException("密码错误!"); + } + return new UsernamePasswordAuthenticationToken(userDTO, userDTO.getPassword(), null); + } + + @Override + public boolean supports(Class aClass) { + return UsernamePasswordAuthenticationToken.class.equals(aClass); + } +} \ No newline at end of file diff --git a/dubhe-server/auth/src/main/java/org/dubhe/auth/exception/CustomerOauthException.java b/dubhe-server/auth/src/main/java/org/dubhe/auth/exception/CustomerOauthException.java new file mode 100644 index 0000000..c2d76bf --- /dev/null +++ b/dubhe-server/auth/src/main/java/org/dubhe/auth/exception/CustomerOauthException.java @@ -0,0 +1,37 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.auth.exception; + +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import org.springframework.security.oauth2.common.exceptions.OAuth2Exception; + +/** + * @description 定义自已的异常处理类 + * @date 2020-12-21 + */ +@JsonSerialize(using = CustomerOauthExceptionSerializer.class) +public class CustomerOauthException extends OAuth2Exception { + public CustomerOauthException(String msg, Throwable t) { + super(msg, t); + } + + public CustomerOauthException(String msg) { + super(msg); + } + +} diff --git a/dubhe-server/auth/src/main/java/org/dubhe/auth/exception/CustomerOauthExceptionSerializer.java b/dubhe-server/auth/src/main/java/org/dubhe/auth/exception/CustomerOauthExceptionSerializer.java new file mode 100644 index 0000000..c3ec451 --- /dev/null +++ b/dubhe-server/auth/src/main/java/org/dubhe/auth/exception/CustomerOauthExceptionSerializer.java @@ -0,0 +1,49 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.auth.exception; + + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.ser.std.StdSerializer; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; + +/** + * @description 序列化异常处理类 + * @date 2020-12-21 + */ +public class CustomerOauthExceptionSerializer extends StdSerializer { + + protected CustomerOauthExceptionSerializer() { + super(CustomerOauthException.class); + } + + @Override + public void serialize(CustomerOauthException e, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { + HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); + jsonGenerator.writeStartObject(); + jsonGenerator.writeStringField("code", String.valueOf(e.getHttpErrorCode())); + jsonGenerator.writeStringField("msg", e.getMessage()); + jsonGenerator.writeStringField("data",null); + jsonGenerator.writeEndObject(); + } +} + diff --git a/dubhe-server/auth/src/main/java/org/dubhe/auth/exception/CustomerOauthWebResponseExceptionTranslator.java b/dubhe-server/auth/src/main/java/org/dubhe/auth/exception/CustomerOauthWebResponseExceptionTranslator.java new file mode 100644 index 0000000..f93e43e --- /dev/null +++ b/dubhe-server/auth/src/main/java/org/dubhe/auth/exception/CustomerOauthWebResponseExceptionTranslator.java @@ -0,0 +1,168 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.auth.exception; + + + +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.oauth2.common.DefaultThrowableAnalyzer; +import org.springframework.security.oauth2.common.OAuth2AccessToken; +import org.springframework.security.oauth2.common.exceptions.InsufficientScopeException; +import org.springframework.security.oauth2.common.exceptions.OAuth2Exception; +import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator; +import org.springframework.security.web.util.ThrowableAnalyzer; +import org.springframework.stereotype.Component; +import org.springframework.web.HttpRequestMethodNotSupportedException; + +import java.io.IOException; + + + +/** + * @description 异常捕获并通过CustomerOauthException处理 + * @date 2020-12-21 + */ +@Component +public class CustomerOauthWebResponseExceptionTranslator implements WebResponseExceptionTranslator { + private ThrowableAnalyzer throwableAnalyzer = new DefaultThrowableAnalyzer(); + + @Override + public ResponseEntity translate(Exception e) throws Exception { + Throwable[] causeChain = throwableAnalyzer.determineCauseChain(e); + Exception ase=null; + + // 异常栈获取 OAuth2Exception 异常 + ase = (OAuth2Exception) throwableAnalyzer.getFirstThrowableOfType( + OAuth2Exception.class, causeChain); + // 异常栈中有OAuth2Exception + if (ase != null) { + return handleOAuth2Exception((OAuth2Exception) ase); + } + + ase = (AuthenticationException) throwableAnalyzer.getFirstThrowableOfType(AuthenticationException.class, + causeChain); + if (ase != null) { + return handleOAuth2Exception(new UnauthorizedException(e.getMessage(), e)); + } + + ase = (AccessDeniedException) throwableAnalyzer + .getFirstThrowableOfType(AccessDeniedException.class, causeChain); + if (ase instanceof AccessDeniedException) { + return handleOAuth2Exception(new ForbiddenException(ase.getMessage(), ase)); + } + + ase = (HttpRequestMethodNotSupportedException) throwableAnalyzer + .getFirstThrowableOfType(HttpRequestMethodNotSupportedException.class, causeChain); + if (ase instanceof HttpRequestMethodNotSupportedException) { + return handleOAuth2Exception(new MethodNotAllowed(ase.getMessage(), ase)); + } + + // 不包含上述异常则服务器内部错误 + return handleOAuth2Exception(new ServerErrorException(HttpStatus.OK.getReasonPhrase(), e)); + } + + //使用自定义的异常处理类处理异常 + private ResponseEntity handleOAuth2Exception(OAuth2Exception e) throws IOException { + int status = e.getHttpErrorCode(); + HttpHeaders headers = new HttpHeaders(); + headers.set("Cache-Control", "no-store"); + headers.set("Pragma", "no-cache"); + if (status == HttpStatus.UNAUTHORIZED.value() || (e instanceof InsufficientScopeException)) { + headers.set("WWW-Authenticate", String.format("%s %s", OAuth2AccessToken.BEARER_TYPE, e.getSummary())); + } + CustomerOauthException exception = new CustomerOauthException(e.getMessage(), e); + + ResponseEntity response = new ResponseEntity(exception, headers, + HttpStatus.OK); + + return response; + + } + + @SuppressWarnings("serial") + private static class ForbiddenException extends OAuth2Exception { + + public ForbiddenException(String msg, Throwable t) { + super(msg, t); + } + + public String getOAuth2ErrorCode() { + return "access_denied"; + } + + public int getHttpErrorCode() { + return 403; + } + + } + + @SuppressWarnings("serial") + private static class ServerErrorException extends OAuth2Exception { + + public ServerErrorException(String msg, Throwable t) { + super(msg, t); + } + + public String getOAuth2ErrorCode() { + return "server_error"; + } + + public int getHttpErrorCode() { + return 500; + } + + } + + @SuppressWarnings("serial") + private static class UnauthorizedException extends OAuth2Exception { + + public UnauthorizedException(String msg, Throwable t) { + super(msg, t); + } + + public String getOAuth2ErrorCode() { + return "unauthorized"; + } + + public int getHttpErrorCode() { + return 401; + } + + } + + @SuppressWarnings("serial") + private static class MethodNotAllowed extends OAuth2Exception { + + public MethodNotAllowed(String msg, Throwable t) { + super(msg, t); + } + + public String getOAuth2ErrorCode() { + return "method_not_allowed"; + } + + public int getHttpErrorCode() { + return 405; + } + + } + +} diff --git a/dubhe-server/auth/src/main/java/org/dubhe/auth/rest/AuthController.java b/dubhe-server/auth/src/main/java/org/dubhe/auth/rest/AuthController.java new file mode 100644 index 0000000..a370fb0 --- /dev/null +++ b/dubhe-server/auth/src/main/java/org/dubhe/auth/rest/AuthController.java @@ -0,0 +1,118 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.auth.rest; + +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiImplicitParams; +import io.swagger.annotations.ApiOperation; +import org.dubhe.biz.base.dto.Oauth2TokenDTO; +import org.dubhe.biz.base.constant.AuthConst; +import org.dubhe.biz.base.context.UserContext; +import org.dubhe.biz.base.service.UserContextService; +import org.dubhe.biz.base.utils.StringUtils; +import org.dubhe.biz.base.vo.DataResponseBody; +import org.dubhe.biz.dataresponse.factory.DataResponseFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.oauth2.common.OAuth2AccessToken; +import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint; +import org.springframework.security.oauth2.provider.token.ConsumerTokenServices; +import org.springframework.web.HttpRequestMethodNotSupportedException; +import org.springframework.web.bind.annotation.*; +import springfox.documentation.annotations.ApiIgnore; + +import javax.annotation.Resource; +import java.security.Principal; +import java.util.Map; + +/** + * @description 授权接口类 + * @date 2020-11-03 + */ +@RestController +@RequestMapping(value = "/oauth") +public class AuthController { + + @Resource + private ConsumerTokenServices consumerTokenServices; + + @Autowired + private UserContextService userContextService; + + @Autowired + private TokenEndpoint tokenEndpoint; + + @ApiOperation("Oauth2获取token") + @ApiImplicitParams({ + @ApiImplicitParam(name = "grant_type", value = "授权模式", required = true), + @ApiImplicitParam(name = "client_id", value = "Oauth2客户端ID", required = true), + @ApiImplicitParam(name = "client_secret", value = "Oauth2客户端秘钥", required = true), + @ApiImplicitParam(name = "refresh_token", value = "刷新token"), + @ApiImplicitParam(name = "username", value = "登录用户名"), + @ApiImplicitParam(name = "password", value = "登录密码") + }) + @RequestMapping(value = "/token", method = RequestMethod.POST) + public DataResponseBody postAccessToken(@ApiIgnore Principal principal, @ApiIgnore @RequestParam Map parameters) throws HttpRequestMethodNotSupportedException { + OAuth2AccessToken oAuth2AccessToken = tokenEndpoint.postAccessToken(principal, parameters).getBody(); + Oauth2TokenDTO oauth2TokenDto = Oauth2TokenDTO.builder() + .token(oAuth2AccessToken.getValue()) + .refreshToken(oAuth2AccessToken.getRefreshToken().getValue()) + .expiresIn(oAuth2AccessToken.getExpiresIn()) + .tokenHead(AuthConst.ACCESS_TOKEN_PREFIX).build(); + + return DataResponseFactory.success(oauth2TokenDto); + } + + + /** + * 基于authorization_code方式授权的回调接口 + * @param code + * @return + */ + @GetMapping(value="/callback") + public String hello(String code){ + return "Auth code -> ".concat(code); + } + + + /** + * 获取当前用户 + * @param principal + */ + @GetMapping(value="/user") + @ResponseBody + public UserContext getCurUser(Principal principal){ + return userContextService.getCurUser(); + } + + + + /** + * 自定义登出(请求时header还是需要Authorization信息) + * @param accessToken token + * @return + */ + @DeleteMapping(value="/logout") + public DataResponseBody logout(@RequestParam("token")String accessToken){ + String token = StringUtils.substringAfter(accessToken, "Bearer ").trim(); + if (consumerTokenServices.revokeToken(token)){ + // 登出成功,自定义登出业务逻辑 + return DataResponseFactory.success(); + } + return DataResponseFactory.failed("Logout failed!"); + } + +} diff --git a/dubhe-server/auth/src/main/resources/banner.txt b/dubhe-server/auth/src/main/resources/banner.txt new file mode 100644 index 0000000..c1b1ceb --- /dev/null +++ b/dubhe-server/auth/src/main/resources/banner.txt @@ -0,0 +1,13 @@ + + + _____ _ _ _ _ _ _ _ _ + | __ \ | | | | /\ | | | | | | (_) | | (_) + | | | |_ _| |__ | |__ ___ / \ _ _| |_| |__ ___ _ __ | |_ _ ___ __ _| |_ _ ___ _ __ + | | | | | | | '_ \| '_ \ / _ \ / /\ \| | | | __| '_ \ / _ \ '_ \| __| |/ __/ _` | __| |/ _ \| '_ \ + | |__| | |_| | |_) | | | | __/ / ____ \ |_| | |_| | | | __/ | | | |_| | (_| (_| | |_| | (_) | | | | + |_____/ \__,_|_.__/|_| |_|\___| /_/ \_\__,_|\__|_| |_|\___|_| |_|\__|_|\___\__,_|\__|_|\___/|_| |_| + + + + + :: Dubhe Authentication :: 0.0.1-SNAPSHOT diff --git a/dubhe-server/auth/src/main/resources/bootstrap.yml b/dubhe-server/auth/src/main/resources/bootstrap.yml new file mode 100644 index 0000000..2e2179e --- /dev/null +++ b/dubhe-server/auth/src/main/resources/bootstrap.yml @@ -0,0 +1,29 @@ +server: + port: 8866 + + +spring: + application: + name: auth + profiles: + active: dev + cloud: + nacos: + config: + enabled: true + server-addr: 127.0.0.1:8848 + namespace: dubhe-server-cloud-prod + shared-configs[0]: + data-id: common-biz.yaml + group: dubhe + refresh: true # 是否动态刷新,默认为false + shared-configs[1]: + data-id: auth.yaml + group: dubhe + refresh: true + discovery: + enabled: true + namespace: dubhe-server-cloud-prod + group: dubhe + server-addr: 127.0.0.1:8848 + diff --git a/dubhe-server/auth/src/test/java/org/dubhe/auth/AuthApplicationTests.java b/dubhe-server/auth/src/test/java/org/dubhe/auth/AuthApplicationTests.java new file mode 100644 index 0000000..fe4ff09 --- /dev/null +++ b/dubhe-server/auth/src/test/java/org/dubhe/auth/AuthApplicationTests.java @@ -0,0 +1,13 @@ +package org.dubhe.auth; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class AuthApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/dubhe-server/common-biz/base/pom.xml b/dubhe-server/common-biz/base/pom.xml new file mode 100644 index 0000000..abc26cc --- /dev/null +++ b/dubhe-server/common-biz/base/pom.xml @@ -0,0 +1,75 @@ + + + 4.0.0 + + org.dubhe.biz + common-biz + 0.0.1-SNAPSHOT + + base + 0.0.1-SNAPSHOT + Biz 通用配置 + Base config for Dubhe Server + + + + + org.projectlombok + lombok + ${lombok.version} + + + org.springframework + spring-web + + + javax.servlet + javax.servlet-api + ${javax.servlet-api.version} + + + + jakarta.validation + jakarta.validation-api + + + org.hibernate.validator + hibernate-validator + + + com.thoughtworks.qdox + qdox + ${com.thoughtworks.qdox.version} + + + org.projectlombok + lombok + + + + jakarta.validation + jakarta.validation-api + + + + jakarta.validation + jakarta.validation-api + ${jakarta.validation-api.version} + + + + + commons-codec + commons-codec + + + + + + + + + + + diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/annotation/ApiVersion.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/annotation/ApiVersion.java new file mode 100644 index 0000000..5e516ce --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/annotation/ApiVersion.java @@ -0,0 +1,32 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.annotation; + +import java.lang.annotation.*; + +/** + * @description API版本控制注解 + * @date 2020-04-06 + */ +@Target({ElementType.METHOD, ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface ApiVersion { + //标识版本号 + int value() default 1; +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/annotation/DataPermission.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/annotation/DataPermission.java new file mode 100644 index 0000000..54509a2 --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/annotation/DataPermission.java @@ -0,0 +1,41 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.annotation; + +/** + * @description 数据权限注解 + * @date 2020-11-26 + */ +import java.lang.annotation.*; + +@Target({ElementType.METHOD, ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface DataPermission { + + /** + * 只在类的注解上使用,代表方法的数据权限类型 + * @return + */ + String permission() default ""; + + /** + * 不需要数据权限的方法名 + * @return + */ + String[] ignoresMethod() default {}; +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/annotation/EnumValue.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/annotation/EnumValue.java new file mode 100644 index 0000000..33804bf --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/annotation/EnumValue.java @@ -0,0 +1,88 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.annotation; + +import javax.validation.Constraint; +import javax.validation.ConstraintValidator; +import javax.validation.ConstraintValidatorContext; +import javax.validation.Payload; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +/** + * @description 接口枚举类检测标注类 + * @date 2020-05-21 + */ +@Target({ ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE }) +@Retention(RetentionPolicy.RUNTIME) +@Constraint(validatedBy = EnumValue.Validator.class) +public @interface EnumValue { + + String message() default "custom.value.invalid"; + + Class[] groups() default {}; + + Class[] payload() default {}; + + Class> enumClass(); + + String enumMethod(); + + class Validator implements ConstraintValidator { + + private Class> enumClass; + private String enumMethod; + + @Override + public void initialize(EnumValue enumValue) { + enumMethod = enumValue.enumMethod(); + enumClass = enumValue.enumClass(); + } + + @Override + public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) { + if (value == null) { + return Boolean.TRUE; + } + + if (enumClass == null || enumMethod == null) { + return Boolean.TRUE; + } + Class valueClass = value.getClass(); + + try { + Method method = enumClass.getMethod(enumMethod, valueClass); + if (!Boolean.TYPE.equals(method.getReturnType()) && !Boolean.class.equals(method.getReturnType())) { + throw new RuntimeException(String.format("%s method return is not boolean type in the %s class", enumMethod, enumClass)); + } + + Boolean result = (Boolean)method.invoke(null, value); + return result == null ? false : result; + } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { + throw new RuntimeException(e); + } catch (NoSuchMethodException | SecurityException e) { + throw new RuntimeException(String.format("This %s(%s) method does not exist in the %s", enumMethod, valueClass, enumClass), e); + } + } + + } +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/annotation/FlagValidator.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/annotation/FlagValidator.java new file mode 100644 index 0000000..4195cdb --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/annotation/FlagValidator.java @@ -0,0 +1,66 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.annotation; + +import javax.validation.Constraint; +import javax.validation.ConstraintValidator; +import javax.validation.ConstraintValidatorContext; +import javax.validation.Payload; +import java.lang.annotation.*; +import java.util.Arrays; + +/** + * @description 自定义状态校验注解(传入值是否在指定状态范围内) + * @date 2020-09-18 + */ +@Target({ElementType.FIELD, ElementType.PARAMETER}) +@Retention(RetentionPolicy.RUNTIME) +@Constraint(validatedBy = FlagValidator.Validator.class) +@Documented +public @interface FlagValidator { + + String[] value() default {}; + + String message() default "flag value is invalid"; + + Class[] groups() default {}; + + Class[] payload() default {}; + + /** + * @description 校验传入值是否在默认值范围校验逻辑 + * @date 2020-09-18 + */ + class Validator implements ConstraintValidator { + + private String[] values; + + @Override + public void initialize(FlagValidator flagValidator) { + this.values = flagValidator.value(); + } + + @Override + public boolean isValid(Integer value, ConstraintValidatorContext constraintValidatorContext) { + if (value == null) { + //当状态为空时,使用默认值 + return false; + } + return Arrays.stream(values).anyMatch(Integer.toString(value)::equals); + } + } +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/annotation/Log.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/annotation/Log.java new file mode 100644 index 0000000..49ffc9b --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/annotation/Log.java @@ -0,0 +1,23 @@ + /** + * Copyright 2019-2020 Zheng Jie + * + * Licensed 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 org.dubhe.biz.base.annotation; + +/** + * @description 日志 + * @date 2020-03-15 + */ +public @interface Log { +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/constant/ApplicationNameConst.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/constant/ApplicationNameConst.java new file mode 100644 index 0000000..34d61d8 --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/constant/ApplicationNameConst.java @@ -0,0 +1,84 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.constant; + +/** + * @description 服务名常量类 spring.application.name + * @date 2020-11-05 + */ +public class ApplicationNameConst { + private ApplicationNameConst() { + + } + + /** + * 授权中心 + */ + public final static String SERVER_AUTHORIZATION = "auth"; + /** + * 网关 + */ + public final static String SERVER_GATEWAY = "gateway"; + /** + * 模型开发 + */ + public final static String SERVER_NOTEBOOK = "dubhe-notebook"; + /** + * 算法管理 + */ + public final static String SERVER_ALGORITHM = "dubhe-algorithm"; + /** + * 模型管理 + */ + public final static String SERVER_MODEL = "dubhe-model"; + /** + * 系统管理 + */ + public final static String SERVER_ADMIN = "admin"; + /** + * 镜像管理 + */ + public final static String SERVER_IMAGE = "dubhe-image"; + /** + * 度量管理 + */ + public final static String SERVER_MEASURE = "dubhe-measure"; + /** + * 训练管理 + */ + public final static String SERVER_TRAIN = "dubhe-train"; + /** + * 模型优化 + */ + public final static String SERVER_OPTIMIZE = "dubhe-optimize"; + /** + * 数据集管理 + */ + public final static String SERVER_DATA = "dubhe-data"; + + /** + * 云端Serving + */ + public final static String SERVER_SERVING = "dubhe-serving"; + + + /** + * 医学服务 + */ + public final static String SERVER_DATA_DCM = "dubhe-data-dcm"; + +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/constant/AuthConst.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/constant/AuthConst.java new file mode 100644 index 0000000..384679a --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/constant/AuthConst.java @@ -0,0 +1,77 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.constant; + +/** + * @description 授权常量类 + * @date 2020-11-05 + */ +public class AuthConst { + private AuthConst() { + + } + + /** + * 授权token名称 Header + */ + public final static String AUTHORIZATION = "Authorization"; + /** + * 授权token名称 Params + */ + public final static String ACCESS_TOKEN = "access_token"; + /** + * token前缀 + */ + public final static String ACCESS_TOKEN_PREFIX = "Bearer "; + /** + * 客户端安全码 + * $2a$10$RUYBRsyV2jpG7pvg/VNus.YHVebzfRen3RGeDe1LVEIJeHYe2F1YK + */ + public final static String CLIENT_SECRET = "dubhe-secret"; + /** + * 客户端安全码 + */ + public final static String CLIENT_ID = "dubhe-client"; + /** + * 授权中心token校验地址 + */ + public final static String CHECK_TOKEN_ENDPOINT_URL = "http://" + ApplicationNameConst.SERVER_AUTHORIZATION + "/oauth/check_token"; + /** + * 默认匿名访问路径 + */ + public final static String[] DEFAULT_PERMIT_PATHS = {"/swagger**/**", "/webjars/**", "/v2/api-docs/**", "/doc.html/**", + "/users/findUserByUsername", "/auth/login", "/auth/code", + "/datasets/files/annotations/auto","/datasets/versions/**/convert/finish", "/datasets/enhance/finish", + "/auth/getCodeBySentEmail","/auth/userRegister", + StringConstant.RECYCLE_CALL_URI+"**" + }; + + /** + * k8s 回调token key + */ + public static final String K8S_CALLBACK_TOKEN = "k8sCallbackToken"; + + /** + * 通用授权token key + */ + public static final String COMMON_TOKEN = "commonToken"; + + /** + * 授权模式 + */ + public static final String GRANT_TYPE = "password"; +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/constant/DataStateCodeConstant.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/constant/DataStateCodeConstant.java new file mode 100644 index 0000000..cae8bc3 --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/constant/DataStateCodeConstant.java @@ -0,0 +1,84 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.constant; + +/** + * @description 数据集状态码 + * @date 2020-09-03 + */ +public class DataStateCodeConstant { + + private DataStateCodeConstant() { + } + + /** + * 未标注 + */ + public static final Integer NOT_ANNOTATION_STATE = 101; + /** + * 手动标注中 + */ + public static final Integer MANUAL_ANNOTATION_STATE = 102; + /** + * 自动标注中 + */ + public static final Integer AUTOMATIC_LABELING_STATE = 103; + /** + * 自动标注完成 + */ + public static final Integer AUTO_TAG_COMPLETE_STATE = 104; + /** + * 标注完成 + */ + public static final Integer ANNOTATION_COMPLETE_STATE = 105; + + /** + * 目标跟踪中 + */ + public static final Integer TARGET_FOLLOW_STATE = 201; + /** + * 目标跟踪完成 + */ + public static final Integer TARGET_COMPLETE_STATE = 202; + /** + * 目标跟踪失败 + */ + public static final Integer TARGET_FAILURE_STATE = 203; + + /** + * 未采样 + */ + public static final Integer NOT_SAMPLED_STATE = 301; + /** + * 采样中 + */ + public static final Integer SAMPLING_STATE = 302; + /** + * 采样失败 + */ + public static final Integer SAMPLED_FAILURE_STATE = 303; + + /** + * 增强中 + */ + public static final Integer STRENGTHENING_STATE = 401; + /** + * 导入中 + */ + public static final Integer IN_THE_IMPORT_STATE = 402; + +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/constant/FileStateCodeConstant.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/constant/FileStateCodeConstant.java new file mode 100644 index 0000000..3eb54c0 --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/constant/FileStateCodeConstant.java @@ -0,0 +1,54 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.constant; + +/** + * @description 数据集状态码 + * @date 2020-09-03 + */ +public class FileStateCodeConstant { + + private FileStateCodeConstant(){ + + } + + /** + * 未标注 + */ + public static final Integer NOT_ANNOTATION_FILE_STATE = 101; + /** + * 手动标注中 + */ + public static final Integer MANUAL_ANNOTATION_FILE_STATE = 102; + /** + * 自动标注完成 + */ + public static final Integer AUTO_TAG_COMPLETE_FILE_STATE = 103; + /** + * 标注完成 + */ + public static final Integer ANNOTATION_COMPLETE_FILE_STATE = 104; + /** + * 标注未识别 + */ + public static final Integer ANNOTATION_NOT_DISTINGUISH_FILE_STATE = 105; + /** + * 目标跟踪完成 + */ + public static final Integer TARGET_COMPLETE_FILE_STATE = 201; + +} \ No newline at end of file diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/constant/HarborProperties.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/constant/HarborProperties.java new file mode 100644 index 0000000..ed6ba31 --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/constant/HarborProperties.java @@ -0,0 +1,37 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.constant; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +/** + * @description harbor相关配置 + * @date 2020-07-17 + */ +@Data +@Component +@ConfigurationProperties(prefix = "harbor") +public class HarborProperties { + + private String address; + + private String username; + + private String password; +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/constant/MagicNumConstant.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/constant/MagicNumConstant.java new file mode 100644 index 0000000..fe03ad6 --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/constant/MagicNumConstant.java @@ -0,0 +1,109 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.constant; + +/** + * @description 常用常量类 + * @date 2020-05-14 + */ +public final class MagicNumConstant { + + public static final int NEGATIVE_ONE = -1; + public static final int ZERO = 0; + public static final int ONE = 1; + public static final int TWO = 2; + public static final int THREE = 3; + public static final int FOUR = 4; + public static final int FIVE = 5; + public static final int SIX = 6; + public static final int SEVEN = 7; + public static final int EIGHT = 8; + public static final int NINE = 9; + public static final int TEN = 10; + + public static final int ELEVEN = 11; + public static final int SIXTEEN = 16; + public static final int TWENTY = 20; + public static final int THIRTY_TWO = 32; + public static final int FIFTY = 50; + public static final int SIXTY = 60; + public static final int SIXTY_TWO = 62; + public static final int SIXTY_FOUR = 64; + public static final int ONE_HUNDRED = 100; + public static final int ONE_HUNDRED_TWENTY_SEVEN = 127; + public static final int ONE_HUNDRED_TWENTY_EIGHT = 128; + public static final int ONE_HUNDRED_SIXTY_EIGHT = 168; + public static final int TWO_HUNDRED = 200; + public static final int INTEGER_TWO_HUNDRED_AND_FIFTY_FIVE = 255; + public static final int FIVE_HUNDRED = 500; + public static final int FIVE_HUNDRED_AND_SIXTEEN = 516; + public static final int ONE_THOUSAND = 1000; + public static final int BINARY_TEN_EXP = 1024; + public static final int ONE_THOUSAND_ONE_HUNDRED = 1100; + public static final int ONE_THOUSAND_ONE_HUNDRED_ONE = 1101; + public static final int ONE_THOUSAND_TWO_HUNDRED = 1200; + public static final int ONE_THOUSAND_TWO_HUNDRED_ONE = 1201; + public static final int ONE_THOUSAND_TWENTY_FOUR = 1024; + public static final int ONE_THOUSAND_THREE_HUNDRED = 1300; + public static final int ONE_THOUSAND_THREE_HUNDRED_ONE = 1301; + public static final int ONE_THOUSAND_THREE_HUNDRED_NINE = 1309; + public static final int ONE_THOUSAND_FIVE_HUNDRED = 1500; + public static final int TWO_THOUSAND = 2000; + public static final int TWO_THOUSAND_TWENTY_EIGHT = 2048; + public static final int THREE_THOUSAND = 3000; + public static final int FOUR_THOUSAND = 4000; + public static final int NINE_THOUSAND = 9000; + public static final int NINE_THOUSAND_NINE_HUNDRED_NINTY_NINE = 9999; + public static final int TEN_THOUSAND = 10000; + public static final int FIFTEEN_THOUSAND = 15000; + public static final int HUNDRED_THOUSAND = 100000; + public static final int MILLION = 1000000; + public static final int ONE_MINUTE = 60000; + public static final int TWO_BILLION = 2000000000; + + public static final long NEGATIVE_ONE__LONG = -1L; + public static final long ZERO_LONG = 0L; + public static final long ONE_LONG = 1L; + public static final long TWO_LONG = 2L; + public static final long THREE_LONG = 3L; + public static final long FOUR_LONG = 4L; + public static final long FIVE_LONG = 5L; + public static final long SIX_LONG = 6L; + public static final long SEVEN_LONG = 7L; + public static final long EIGHT_LONG = 8L; + public static final long NINE_LONG = 9L; + public static final long TEN_LONG = 10L; + + public static final long TWELVE_LONG = 12L; + public static final long SIXTY_LONG = 60L; + public static final long THOUSAND_LONG = 1000L; + public static final long TEN_THOUSAND_LONG = 10000L; + public static final long MILLION_LONG = 1000000L; + public static final long ONE_ZERO_ONE_ZERO_ONE_ZERO_LONG = 101010L; + public static final long NINE_ZERO_NINE_ZERO_NINE_ZERO_LONG = 909090L; + public static final long ONE_YEAR_BEFORE_LONG = 1552579200000L; + + public static final double ZERO_DOUBLE = 0.0; + public static final double ONE_DOUBLE = 1.0; + + public static final int SIXITY_0XFF = 0xFF; + + + private MagicNumConstant() { + } +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/constant/MetaHandlerConstant.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/constant/MetaHandlerConstant.java new file mode 100644 index 0000000..338bd17 --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/constant/MetaHandlerConstant.java @@ -0,0 +1,53 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.constant; + +/** + * @description 元数据枚举 + * @date 2020-11-26 + */ +public final class MetaHandlerConstant { + + /** + * 创建时间字段 + */ + public static final String CREATE_TIME = "createTime"; + /** + *更新时间字段 + */ + public static final String UPDATE_TIME = "updateTime"; + /** + *更新人id字段 + */ + public static final String UPDATE_USER_ID = "updateUserId"; + /** + *创建人id字段 + */ + public static final String CREATE_USER_ID = "createUserId"; + /** + *资源拥有人id字段 + */ + public static final String ORIGIN_USER_ID = "originUserId"; + /** + *删除字段 + */ + public static final String DELETED = "deleted"; + + private MetaHandlerConstant() { + } +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/constant/NumberConstant.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/constant/NumberConstant.java new file mode 100644 index 0000000..bb177ef --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/constant/NumberConstant.java @@ -0,0 +1,48 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.constant; + +/** + * @description 数字常量 + * @date 2020-06-09 + */ +public class NumberConstant { + + public final static int NUMBER_0 = 0; + public final static int NUMBER_1 = 1; + public final static int NUMBER_2 = 2; + public final static int NUMBER_3 = 3; + public final static int NUMBER_4 = 4; + public final static int NUMBER_5 = 5; + public final static int NUMBER_6 = 6; + public final static int NUMBER_8 = 8; + public final static int NUMBER_10 = 10; + public final static int NUMBER_30 = 30; + public final static int NUMBER_32 = 32; + public final static int NUMBER_50 = 50; + public final static int NUMBER_60 = 60; + public final static int NUMBER_64 = 64; + public final static int NUMBER_100 = 100; + public final static int NUMBER_1024 = 1024; + public final static int NUMBER_1000 = 1000; + public final static int HOUR_SECOND = 60 * 60; + public final static int DAY_SECOND = 60 * 60 * 24; + public final static int WEEK_SECOND = 60 * 60 * 24 * 7; + public final static int MAX_PAGE_SIZE = 2000; + public final static int MAX_MESSAGE_LENGTH = 1024 * 1024 * 1024; +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/constant/Permissions.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/constant/Permissions.java new file mode 100644 index 0000000..5946fad --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/constant/Permissions.java @@ -0,0 +1,205 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.constant; + +/** + * @description 权限标识,对应 menu 表中的 permission 字段 + * @date 2020-05-14 + */ +public final class Permissions { + + /** + * 数据管理 + */ + public static final String DATA = "hasAuthority('ROLE_data')"; + + /** + * notebook权限 + */ + public static final String NOTEBOOK = "hasAuthority('ROLE_notebook')"; + public static final String NOTEBOOK_CREATE = "hasAuthority('ROLE_notebook:create')"; + public static final String NOTEBOOK_UPDATE = "hasAuthority('ROLE_notebook:update')"; + public static final String NOTEBOOK_OPEN = "hasAuthority('ROLE_notebook:open')"; + public static final String NOTEBOOK_START = "hasAuthority('ROLE_notebook:start')"; + public static final String NOTEBOOK_STOP = "hasAuthority('ROLE_notebook:stop')"; + public static final String NOTEBOOK_DELETE = "hasAuthority('ROLE_notebook:delete')"; + + /** + * 算法管理 + */ + public static final String DEVELOPMENT_ALGORITHM = "hasAuthority('ROLE_development:algorithm')"; + public static final String DEVELOPMENT_ALGORITHM_CREATE = "hasAuthority('ROLE_development:algorithm:create')"; + public static final String DEVELOPMENT_ALGORITHM_EDIT = "hasAuthority('ROLE_development:algorithm:edit')"; + public static final String DEVELOPMENT_ALGORITHM_DELETE = "hasAuthority('ROLE_development:algorithm:delete')"; + + /** + * 训练管理 + */ + public static final String TRAINING_JOB = "hasAuthority('ROLE_training:job')"; + public static final String TRAINING_JOB_CREATE = "hasAuthority('ROLE_training:job:create')"; + public static final String TRAINING_JOB_UPDATE = "hasAuthority('ROLE_training:job:update')"; + public static final String TRAINING_JOB_DELETE = "hasAuthority('ROLE_training:job:delete')"; + + + public static final String MODEL_MODEL = "hasAuthority('ROLE_model:model')"; + public static final String MODEL_MODEL_CREATE = "hasAuthority('ROLE_model:model:create')"; + public static final String MODEL_MODEL_EDIT = "hasAuthority('ROLE_model:model:edit')"; + public static final String MODEL_MODEL_DELETE = "hasAuthority('ROLE_model:model:delete')"; + + /** + * 模型版本管理 + */ + public static final String MODEL_BRANCH = "hasAuthority('ROLE_model:branch')"; + public static final String MODEL_BRANCH_CREATE = "hasAuthority('ROLE_model:branch:create')"; + public static final String MODEL_BRANCH_DELETE = "hasAuthority('ROLE_model:branch:delete')"; + public static final String MODEL_BRANCH_CONVERT_PRESET = "hasAuthority('ROLE_model:branch:convertPreset')"; + public static final String MODEL_BRANCH_CONVERT_ONNX = "hasAuthority('ROLE_model:branch:convertOnnx')"; + + /** + * 模型优化 + */ + public static final String MODEL_OPTIMIZE = "hasAuthority('ROLE_model:optimize')"; + public static final String MODEL_OPTIMIZE_CREATE = "hasAuthority('ROLE_model:optimize:createTask')"; + public static final String MODEL_OPTIMIZE_SUBMIT_TASK = "hasAuthority('ROLE_model:optimize:submitTask')"; + public static final String MODEL_OPTIMIZE_SUBMIT_TASK_INSTANCE = "hasAuthority('ROLE_model:optimize:submitTaskInstance')"; + public static final String MODEL_OPTIMIZE_CANCEL_TASK_INSTANCE = "hasAuthority('ROLE_model:optimize:cancelTaskInstance')"; + public static final String MODEL_OPTIMIZE_EDIT = "hasAuthority('ROLE_model:optimize:editTask')"; + public static final String MODEL_OPTIMIZE_DELETE_TASK = "hasAuthority('ROLE_model:optimize:deleteTask')"; + public static final String MODEL_OPTIMIZE_DELETE_TASK_INSTANCE = "hasAuthority('ROLE_model:optimize:deleteTaskInstance')"; + + /** + * 控制台 + */ + public static final String SYSTEM_NODE = "hasAuthority('ROLE_system:node')"; + public static final String SYSTEM_LOG = "hasAuthority('ROLE_system:log')"; + public static final String SYSTEM_TEAM = "hasAuthority('ROLE_system:team')"; + + /** + * 云端Serving + */ + public static final String SERVING = "hasAuthority('ROLE_serving')"; + public static final String SERVING_BATCH = "hasAuthority('ROLE_serving:batch')"; + public static final String SERVING_BATCH_CREATE = "hasAuthority('ROLE_serving:batch:create')"; + public static final String SERVING_BATCH_EDIT = "hasAuthority('ROLE_serving:batch:edit')"; + public static final String SERVING_BATCH_START = "hasAuthority('ROLE_serving:batch:start')"; + public static final String SERVING_BATCH_STOP = "hasAuthority('ROLE_serving:batch:stop')"; + public static final String SERVING_BATCH_DELETE = "hasAuthority('ROLE_serving:batch:delete')"; + public static final String SERVING_DEPLOYMENT = "hasAuthority('ROLE_serving:online')"; + public static final String SERVING_DEPLOYMENT_CREATE = "hasAuthority('ROLE_serving:online:create')"; + public static final String SERVING_DEPLOYMENT_EDIT = "hasAuthority('ROLE_serving:online:edit')"; + public static final String SERVING_DEPLOYMENT_DELETE = "hasAuthority('ROLE_serving:online:delete')"; + public static final String SERVING_DEPLOYMENT_START = "hasAuthority('ROLE_serving:online:start')"; + public static final String SERVING_DEPLOYMENT_STOP = "hasAuthority('ROLE_serving:online:stop')"; + + /** + * 镜像管理 + */ + public static final String IMAGE = "hasAuthority('ROLE_training:image')"; + public static final String IMAGE_UPLOAD = "hasAuthority('ROLE_training:image:upload')"; + public static final String IMAGE_EDIT = "hasAuthority('ROLE_training:image:edit')"; + public static final String IMAGE_DELETE = "hasAuthority('ROLE_training:image:delete')"; + + /** + * 度量管理 + */ + public static final String MEASURE = "hasAuthority('ROLE_atlas:measure')"; + public static final String MEASURE_CREATE = "hasAuthority('ROLE_atlas:measure:create')"; + public static final String MEASURE_EDIT = "hasAuthority('ROLE_atlas:measure:edit')"; + public static final String MEASURE_DELETE = "hasAuthority('ROLE_atlas:measure:delete')"; + + /** + * 控制台:用户组管理 + */ + public static final String USER_GROUP_CREATE = "hasAuthority('ROLE_system:userGroup:create')"; + public static final String USER_GROUP_EDIT = "hasAuthority('ROLE_system:userGroup:edit')"; + public static final String USER_GROUP_DELETE = "hasAuthority('ROLE_system:userGroup:delete')"; + public static final String USER_GROUP_EDIT_USER = "hasAuthority('ROLE_system:userGroup:editUser')"; + public static final String USER_GROUP_EDIT_USER_ROLE = "hasAuthority('ROLE_system:userGroup:editUserRole')"; + public static final String USER_GROUP_EDIT_USER_STATE = "hasAuthority('ROLE_system:userGroup:editUserState')"; + public static final String USER_GROUP_DELETE_USER = "hasAuthority('ROLE_system:userGroup:deleteUser')"; + + /** + * 控制台:用户管理 + */ + public static final String USER_CREATE = "hasAuthority('ROLE_system:user:create')"; + public static final String USER_EDIT = "hasAuthority('ROLE_system:user:edit')"; + public static final String USER_DELETE = "hasAuthority('ROLE_system:user:delete')"; + public static final String USER_DOWNLOAD = "hasAuthority('ROLE_system:user:download')"; + + /** + * 控制台:角色管理 + */ + public static final String ROLE = "hasAuthority('ROLE_system:role')"; + public static final String ROLE_CREATE = "hasAuthority('ROLE_system:role:create')"; + public static final String ROLE_EDIT = "hasAuthority('ROLE_system:role:edit')"; + public static final String ROLE_DELETE = "hasAuthority('ROLE_system:role:delete')"; + public static final String ROLE_DWONLOAD = "hasAuthority('ROLE_system:role:download')"; + public static final String ROLE_MENU = "hasAuthority('ROLE_system:role:menu')"; + public static final String ROLE_AUTH = "hasAuthority('ROLE_system:role:auth')"; + + /** + * 控制台:权限组管理 + */ + public static final String AUTH_CODE = "hasAuthority('ROLE_system:authCode')"; + public static final String AUTH_CODE_CREATE = "hasAuthority('ROLE_system:authCode:create')"; + public static final String AUTH_CODE_EDIT = "hasAuthority('ROLE_system:authCode:edit')"; + public static final String AUTH_CODE_DELETE = "hasAuthority('ROLE_system:authCode:delete')"; + + /** + * 控制台:权限管理 + */ + public static final String PERMISSION = "hasAuthority('ROLE_system:permission')"; + public static final String PERMISSION_CREATE = "hasAuthority('ROLE_system:permission:create')"; + public static final String PERMISSION_EDIT = "hasAuthority('ROLE_system:permission:edit')"; + public static final String PERMISSION_DELETE = "hasAuthority('ROLE_system:permission:delete')"; + + /** + * 控制台:菜单管理 + */ + public static final String MENU = "hasAuthority('ROLE_system:menu')"; + public static final String MENU_CREATE = "hasAuthority('ROLE_system:menu:create')"; + public static final String MENU_EDIT = "hasAuthority('ROLE_system:menu:edit')"; + public static final String MENU_DELETE = "hasAuthority('ROLE_system:menu:delete')"; + public static final String MENU_DOWNLOAD = "hasAuthority('ROLE_system:menu:download')"; + + /** + * 控制台:字典管理 + */ + public static final String DICT = "hasAuthority('ROLE_system:dict')"; + public static final String DICT_CREATE = "hasAuthority('ROLE_system:dict:create')"; + public static final String DICT_EDIT = "hasAuthority('ROLE_system:dict:edit')"; + public static final String DICT_DELETE = "hasAuthority('ROLE_system:dict:delete')"; + public static final String DICT_DOWNLOAD = "hasAuthority('ROLE_system:dict:download')"; + + /** + * 控制台:字典详情管理 + */ + public static final String DICT_DETAIL_CREATE = "hasAuthority('ROLE_system:dictDetail:create')"; + public static final String DICT_DETAIL_EDIT = "hasAuthority('ROLE_system:dictDetail:edit')"; + public static final String DICT_DETAIL_DELETE = "hasAuthority('ROLE_system:dictDetail:delete')"; + + /** + * 控制台:资源规格管理 + */ + public static final String SPECS_CREATE = "hasAuthority('ROLE_system:specs:create')"; + public static final String SPECS_EDIT = "hasAuthority('ROLE_system:specs:edit')"; + public static final String SPECS_DELETE = "hasAuthority('ROLE_system:specs:delete')"; + + private Permissions() { + } +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/constant/ResponseCode.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/constant/ResponseCode.java new file mode 100644 index 0000000..2c52142 --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/constant/ResponseCode.java @@ -0,0 +1,34 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.constant; + +/** + * @description 业务返回状态码 + * @date 2020-02-23 + */ +public class ResponseCode { + public static Integer SUCCESS = 200; + public static Integer UNAUTHORIZED = 401; + public static Integer TOKEN_ERROR = 403; + public static Integer ERROR = 10000; + public static Integer ENTITY_NOT_EXIST = 10001; + public static Integer BADREQUEST = 10002; + public static Integer SERVICE_ERROR = 10003; + public static Integer DOCKER_ERROR = 10004; + +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/constant/StringConstant.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/constant/StringConstant.java new file mode 100644 index 0000000..fd10aee --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/constant/StringConstant.java @@ -0,0 +1,115 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.constant; + +import java.util.regex.Pattern; + +/** + * @description 字符串constant + * @date 2020-05-14 + */ +public final class StringConstant { + + public static final String MSIE = "MSIE"; + public static final String MOZILLA = "Mozilla"; + public static final String REQUEST_METHOD_GET = "GET"; + + /** + * 字母、数字、英文横杠和下划线匹配 + */ + public static final String REGEXP_NAME = "^[a-zA-Z0-9\\-\\_\\u4e00-\\u9fa5]+$"; + + /** + * 字母、数字、英文横杠、英文.号和下划线 + */ + public static final String REGEXP_TAG = "^[a-zA-Z0-9\\-\\_\\.]+$"; + + /** + * 算法名称支持字母、数字、汉字、英文横杠和下划线 + */ + public static final String REGEXP_ALGORITHM = "^[a-zA-Z0-9\\-\\_\\u4e00-\\u9fa5]+$"; + + /** + * 资源规格名称支持字母、数字、汉字、英文横杠、下划线和空白字符 + */ + public static final String REGEXP_SPECS = "^[a-zA-Z0-9\\-\\_\\s\\u4e00-\\u9fa5]+$"; + + /** + * 整数匹配 + */ + public static final Pattern PATTERN_NUM = Pattern.compile("^[-\\+]?[\\d]*$"); + + + /** + * 公共字段 + */ + public static final String CREATE_TIME = "createTime"; + public static final String UPDATE_TIME = "updateTime"; + public static final String UPDATE_USER_ID = "updateUserId"; + public static final String CREATE_USER_ID = "createUserId"; + public static final String ORIGIN_USER_ID = "originUserId"; + public static final String DELETED = "deleted"; + public static final String UTF8 = "utf-8"; + public static final String JSON_REQUEST = "application/json"; + public static final String CREATE_TIME_SQL = "create_time"; + public static final String UPDATE_TIME_SQL = "update_time"; + public static final String COMMON = "common"; + /** + * k8s回调公共路径 + */ + public static final String K8S_CALLBACK_URI = "/api/k8s/callback/pod"; + /** + * 资源回收远程调用路径 + */ + public static final String RECYCLE_CALL_URI = "/api/recycle/call/"; + public static final String K8S_CALLBACK_PATH_DEPLOYMENT = "/api/k8s/callback/deployment"; + public static final String MULTIPART = "multipart/form-data"; + /** + * 分页内容 + */ + public static final String RESULT = "result"; + /** + * 排序规则 + */ + public static final String SORT_ASC = "asc"; + + public static final String SORT_DESC = "desc"; + + public static final String QUERY = "query"; + + public static final String NGINX_LOWERCASE = "nginx"; + + public static final String TRUE_LOWERCASE = "true"; + + public static final String GRPC_CAPITALIZE = "GRPC"; + + public static final String ID = "id"; + + public static final String START_LOW = "start"; + public static final String END_LOW = "end"; + public static final String STEP_LOW = "step"; + + /** + * 测试环境 + */ + public static final String PROFILE_ACTIVE_TEST = "test"; + + + private StringConstant() { + } +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/constant/SymbolConstant.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/constant/SymbolConstant.java new file mode 100644 index 0000000..4190208 --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/constant/SymbolConstant.java @@ -0,0 +1,55 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.constant; + +/** + * @description 符号常量 + * @date 2020-5-29 + */ +public class SymbolConstant { + public static final String SLASH = "/"; + public static final String COMMA = ","; + public static final String COLON = ":"; + public static final String LINEBREAK = "\n"; + public static final String BLANK = ""; + public static final String QUESTION = "?"; + public static final String ZERO = "0"; + public static final String DOT = "."; + public static final String TOKEN = "token"; + public static final String GET = "get"; + public static final String SET = "set"; + public static final String HTTP = "http"; + public static final String GRPC = "grpc"; + public static final String BRACKETS = "{}"; + public static final String BACKSLASH = "\\"; + public static final String BACKSLASH_MARK= "\\\""; + public static final String DOUBLE_MARK= "\"\""; + public static final String MARK= "\""; + public static final String FLAG_EQUAL = "="; + public static final String LEFT_PARENTHESIS = "["; + public static final String RIGHT_PARENTHESIS = "]"; + public static final String APOSTROPHE = "'"; + public static final String HYPHEN = "-"; + public static final String EVENT_SEPARATOR = "&&"; + public static final String POST = "POST"; + public static final String HTTP_SLASH = "http://"; + + private SymbolConstant() { + } + +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/constant/UserConstant.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/constant/UserConstant.java new file mode 100644 index 0000000..c382617 --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/constant/UserConstant.java @@ -0,0 +1,94 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.constant; + + +/** + * @description 用户常量类 + * @date 2020-06-01 + */ +public class UserConstant { + + public final static String SEX_MEN = "男"; + + public final static String SEX_WOMEN = "女"; + + /** + * redis key + */ + /** + * 用户发送邮件限制次数 + */ + public final static String USER_EMAIL_LIMIT_COUNT = "user:email:limit:count:"; + + /** + * 用户邮箱注册信息发送验证码 + */ + public final static String USER_EMAIL_REGISTER = "user:email:register:"; + + /** + * 用户邮箱激修改信息发送验证码 + */ + public final static String USER_EMAIL_UPDATE = "user:email:update:"; + + /** + * 用户邮箱忘记发送验证码 + */ + public final static String USER_EMAIL_RESET_PASSWORD = "user:email:reset-password:"; + + /** + * 用户其他操作发送验证码 + */ + public final static String USER_EMAIL_OTHER = "user:email:other:"; + + /** + * 一天的秒数 24x60x60 + */ + public final static long DATE_SECOND = 86400; + + /** + * 发邮件次数 + */ + public final static int COUNT_SENT_EMAIL = 3; + + /** + * 账号密码不正确登录失败次数 + */ + public final static int COUNT_LOGIN_FAIL = 5; + + /** + * 用户登录限制次数 + */ + public final static String USER_LOGIN_LIMIT_COUNT = "user:login:limit:count:"; + + /** + * 初始化管理员ID + */ + public final static Integer ADMIN_USER_ID = 1; + + /** + * 管理员角色ID + */ + public final static int ADMIN_ROLE_ID = 1; + + /** + * 注册用户角色ID + */ + public final static int REGISTER_ROLE_ID = 2; + +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/context/DataContext.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/context/DataContext.java new file mode 100644 index 0000000..b831c3b --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/context/DataContext.java @@ -0,0 +1,62 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.context; + + +import org.dubhe.biz.base.dto.CommonPermissionDataDTO; + +/** + * @description 共享上下文数据集信息 + * @date 2020-11-25 + */ +public class DataContext { + + /** + * 私有化构造参数 + */ + private DataContext() { + } + + private static final ThreadLocal CONTEXT = new ThreadLocal<>(); + + /** + * 存放数据集信息 + * + * @param datasetVO + */ + public static void set(CommonPermissionDataDTO datasetVO) { + CONTEXT.set(datasetVO); + } + + /** + * 获取用户信息 + * + * @return + */ + public static CommonPermissionDataDTO get() { + return CONTEXT.get(); + } + + /** + * 清除当前线程内引用,防止内存泄漏 + */ + public static void remove() { + CONTEXT.remove(); + } + +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/context/UserContext.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/context/UserContext.java new file mode 100644 index 0000000..4a764e5 --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/context/UserContext.java @@ -0,0 +1,76 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.context; + +import lombok.Data; +import org.dubhe.biz.base.dto.SysRoleDTO; + +import java.io.Serializable; +import java.util.List; + +/** + * @description 用户上下文(当前登录用户) + * 可根据需要自定义改造 + * @date 2020-12-07 + */ +@Data +public class UserContext implements Serializable { + + private static final long serialVersionUID = 1L; + + /** + * 用户ID + */ + private Long id; + /** + * 用户名称 + */ + private String username; + /** + * 密码 + */ + private String password; + /** + * 邮箱 + */ + private String email; + /** + * 性别 + */ + private String sex; + /** + * 手机号 + */ + private String phone; + /** + * 昵称 + */ + private String nickName; + /** + * 是否启用 + */ + private Boolean enabled; + /** + * 角色 + */ + private List roles; + /** + * 头像路径 + */ + private String userAvatarPath; + +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/BaseDTO.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/BaseDTO.java new file mode 100644 index 0000000..d685032 --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/BaseDTO.java @@ -0,0 +1,48 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.dto; + +import lombok.Getter; +import lombok.Setter; + +import java.io.Serializable; +import java.sql.Timestamp; + +/** + * @description DTO基础类 + * @date 2020-03-15 + */ +@Getter +@Setter +public class BaseDTO implements Serializable { + + private Boolean deleted; + + private Timestamp createTime; + + private Timestamp updateTime; + + @Override + public String toString() { + return "BaseDTO{" + + "deleted=" + deleted + + ", createTime=" + createTime + + ", updateTime=" + updateTime + + '}'; + } +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/BaseImageDTO.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/BaseImageDTO.java new file mode 100644 index 0000000..975efa4 --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/BaseImageDTO.java @@ -0,0 +1,47 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.dto; + +import lombok.Data; +import lombok.experimental.Accessors; + +import javax.validation.constraints.NotBlank; +import java.io.Serializable; + +/** + * @description 镜像基础类DTO + * @date 2020-07-14 + */ +@Data +@Accessors(chain = true) +public class BaseImageDTO implements Serializable { + + private static final long serialVersionUID = 1L; + + /** + * 镜像版本 + */ + @NotBlank(message = "镜像版本不能为空") + private String imageTag; + + /** + * 镜像名称 + */ + @NotBlank(message = "镜像名称不能为空") + private String imageName; + +} \ No newline at end of file diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/CommonPermissionDataDTO.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/CommonPermissionDataDTO.java new file mode 100644 index 0000000..0887463 --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/CommonPermissionDataDTO.java @@ -0,0 +1,48 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.dto; + +import lombok.Builder; +import lombok.Data; + +import java.io.Serializable; +import java.util.Set; + +/** + * @description 公共权限信息DTO + * @date 2020-11-25 + */ +@Data +@Builder +public class CommonPermissionDataDTO implements Serializable { + + /** + * 资源拥有者ID + */ + private Long id; + + /** + * 公共类型 + */ + private Boolean type; + + /** + * 资源所属用户ids + */ + private Set resourceUserIds; + +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/DictDetailQueryByLabelNameDTO.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/DictDetailQueryByLabelNameDTO.java new file mode 100644 index 0000000..1511999 --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/DictDetailQueryByLabelNameDTO.java @@ -0,0 +1,35 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.dto; + +import lombok.Data; + +import javax.validation.constraints.NotBlank; +import java.io.Serializable; + +/** + * @description 根据名称查询字典详情 + * @date 2020-12-23 + */ +@Data +public class DictDetailQueryByLabelNameDTO implements Serializable { + + private static final long serialVersionUID = 1L; + + @NotBlank(message = "Label名称不能为空") + private String name; +} \ No newline at end of file diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/ModelOptAlgorithmCreateDTO.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/ModelOptAlgorithmCreateDTO.java new file mode 100644 index 0000000..df7014c --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/ModelOptAlgorithmCreateDTO.java @@ -0,0 +1,48 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.dto; + +import lombok.Data; +import lombok.experimental.Accessors; +import org.dubhe.biz.base.constant.NumberConstant; +import org.dubhe.biz.base.constant.StringConstant; +import org.hibernate.validator.constraints.Length; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Pattern; +import java.io.Serializable; + +/** + * @description 模型优化上传算法入参 + * @date 2021-01-06 + */ +@Data +@Accessors(chain = true) +public class ModelOptAlgorithmCreateDTO implements Serializable { + + private static final long serialVersionUID = 1L; + + @NotBlank(message = "算法名称不能为空") + @Length(max = NumberConstant.NUMBER_32, message = "算法名称-输入长度不能超过32个字符") + @Pattern(regexp = StringConstant.REGEXP_ALGORITHM, message = "算法名称支持字母、数字、汉字、英文横杠和下划线") + private String name; + + @NotBlank(message = "代码目录不能为空") + @Length(max = NumberConstant.NUMBER_64, message = "代码目录-输入长度不能超过128个字符") + private String path; + +} \ No newline at end of file diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/NoteBookAlgorithmQueryDTO.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/NoteBookAlgorithmQueryDTO.java new file mode 100644 index 0000000..2fb230a --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/NoteBookAlgorithmQueryDTO.java @@ -0,0 +1,41 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.dto; + +import lombok.Data; + +import javax.validation.constraints.NotEmpty; +import java.io.Serializable; +import java.util.List; + +/** + * @description 算法查询notebook对象 + * @date 2020-12-14 + */ +@Data +public class NoteBookAlgorithmQueryDTO implements Serializable { + + private static final long serialVersionUID = 1L; + + /** + * 算法ID + */ + @NotEmpty(message = "算法ID不能为空") + private List algorithmIdList; + +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/NoteBookAlgorithmUpdateDTO.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/NoteBookAlgorithmUpdateDTO.java new file mode 100644 index 0000000..310f9db --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/NoteBookAlgorithmUpdateDTO.java @@ -0,0 +1,49 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.dto; + +import lombok.Data; + +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; +import java.io.Serializable; +import java.util.List; + +/** + * @description 算法更新notebook对象 + * @date 2020-12-14 + */ +@Data +public class NoteBookAlgorithmUpdateDTO implements Serializable { + + private static final long serialVersionUID = 1L; + + /** + * NoteBookID + */ + @NotEmpty(message = "NoteBookID不能为空") + private List notebookIdList; + + /** + * 算法ID + */ + @NotNull(message = "算法ID不能为空") + private Long algorithmId; + + +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/Oauth2TokenDTO.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/Oauth2TokenDTO.java new file mode 100644 index 0000000..77a349a --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/Oauth2TokenDTO.java @@ -0,0 +1,49 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.dto; + +import lombok.Builder; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.io.Serializable; + +/** + * @description Oauth2获取Token返回信息封装 + * @date 2020-05-08 + */ +@Data +@EqualsAndHashCode(callSuper = false) +@Builder +public class Oauth2TokenDTO implements Serializable { + /** + * 访问令牌 + */ + private String token; + /** + * 刷令牌 + */ + private String refreshToken; + /** + * 访问令牌头前缀 + */ + private String tokenHead; + /** + * 有效时间(秒 + */ + private int expiresIn; +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/PtDatasetSmallDTO.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/PtDatasetSmallDTO.java new file mode 100644 index 0000000..50fed5e --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/PtDatasetSmallDTO.java @@ -0,0 +1,32 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.dto; + +import lombok.Data; + +import java.io.Serializable; + +/** + * @description 数据集 + * @date 2020-03-17 + */ +@Data +public class PtDatasetSmallDTO implements Serializable { + private Long id; + private String name; +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/PtImageQueryUrlDTO.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/PtImageQueryUrlDTO.java new file mode 100644 index 0000000..9c7f7bc --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/PtImageQueryUrlDTO.java @@ -0,0 +1,40 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.dto; + +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.experimental.Accessors; + +/** + * @description 查询镜像路径 + * @date 2020-12-14 + */ +@Data +@Accessors(chain = true) +@EqualsAndHashCode +public class PtImageQueryUrlDTO { + + private Integer imageResource; + + private String imageName; + + private String imageTag; + + private Integer projectType; + +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/PtModelBranchConditionQueryDTO.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/PtModelBranchConditionQueryDTO.java new file mode 100644 index 0000000..a12fd36 --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/PtModelBranchConditionQueryDTO.java @@ -0,0 +1,39 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.dto; + +import lombok.Data; + +import javax.validation.constraints.NotNull; +import java.io.Serializable; + +/** + * @description 条件查询模型版本 + * @date 2020-03-24 + */ +@Data +public class PtModelBranchConditionQueryDTO implements Serializable { + + private static final long serialVersionUID = 1L; + + @NotNull(message = "父ID不能为空") + private Long parentId; + + private String modelAddress; + +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/PtModelBranchQueryByIdDTO.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/PtModelBranchQueryByIdDTO.java new file mode 100644 index 0000000..2f555bc --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/PtModelBranchQueryByIdDTO.java @@ -0,0 +1,38 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.dto; + +import lombok.Data; + +import javax.validation.constraints.NotNull; +import java.io.Serializable; + +/** + * @description 根据模型版本id查询模型版本详情入参 + * @date 2020-12-16 + */ +@Data +public class PtModelBranchQueryByIdDTO implements Serializable { + + private static final long serialVersionUID = 1L; + + /** + * 模型版本ID + */ + @NotNull(message = "模型版本ID不能为空") + private Long id; +} \ No newline at end of file diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/PtModelInfoConditionQueryDTO.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/PtModelInfoConditionQueryDTO.java new file mode 100644 index 0000000..836981c --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/PtModelInfoConditionQueryDTO.java @@ -0,0 +1,54 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.dto; + +import lombok.Data; +import lombok.experimental.Accessors; +import org.dubhe.biz.base.utils.PtModelUtil; + +import javax.validation.constraints.Max; +import javax.validation.constraints.Min; +import javax.validation.constraints.NotNull; +import java.io.Serializable; +import java.util.Set; + +/** + * @description 模型条件查询 + * @date 2020-12-17 + */ +@Data +@Accessors +public class PtModelInfoConditionQueryDTO implements Serializable { + + private static final long serialVersionUID = 1L; + + /** + * 模型是否为预置模型(0默认模型,1预置模型) + * + */ + @Min(value = PtModelUtil.NUMBER_ZERO, message = "模型类型错误") + @Max(value = PtModelUtil.NUMBER_TWO, message = "模型类型错误") + @NotNull(message = "modelResource不能为空") + private Integer modelResource; + + /** + * 模型id + */ + @NotNull(message = "id不能为空") + private Set ids; + +} \ No newline at end of file diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/PtModelInfoQueryByIdDTO.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/PtModelInfoQueryByIdDTO.java new file mode 100644 index 0000000..c05b5db --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/PtModelInfoQueryByIdDTO.java @@ -0,0 +1,38 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.dto; + +import lombok.Data; + +import javax.validation.constraints.NotNull; +import java.io.Serializable; + +/** + * @description 根据模型id查询模型详情入参 + * @date 2020-12-16 + */ +@Data +public class PtModelInfoQueryByIdDTO implements Serializable { + + private static final long serialVersionUID = 1L; + + /** + * 模型ID + */ + @NotNull(message = "模型ID不能为空") + private Long id; +} \ No newline at end of file diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/PtModelStatusQueryDTO.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/PtModelStatusQueryDTO.java new file mode 100644 index 0000000..a6af7b6 --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/PtModelStatusQueryDTO.java @@ -0,0 +1,45 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.dto; + +import lombok.Data; +import lombok.experimental.Accessors; + +import java.io.Serializable; +import java.util.List; + +/** + * @description 查询模型对应训练状态 + * @date 2021-03-04 + */ +@Data +@Accessors(chain = true) +public class PtModelStatusQueryDTO implements Serializable { + + private static final long serialVersionUID = 1L; + + /** + * 模型id + */ + private List modelIds; + + /** + * 模型对应版本id + */ + private List modelBranchIds; + +} \ No newline at end of file diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/PtStorageSmallDTO.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/PtStorageSmallDTO.java new file mode 100644 index 0000000..0e85478 --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/PtStorageSmallDTO.java @@ -0,0 +1,33 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.dto; + +import lombok.Data; + +import java.io.Serializable; + +/** + * @description 存储 + * @date 2020-03-17 + */ +@Data +public class PtStorageSmallDTO implements Serializable { + private Long id; + private String name; + +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/PtTrainDataSourceStatusQueryDTO.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/PtTrainDataSourceStatusQueryDTO.java new file mode 100644 index 0000000..5d07628 --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/PtTrainDataSourceStatusQueryDTO.java @@ -0,0 +1,41 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.dto; + +import lombok.Data; +import lombok.experimental.Accessors; + +import java.io.Serializable; +import java.util.List; + +/** + * @description 查询数据集对应训练状态查询条件 + * @date 2020-05-21 + */ +@Data +@Accessors(chain = true) +public class PtTrainDataSourceStatusQueryDTO implements Serializable { + + private static final long serialVersionUID = 1L; + + /** + * 数据集路径 + */ + private List dataSourcePath; + +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/QueryResourceSpecsDTO.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/QueryResourceSpecsDTO.java new file mode 100644 index 0000000..08e48de --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/QueryResourceSpecsDTO.java @@ -0,0 +1,54 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.dto; + +import lombok.Data; +import lombok.experimental.Accessors; +import org.dubhe.biz.base.constant.MagicNumConstant; +import org.hibernate.validator.constraints.Length; + +import javax.validation.constraints.Max; +import javax.validation.constraints.Min; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; +import java.io.Serializable; + +/** + * @description 查询资源规格 + * @date 2021-06-02 + */ +@Data +@Accessors(chain = true) +public class QueryResourceSpecsDTO implements Serializable { + + private static final long serialVersionUID = 1L; + + /** + * 规格名称 + */ + @NotBlank(message = "规格名称不能为空") + @Length(max = MagicNumConstant.THIRTY_TWO, message = "规格名称错误") + private String specsName; + + /** + * 所属业务场景(0:通用,1:dubhe-notebook,2:dubhe-train,3:dubhe-serving) + */ + @NotNull(message = "所属业务场景不能为空") + @Min(value = MagicNumConstant.ZERO, message = "所属业务场景错误") + @Max(value = MagicNumConstant.THREE, message = "所属业务场景错误") + private Integer module; +} \ No newline at end of file diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/SysPermissionDTO.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/SysPermissionDTO.java new file mode 100644 index 0000000..c16c798 --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/SysPermissionDTO.java @@ -0,0 +1,38 @@ +/** + * Copyright 2019-2020 Zheng Jie + * + * Licensed 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 org.dubhe.biz.base.dto; + +import lombok.Data; + +import java.io.Serializable; + + +/** + * @description 系统权限DTO + * @date 2020-06-29 + */ +@Data +public class SysPermissionDTO implements Serializable { + + private static final long serialVersionUID = -3836401769559845765L; + + private Long roleId; + + private String permission; + + private String name; + +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/SysRoleDTO.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/SysRoleDTO.java new file mode 100644 index 0000000..33e6270 --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/SysRoleDTO.java @@ -0,0 +1,48 @@ +/** + * Copyright 2019-2020 Zheng Jie + * + * Licensed 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 org.dubhe.biz.base.dto; + +import lombok.Data; + +import java.io.Serializable; +import java.util.List; + + +/** + * @description 系统角色DTO + * @date 2020-06-29 + */ +@Data +public class SysRoleDTO implements Serializable { + + private static final long serialVersionUID = -3836401769559845765L; + + /** + * 权限列表 + */ + private List permissions; + + /** + * 角色名称 + */ + private String name; + + /** + * 角色ID + */ + private Long id; + +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/TeamDTO.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/TeamDTO.java new file mode 100644 index 0000000..7dc48d8 --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/TeamDTO.java @@ -0,0 +1,53 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.dto; + +import lombok.Data; +import org.dubhe.biz.base.dto.UserSmallDTO; + +import java.io.Serializable; +import java.sql.Timestamp; +import java.util.List; + +/** + * @description 团队转换DTO + * @date 2020-06-01 + */ +@Data +public class TeamDTO implements Serializable { + + private static final long serialVersionUID = -7049447715255649751L; + private Long id; + + private String name; + + private Boolean enabled; + + private Long pid; + + /** + * 团队成员 + */ + private List teamUserList; + + private Timestamp createTime; + + public String getLabel() { + return name; + } +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/TeamSmallDTO.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/TeamSmallDTO.java new file mode 100644 index 0000000..c916f15 --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/TeamSmallDTO.java @@ -0,0 +1,36 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.dto; + +import lombok.Data; + +import java.io.Serializable; + +/** + * @description 团队DTO + * @date 2020-06-01 + */ +@Data +public class TeamSmallDTO implements Serializable { + + private static final long serialVersionUID = 7811877555052402740L; + + private Long id; + + private String name; +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/TrainAlgorithmSelectAllBatchIdDTO.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/TrainAlgorithmSelectAllBatchIdDTO.java new file mode 100644 index 0000000..4f4ea4a --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/TrainAlgorithmSelectAllBatchIdDTO.java @@ -0,0 +1,36 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.dto; + +import lombok.Data; + +import javax.validation.constraints.NotNull; +import java.io.Serializable; +import java.util.Set; + +/** + * @description 根据Id批量查询 + * @date 2020-12-23 + */ +@Data +public class TrainAlgorithmSelectAllBatchIdDTO implements Serializable { + + private static final long serialVersionUID = 1L; + + @NotNull(message = "id不能为空") + private Set ids; +} \ No newline at end of file diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/TrainAlgorithmSelectAllByIdDTO.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/TrainAlgorithmSelectAllByIdDTO.java new file mode 100644 index 0000000..aa45476 --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/TrainAlgorithmSelectAllByIdDTO.java @@ -0,0 +1,35 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.dto; + +import lombok.Data; + +import javax.validation.constraints.NotNull; +import java.io.Serializable; + +/** + * @description 根据Id查询所有数据(包含已被软删除的数据) + * @date 2020-12-23 + */ +@Data +public class TrainAlgorithmSelectAllByIdDTO implements Serializable { + + private static final long serialVersionUID = 1L; + + @NotNull(message = "id不能为空") + private Long id; +} \ No newline at end of file diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/TrainAlgorithmSelectByIdDTO.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/TrainAlgorithmSelectByIdDTO.java new file mode 100644 index 0000000..b831745 --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/TrainAlgorithmSelectByIdDTO.java @@ -0,0 +1,35 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.dto; + +import lombok.Data; + +import javax.validation.constraints.NotNull; +import java.io.Serializable; + +/** + * @description 根据Id查询 + * @date 2020-12-23 + */ +@Data +public class TrainAlgorithmSelectByIdDTO implements Serializable { + + private static final long serialVersionUID = 1L; + + @NotNull(message = "id不能为空") + private Long id; +} \ No newline at end of file diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/UserDTO.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/UserDTO.java new file mode 100644 index 0000000..1572a16 --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/UserDTO.java @@ -0,0 +1,63 @@ +/** + * Copyright 2019-2020 Zheng Jie + * + * Licensed 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 org.dubhe.biz.base.dto; + +import lombok.Data; + +import java.io.Serializable; +import java.sql.Timestamp; +import java.util.Date; +import java.util.List; + +/** + * @description 用户信息 + * @date 2020-06-29 + */ +@Data +public class UserDTO implements Serializable { + + private Long id; + + private String username; + + private String nickName; + + private String sex; + + private String email; + + private String phone; + + private Boolean enabled; + + private String remark; + + private Date lastPasswordResetTime; + + private Timestamp createTime; + + /** + * 头像路径 + */ + private String userAvatarPath; + + /** + * 角色 + */ + private List roles; + + +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/UserSmallDTO.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/UserSmallDTO.java new file mode 100644 index 0000000..d38065f --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/dto/UserSmallDTO.java @@ -0,0 +1,38 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.dto; + +import lombok.Data; + +/** + * @description 用户信息DTO + * @date 2020-06-01 + */ +@Data +public class UserSmallDTO { + private String username; + private String nickName; + + public UserSmallDTO() {} + + public UserSmallDTO(UserDTO userDTO) { + this.username = userDTO.getUsername(); + this.nickName = userDTO.getNickName(); + } + +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/enums/AlgorithmSourceEnum.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/enums/AlgorithmSourceEnum.java new file mode 100644 index 0000000..4018dad --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/enums/AlgorithmSourceEnum.java @@ -0,0 +1,46 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.enums; + +import lombok.Getter; + +/** + * @description 算法枚举类 + * @date 2020-05-12 + */ +@Getter +public enum AlgorithmSourceEnum { + + /** + * MINE 算法来源 我的算法 + */ + MINE(1, "MINE"), + /** + * PRE 算法来源 预置算法 + */ + PRE(2,"PRE"); + + private Integer status; + + private String message; + + AlgorithmSourceEnum(Integer status, String message) { + this.status = status; + this.message = message; + } +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/enums/AlgorithmStatusEnum.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/enums/AlgorithmStatusEnum.java new file mode 100644 index 0000000..9087728 --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/enums/AlgorithmStatusEnum.java @@ -0,0 +1,63 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.enums; + +/** + * @description 算法状态枚举 + * @date 2020-08-19 + */ +public enum AlgorithmStatusEnum { + + + /** + * 创建中 + */ + MAKING(0, "创建中"), + /** + * 创建成功 + */ + SUCCESS(1, "创建成功"), + /** + * 创建失败 + */ + FAIL(2, "创建失败"); + + + /** + * 编码 + */ + private Integer code; + + /** + * 描述 + */ + private String description; + + AlgorithmStatusEnum(int code, String description) { + this.code = code; + this.description = description; + } + + public Integer getCode() { + return code; + } + + public String getDescription() { + return description; + } +} + diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/enums/BaseErrorCodeEnum.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/enums/BaseErrorCodeEnum.java new file mode 100644 index 0000000..f942768 --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/enums/BaseErrorCodeEnum.java @@ -0,0 +1,71 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.enums; + +import lombok.Getter; +import org.dubhe.biz.base.exception.ErrorCode; + +/** + * @description 通用异常code + * @date 2020-11-26 + */ +@Getter +public enum BaseErrorCodeEnum implements ErrorCode { + + /** + * undefined error + */ + UNDEFINED(10000, "操作成功!"), + ERROR(10001, "操作失败!"), + ERROR_SYSTEM(10002, "系统繁忙!"), + UNAUTHORIZED(401, "无权访问!"), + /** + * system 模块异常码 + */ + SYSTEM_USERNAME_ALREADY_EXISTS(20000, "账号已存在!"), + SYSTEM_CODE_ALREADY_EXISTS(20001, "Code already exists!"), + SYSTEM_USER_IS_NOT_EXISTS(20002, "用户不存在!"), + SYSTEM_USER_ALREADY_REGISTER(20003, "账号已注册!"), + SYSTEM_USER_REGISTER_EMAIL_INFO_EXPIRED(20004, "邮箱验证码已过期!"), + SYSTEM_USER_EMAIL_ALREADY_EXISTS(20004, "该邮箱已被注册!"), + SYSTEM_USER_EMAIL_PASSWORD_ERROR(20005, "邮件密码错误!"), + SYSTEM_USER_EMAIL_CODE_CANNOT_EXCEED_TIMES(20006, "邮件发送不能超过三次!"), + SYSTEM_USER_EMAIL_OR_CODE_ERROR(20007, "邮箱地址或验证码错误、请重新输入!"), + SYSTEM_USER_IS_LOCKED(20008, "用户已锁定!"), + SYSTEM_USER_USERNAME_OR_PASSWORD_ERROR(20009, "账号或密码不正确!"), + SYSTEM_USER_USERNAME_IS_LOCKED(20010, "账号已锁定,6小时后解锁!"), + SYSTEM_USER_CANNOT_UPDATE_ADMIN(20011, "仅超级管理员可操作!"), + SYSTEM_USER_TOKEN_INFO_IS_NULL(20012, "登录信息不存在!"), + SYSTEM_USER_EMAIL_NOT_EXISTS(20013, "该邮箱未注册!"), + SYSTEM_USER_CANNOT_DELETE(20014, "系统默认用户不可删除!"), + SYSTEM_ROLE_CANNOT_DELETE(20015, "系统默认角色不可删除!"), + + DATASET_ADMIN_PERMISSION_ERROR(1310,"无此权限,请联系管理员"), + + ; + + + Integer code; + String msg; + + BaseErrorCodeEnum(Integer code, String msg) { + this.code = code; + this.msg = msg; + } + +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/enums/BizEnum.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/enums/BizEnum.java new file mode 100644 index 0000000..56579ff --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/enums/BizEnum.java @@ -0,0 +1,98 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.enums; + +import lombok.Getter; + +import java.util.HashMap; +import java.util.Map; + +/** + * @description 业务模块 + * @date 2020-05-25 + */ +@Getter +public enum BizEnum { + + /** + * 模型开发 + */ + NOTEBOOK("模型开发", "notebook", 0), + /** + * 算法管理 + */ + ALGORITHM("算法管理", "algorithm", 1), + /** + * 模型管理 + */ + MODEL("模型管理", "model", 2), + /** + * 模型优化 + */ + MODEL_OPT("模型优化管理","modelopt",6), + /** + * 云端Serving-在线服务 + */ + SERVING("云端Serving", "serving", 3), + /** + * 批量服务 + */ + BATCH_SERVING("批量服务", "batchserving", 4), + /** + * 度量管理 + */ + MEASURE("度量管理", "measure", 5); + + /** + * 业务模块名称 + */ + private String bizName; + /** + * 业务模块名称 + */ + private String bizCode; + /** + * 业务源代号 + */ + private Integer createResource; + + BizEnum(String bizName, String bizCode, Integer createResource) { + this.createResource = createResource; + this.bizName = bizName; + this.bizCode = bizCode; + } + + private static final Map RESOURCE_ENUM_MAP = new HashMap() { + { + for (BizEnum enums : BizEnum.values()) { + put(enums.getCreateResource(), enums); + } + } + }; + + /** + * 根据createResource获取BizEnum + * @param createResource + * @return + */ + public static BizEnum getByCreateResource(int createResource) { + return RESOURCE_ENUM_MAP.get(createResource); + } + + +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/enums/DatasetTypeEnum.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/enums/DatasetTypeEnum.java new file mode 100644 index 0000000..8f6ca3d --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/enums/DatasetTypeEnum.java @@ -0,0 +1,67 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.enums; + + +import lombok.Getter; + +/** + * @description 数据集类型 + * @date 2020-11-25 + */ +@Getter +public enum DatasetTypeEnum { + + /** + * 私有数据 + */ + PRIVATE(0, "私有数据"), + /** + * 团队数据 + */ + TEAM(1, "团队数据"), + /** + * 公开数据 + */ + PUBLIC(2, "公开数据"); + + DatasetTypeEnum(Integer value, String msg) { + this.value = value; + this.msg = msg; + } + + private Integer value; + + private String msg; + + /** + * 数据类型校验 用户web端接口调用时参数校验 + * + * @param value 数据类型 + * @return 参数校验结果 + */ + public static boolean isValid(Integer value) { + for (DatasetTypeEnum datasetTypeEnum : DatasetTypeEnum.values()) { + if (datasetTypeEnum.value.equals(value)) { + return true; + } + } + return false; + } + +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/enums/ImageSourceEnum.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/enums/ImageSourceEnum.java new file mode 100644 index 0000000..b8fbe6f --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/enums/ImageSourceEnum.java @@ -0,0 +1,50 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.enums; + +/** + * @description 镜像来源枚举类 + * @date 2020-07-15 + */ +public enum ImageSourceEnum { + MINE(0, "我的镜像"), + PRE(1, "预置镜像"); + + + /** + * 编码 + */ + private Integer code; + + /** + * 描述 + */ + private String description; + + ImageSourceEnum(int code, String description) { + this.code = code; + this.description = description; + } + + public Integer getCode() { + return code; + } + + public String getDescription() { + return description; + } +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/enums/ImageStateEnum.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/enums/ImageStateEnum.java new file mode 100644 index 0000000..27bdb8d --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/enums/ImageStateEnum.java @@ -0,0 +1,53 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.enums; + +/** + * @description 镜像运行状态枚举 + * @date 2020-07-15 + **/ +public enum ImageStateEnum { + + MAKING(0, "制作中"), + SUCCESS(1, "制作成功"), + FAIL(2, "制作失败"); + + + /** + * 编码 + */ + private Integer code; + + /** + * 描述 + */ + private String description; + + ImageStateEnum(int code, String description) { + this.code = code; + this.description = description; + } + + public Integer getCode() { + return code; + } + + public String getDescription() { + return description; + } +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/enums/ImageTypeEnum.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/enums/ImageTypeEnum.java new file mode 100644 index 0000000..9bd9e26 --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/enums/ImageTypeEnum.java @@ -0,0 +1,97 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.enums; + + +import lombok.Getter; + +import java.util.HashMap; +import java.util.Map; + +/** + * @description 镜像项目枚举类 + * @date 2020-12-11 + */ +@Getter +public enum ImageTypeEnum { + + /** + * notebook镜像 + */ + NOTEBOOK("notebook镜像", "notebook", 0), + + /** + * 训练镜像 + */ + TRAIN("训练镜像", "train", 1), + + /** + * Serving镜像 + */ + SERVING("Serving镜像", "serving", 2); + + /** + * 镜像项目名称 + */ + private String name; + /** + * 镜像项目代码 + */ + private String code; + /** + * 镜像项目类型 + */ + private Integer type; + + ImageTypeEnum(String name, String code, Integer type) { + this.name = name; + this.code = code; + this.type = type; + } + + private static final Map RESOURCE_ENUM_MAP = new HashMap() { + { + for (ImageTypeEnum enums : ImageTypeEnum.values()) { + put(enums.getType(), enums); + } + } + }; + + /** + * 根据type获取ImageTypeEnum + * @param type + * @return 镜像项目枚举对象 + */ + public static ImageTypeEnum getType(int type) { + return RESOURCE_ENUM_MAP.get(type); + } + + /** + * 根据type获取code + * + * @param type 镜像项目类型 + * @return String 镜像项目代码 + */ + public static String getType(Integer type) { + for (ImageTypeEnum typeEnum : ImageTypeEnum.values()) { + if (typeEnum.getType().equals(type)) { + return typeEnum.getCode(); + } + } + return null; + } +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/enums/MeasureStateEnum.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/enums/MeasureStateEnum.java new file mode 100644 index 0000000..6254440 --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/enums/MeasureStateEnum.java @@ -0,0 +1,53 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.enums; + +/** + * @description 度量文件生成状态 + * @date 2020-07-15 + **/ +public enum MeasureStateEnum { + + MAKING(0, "生成中"), + SUCCESS(1, "生成成功"), + FAIL(2, "生成失败"); + + + /** + * 编码 + */ + private Integer code; + + /** + * 描述 + */ + private String description; + + MeasureStateEnum(int code, String description) { + this.code = code; + this.description = description; + } + + public Integer getCode() { + return code; + } + + public String getDescription() { + return description; + } +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/enums/ModelResourceEnum.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/enums/ModelResourceEnum.java new file mode 100644 index 0000000..8fb80f6 --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/enums/ModelResourceEnum.java @@ -0,0 +1,66 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.enums; + +import lombok.Getter; + +/** + * @description 模型资源枚举类 + * @date 2020-11-19 + */ +@Getter +public enum ModelResourceEnum { + + /** + * 我的模型 + */ + MINE(0, "我的模型"), + /** + * 预置模型 + */ + PRESET(1, "预置模型"), + /** + * 炼知模型 + */ + ATLAS(2, "炼知模型"); + + private Integer type; + + private String description; + + ModelResourceEnum(Integer type, String description) { + this.type = type; + this.description = description; + } + + /** + * 根据类型获取枚举类对象 + * + * @param type 类型 + * @return 枚举类对象 + */ + public static ModelResourceEnum getType(Integer type) { + for (ModelResourceEnum modelResourceEnum : values()) { + if (modelResourceEnum.getType().compareTo(type) == 0) { + //获取指定的枚举 + return modelResourceEnum; + } + } + return null; + } +} \ No newline at end of file diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/enums/OperationTypeEnum.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/enums/OperationTypeEnum.java new file mode 100644 index 0000000..7061dd0 --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/enums/OperationTypeEnum.java @@ -0,0 +1,69 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.enums; + +import lombok.Getter; + +/** + * @description 操作类型枚举 + * @date 2020-11-25 + */ +@Getter +public enum OperationTypeEnum { + /** + * SELECT 查询类型 + */ + SELECT("select", "查询"), + + /** + * UPDATE 修改类型 + */ + UPDATE("update", "修改"), + + /** + * DELETE 删除类型 + */ + DELETE("delete", "删除"), + + /** + * LIMIT 禁止操作类型 + */ + LIMIT("limit", "禁止操作"), + + /** + * INSERT 新增类型 + */ + INSERT("insert", "新增类型"), + + ; + + /** + * 操作类型值 + */ + private String type; + + /** + * 操作类型备注 + */ + private String desc; + + OperationTypeEnum(String type, String desc) { + this.type = type; + this.desc = desc; + } +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/enums/ResourcesPoolTypeEnum.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/enums/ResourcesPoolTypeEnum.java new file mode 100644 index 0000000..582d85a --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/enums/ResourcesPoolTypeEnum.java @@ -0,0 +1,61 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.enums; + +/** + * @description 规格类型 + * @date 2020-07-15 + */ +public enum ResourcesPoolTypeEnum { + + CPU(0, "CPU"), + GPU(1, "GPU"); + + + /** + * 编码 + */ + private Integer code; + + /** + * 描述 + */ + private String description; + + ResourcesPoolTypeEnum(int code, String description) { + this.code = code; + this.description = description; + } + + public Integer getCode() { + return code; + } + + public String getDescription() { + return description; + } + + /** + * 是否是GPU编码 + * @param code + * @return true 是 ,false 否 + */ + public static boolean isGpuCode(Integer code){ + return GPU.getCode().equals(code); + } + +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/enums/SwitchEnum.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/enums/SwitchEnum.java new file mode 100644 index 0000000..49c0505 --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/enums/SwitchEnum.java @@ -0,0 +1,95 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.enums; + +/** + * @description 是否开关枚举 + * @date 2020-06-01 + */ +public enum SwitchEnum { + /** + * OFF 否 + */ + OFF(0, "否"), + + /** + * ON 否 + */ + ON(1, "是"), + + ; + + private Integer value; + + private String desc; + + SwitchEnum(Integer value, String desc) { + this.value = value; + this.desc = desc; + } + + public Integer getValue() { + return this.value; + } + + public String getDesc() { + return desc; + } + + public void setDesc(String desc) { + this.desc = desc; + } + + public static SwitchEnum getEnumValue(Integer value) { + switch (value) { + case 0: + return OFF; + case 1: + return ON; + default: + return OFF; + } + } + + public static Boolean getBooleanValue(Integer value) { + switch (value) { + case 1: + return true; + case 0: + return false; + default: + return false; + } + } + + public static boolean isExist(Integer value) { + for (SwitchEnum itm : SwitchEnum.values()) { + if (value.compareTo(itm.getValue()) == 0) { + return true; + } + } + return false; + } + + + @Override + public String toString() { + return "[" + this.value + "]" + this.desc; + } + +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/enums/SystemNodeEnum.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/enums/SystemNodeEnum.java new file mode 100644 index 0000000..442edec --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/enums/SystemNodeEnum.java @@ -0,0 +1,80 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.enums; + +/** + * @description 节点枚举类 + * @date 2020-07-08 + */ +public enum SystemNodeEnum { + /** + * 网络资源 + */ + NETWORK("NetworkUnavailable", "网络资源不足"), + /** + * 内存资源 + */ + MEMORY("MemoryPressure", "内存资源不足"), + /** + * 磁盘资源 + */ + DISK("DiskPressure", "磁盘资源不足"), + /** + * 进程资源 + */ + PROCESS("PIDPressure", "进程资源不足"); + + private String type; + private String message; + + SystemNodeEnum(String type, String message) { + this.type = type; + this.message = message; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + /** + * 根据type查询message信息 + * + * @param systemNodeType 节点类型 + * @return String message信息 + */ + public static String findMessageByType(String systemNodeType) { + SystemNodeEnum[] systemNodeEnums = SystemNodeEnum.values(); + for (SystemNodeEnum systemNodeEnum : systemNodeEnums) { + if (systemNodeType.equals(systemNodeEnum.getType())) { + return systemNodeEnum.getMessage(); + } + } + return null; + } +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/exception/BusinessException.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/exception/BusinessException.java new file mode 100644 index 0000000..72da9af --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/exception/BusinessException.java @@ -0,0 +1,72 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.exception; + +import lombok.Getter; +import org.dubhe.biz.base.constant.ResponseCode; +import org.dubhe.biz.base.vo.DataResponseBody; + +/** + * @description 业务异常 + * @date 2020-11-26 + */ +@Getter +public class BusinessException extends RuntimeException { + + private DataResponseBody responseBody; + + public BusinessException(String msg) { + super(msg); + this.responseBody = new DataResponseBody(ResponseCode.BADREQUEST, msg); + } + + public BusinessException(String msg, Throwable cause) { + super(msg,cause); + this.responseBody = new DataResponseBody(ResponseCode.BADREQUEST, msg); + } + + public BusinessException(Throwable cause) { + super(cause); + this.responseBody = new DataResponseBody(ResponseCode.BADREQUEST); + } + + public BusinessException(Integer code, String msg, String info, Throwable cause) { + super(msg,cause); + if (info == null) { + this.responseBody = new DataResponseBody(code, msg); + } else { + this.responseBody = new DataResponseBody(code, msg + ":" + info); + } + } + + public BusinessException(ErrorCode errorCode, Throwable cause) { + this(errorCode.getCode(), errorCode.getMsg(), null, cause); + } + + public BusinessException(ErrorCode errorCode, String info, Throwable cause) { + this(errorCode.getCode(), errorCode.getMsg(), info, cause); + } + + public BusinessException(ErrorCode errorCode) { + this(errorCode, null); + } + + public BusinessException(Integer code,String msg) { + this.responseBody = new DataResponseBody(code, msg); + } +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/exception/CaptchaException.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/exception/CaptchaException.java new file mode 100644 index 0000000..c98496e --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/exception/CaptchaException.java @@ -0,0 +1,48 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.exception; + +import lombok.Getter; +import org.dubhe.biz.base.constant.ResponseCode; +import org.dubhe.biz.base.vo.DataResponseBody; + +/** + * @description 验证码异常 + * @date 2020-02-23 + */ +@Getter +public class CaptchaException extends RuntimeException { + private static final long serialVersionUID = 1L; + + private DataResponseBody responseBody; + private Throwable cause; + + public CaptchaException(String msg) { + this.responseBody = new DataResponseBody(ResponseCode.BADREQUEST, msg); + } + + public CaptchaException(String msg, Throwable cause) { + this.cause = cause; + this.responseBody = new DataResponseBody(ResponseCode.BADREQUEST, msg); + } + + public CaptchaException(Throwable cause) { + this.cause = cause; + this.responseBody = new DataResponseBody(ResponseCode.BADREQUEST); + } +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/exception/DataSequenceException.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/exception/DataSequenceException.java new file mode 100644 index 0000000..846270b --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/exception/DataSequenceException.java @@ -0,0 +1,43 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.exception; + +import lombok.Getter; +import org.dubhe.biz.base.exception.BusinessException; + +/** + * @description 获取序列异常 + * @date 2020-09-23 + */ +@Getter +public class DataSequenceException extends BusinessException { + + private static final long serialVersionUID = 1L; + + public DataSequenceException(String msg) { + super(msg); + } + + public DataSequenceException(String msg, Throwable cause) { + super(msg,cause); + } + + public DataSequenceException(Throwable cause) { + super(cause); + } +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/exception/ErrorCode.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/exception/ErrorCode.java new file mode 100644 index 0000000..579dff7 --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/exception/ErrorCode.java @@ -0,0 +1,39 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.exception; + + +/** + * @description 异常code + * @date 2020-11-26 + */ +public interface ErrorCode { + + /** + * 错误码 + * @return code + */ + Integer getCode(); + + /** + * error info + * @return + */ + String getMsg(); + +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/exception/FeignException.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/exception/FeignException.java new file mode 100644 index 0000000..a47c1af --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/exception/FeignException.java @@ -0,0 +1,72 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.exception; + +import lombok.Getter; +import org.dubhe.biz.base.constant.ResponseCode; +import org.dubhe.biz.base.vo.DataResponseBody; + +/** + * @description 远程调用异常 + * @date 2020-11-26 + */ +@Getter +public class FeignException extends RuntimeException { + + private DataResponseBody responseBody; + + public FeignException(String msg) { + super(msg); + this.responseBody = new DataResponseBody(ResponseCode.BADREQUEST, msg); + } + + public FeignException(String msg, Throwable cause) { + super(msg,cause); + this.responseBody = new DataResponseBody(ResponseCode.BADREQUEST, msg); + } + + public FeignException(Throwable cause) { + super(cause); + this.responseBody = new DataResponseBody(ResponseCode.BADREQUEST); + } + + public FeignException(Integer code, String msg, String info, Throwable cause) { + super(msg,cause); + if (info == null) { + this.responseBody = new DataResponseBody(code, msg); + } else { + this.responseBody = new DataResponseBody(code, msg + ":" + info); + } + } + + public FeignException(ErrorCode errorCode, Throwable cause) { + this(errorCode.getCode(), errorCode.getMsg(), null, cause); + } + + public FeignException(ErrorCode errorCode, String info, Throwable cause) { + this(errorCode.getCode(), errorCode.getMsg(), info, cause); + } + + public FeignException(ErrorCode errorCode) { + this(errorCode, null); + } + + public FeignException(Integer code, String msg) { + this.responseBody = new DataResponseBody(code, msg); + } +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/exception/OAuthResponseError.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/exception/OAuthResponseError.java new file mode 100644 index 0000000..dbfb17a --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/exception/OAuthResponseError.java @@ -0,0 +1,45 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.exception; + +import org.dubhe.biz.base.vo.DataResponseBody; +import org.springframework.http.HttpStatus; + +/** + * @description OAuth2 授权自定义异常 + * @date 2020-11-18 + */ +public class OAuthResponseError extends RuntimeException{ + + private DataResponseBody responseBody; + + private HttpStatus statusCode; + + public OAuthResponseError(HttpStatus statusCode, String msg) { + super(msg); + this.statusCode = statusCode; + this.responseBody = new DataResponseBody(statusCode.value(),msg,null); + } + + public HttpStatus getStatusCode() { + return statusCode; + } + + public DataResponseBody getResponseBody() { + return responseBody; + } +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/functional/StringFormat.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/functional/StringFormat.java new file mode 100644 index 0000000..1b64e95 --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/functional/StringFormat.java @@ -0,0 +1,32 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.functional; + +/** + * @description 字符串格式化函数式接口 + * @date 2021-02-03 + */ +@FunctionalInterface +public interface StringFormat { + /** + * 格式化对象为字符串 + * @param value 被格式对象 + * @return + */ + String format(Object value); +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/service/UserContextService.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/service/UserContextService.java new file mode 100644 index 0000000..7e16c80 --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/service/UserContextService.java @@ -0,0 +1,37 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.service; + +import org.dubhe.biz.base.context.UserContext; + +/** + * @description 获取用户上下文接口 + * @date 2020-12-07 + */ +public interface UserContextService { + + /** + * @return 用户上下文信息 + */ + UserContext getCurUser(); + + /** + * @return 用户ID + */ + Long getCurUserId(); + +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/utils/AesUtil.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/utils/AesUtil.java new file mode 100644 index 0000000..da90596 --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/utils/AesUtil.java @@ -0,0 +1,94 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.utils; + +import cn.hutool.core.util.HexUtil; + +import javax.crypto.Cipher; +import javax.crypto.NoSuchPaddingException; +import javax.crypto.spec.SecretKeySpec; +import java.nio.charset.StandardCharsets; +import java.security.InvalidKeyException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +/** + * @description AES加解密工具 + * @date 2020-06-01 + */ +public class AesUtil { + + private static final String AES = "AES"; + + + private AesUtil(){ + + } + + + /** + * + * @param mode Cipher mode + * @param key 秘钥 + * @return Cipher + * @throws NoSuchAlgorithmException + * @throws NoSuchPaddingException + * @throws InvalidKeyException + */ + private static Cipher getCipher(int mode,String key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException { + MessageDigest md5Digest = MessageDigest.getInstance("MD5"); + SecretKeySpec secretKeySpec = new SecretKeySpec(md5Digest.digest(key.getBytes(StandardCharsets.UTF_8)), AES); + Cipher cipher = Cipher.getInstance(AES); + cipher.init(mode, secretKeySpec); + return cipher; + } + + /** + * 加密 + * + * @param data 原文 + * @param key 秘钥 + * @return String 密文 + */ + public static String encrypt(String data, String key) { + try { + Cipher cipher = getCipher(Cipher.ENCRYPT_MODE,key); + byte[] content = data.getBytes(StandardCharsets.UTF_8); + return new String(HexUtil.encodeHex(cipher.doFinal(content), false)); + } catch (Exception e) { + return null; + } + } + + /** + * 解密 + * @param hexData 十六进制密文 + * @param key 秘钥 + * @return String 密文 + */ + public static String decrypt(String hexData, String key) { + try { + Cipher cipher = getCipher(Cipher.DECRYPT_MODE,key); + byte[] content = HexUtil.decodeHex(hexData); + return new String(cipher.doFinal(content), StandardCharsets.UTF_8); + } catch (Exception e) { + return null; + } + } + +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/utils/DateUtil.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/utils/DateUtil.java new file mode 100644 index 0000000..63d2e14 --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/utils/DateUtil.java @@ -0,0 +1,128 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.utils; + +import java.sql.Timestamp; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.time.Instant; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.util.Calendar; +import java.util.Date; +import java.util.TimeZone; + +/** + * @description 日期工具类 + * @date 2020-11-26 + */ +public class DateUtil { + + private DateUtil() { + + } + + /** + * 北京时间 + */ + public final static String DEFAULT_TIME_ZONE = "GMT+8"; + + + /** + * 获取当前时间戳 + * + * @return + */ + public static Timestamp getCurrentTimestamp() { + return Timestamp.valueOf(LocalDateTime.now()); + } + + + /** + * 获取六小时后时间 + * @return + */ + public static long getAfterSixHourTime() { + long l1 = getTimestampOfDateTime(LocalDateTime.now()); + long milli = getTimestampOfDateTime(LocalDateTime.now().plusHours(6)); + return (milli - l1); + } + + + /** + * LocalDateTime -> long + * @param localDateTime + * @return + */ + public static long getTimestampOfDateTime(LocalDateTime localDateTime) { + ZoneId zone = ZoneId.systemDefault(); + Instant instant = localDateTime.atZone(zone).toInstant(); + return instant.toEpochMilli(); + } + + /** + * 获取第二天凌晨时间 + * @return + */ + public static long getSecondTime() { + LocalDateTime localDateTime = LocalDateTime.now(); + long l1 = localDateTime.atZone(ZoneId.of("Asia/Shanghai")).toInstant().toEpochMilli(); + + LocalDate localDate = LocalDate.now(); + LocalDate localDate1 = localDate.plusDays(1); + LocalDateTime localDateTime1 = localDate1.atStartOfDay(); + long milli = localDateTime1.atZone(ZoneId.of("Asia/Shanghai")).toInstant().toEpochMilli(); + return (milli - l1); + } + + /** + * @return 当前字符串时间yyyy-MM-dd HH:mm:ss SSS + */ + public static String getCurrentTimeStr() { + Date date = new Date(); + DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS"); + return dateFormat.format(date); + } + + /** + * + * @return 当前字符串时间yyyyMMddHHmmss + */ + public static String getTimestampStr() { + SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS"); + return df.format(System.currentTimeMillis()); + } + + + /** + * 获取垃圾回收具体的预执行时间 + * + * @param afterDay 延迟执行天数 + * @return Timestamp 具体的执行时间 + */ + public static Timestamp getRecycleTime(int afterDay){ + + Calendar calendar = Calendar.getInstance(); + calendar.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai")); + calendar.add(Calendar.DATE, afterDay); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 01:00:00"); + + return Timestamp.valueOf(sdf.format(calendar.getTime())); + } +} \ No newline at end of file diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/utils/HttpUtils.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/utils/HttpUtils.java new file mode 100644 index 0000000..b604ab5 --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/utils/HttpUtils.java @@ -0,0 +1,66 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.utils; + +import lombok.extern.slf4j.Slf4j; + +/** + * @description HttpUtil + * @date 2020-04-30 + */ +@Slf4j +public class HttpUtils { + + private HttpUtils() { + + } + + /** + * 判断http请求是否成功 + * + * @param httpCode + * 1XX Informational(信息性状态码) + * 2XX Success(成功状态码) + * 3XX Redirection(重定向状态码) + * 4XX Client Error(客户端错误状态码) + * 5XX Server Error(服务器错误状态码) + * @return + */ + public static boolean isSuccess(String httpCode){ + if (StringUtils.isBlank(httpCode)){ + return false; + } + return httpCode.length() == 3 && httpCode.startsWith("2"); + } + + /** + * 判断http请求是否成功 + * + * @param httpCode + * 1XX Informational(信息性状态码) + * 2XX Success(成功状态码) + * 3XX Redirection(重定向状态码) + * 4XX Client Error(客户端错误状态码) + * 5XX Server Error(服务器错误状态码) + * @return + */ + public static boolean isSuccess(int httpCode) { + return isSuccess(String.valueOf(httpCode)); + } + +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/utils/MathUtils.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/utils/MathUtils.java new file mode 100644 index 0000000..2d779c5 --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/utils/MathUtils.java @@ -0,0 +1,75 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.utils; + + +import org.dubhe.biz.base.constant.MagicNumConstant; + +/** + * @description 计算工具类 + * @date 2020-06-04 + */ +public class MathUtils { + + private static String FLOAT_DIVISION_FORMATE = "%1$0"; + + /** + * 字符串整数加法 + * num1+num2 + * @param num1 + * @param num2 + * @return + */ + public static String add(String num1, String num2) { + return String.valueOf((!RegexUtil.isDigits(num1) ? MagicNumConstant.ZERO : Integer.valueOf(num1)) + (!RegexUtil.isDigits(num2) ? MagicNumConstant.ZERO : Integer.valueOf(num2))); + } + + /** + * 字符串整数减法 + * num1 - num2 + * @param num1 + * @param num2 + * @return + */ + public static String reduce(String num1, String num2) { + return String.valueOf((!RegexUtil.isDigits(num1) ? MagicNumConstant.ZERO : Integer.valueOf(num1)) - (!RegexUtil.isDigits(num2) ? MagicNumConstant.ZERO : Integer.valueOf(num2))); + } + + /** + * + * 浮点数除法 num1/num2 + * @param num1 + * @param num2 + * @param decimal 结果小数位数 + * @return + */ + public static Float floatDivision(String num1, String num2, Integer decimal) { + if (!RegexUtil.isFloat(num1) || !RegexUtil.isFloat(num2)) { + return null; + } + if (Float.valueOf(num2).equals(0f)) { + return null; + } + if (decimal != null && decimal > MagicNumConstant.ZERO) { + Integer d = Integer.valueOf(MagicNumConstant.ONE + String.format(FLOAT_DIVISION_FORMATE + decimal + "d", MagicNumConstant.ZERO)); + return (float) (Math.round((Float.valueOf(num1) / Float.valueOf(num2)) * d)) / d; + } else { + return Float.valueOf(num1) / Float.valueOf(num2); + } + } +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/utils/Md5Util.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/utils/Md5Util.java new file mode 100644 index 0000000..a9f5437 --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/utils/Md5Util.java @@ -0,0 +1,53 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.utils; + +import java.security.MessageDigest; + +/** + * @description md5工具类 + * @date 2020-06-29 + */ +public class Md5Util { + public static final String CHARSET = "UTF-8"; + + public final static String createMd5(String s) { + char[] hexDigits ={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; + try { + byte[] btInput = s.getBytes(); + // 获得MD5摘要算法的 MessageDigest 对象 + MessageDigest mdInst = MessageDigest.getInstance("MD5"); + // 使用指定的字节更新摘要 + mdInst.update(btInput); + // 获得密文 + byte[] md = mdInst.digest(); + // 把密文转换成十六进制的字符串形式 + int j = md.length; + char[] str = new char[j * 2]; + int k = 0; + for (int i = 0; i < j; i++) { + byte byte0 = md[i]; + str[k++] = hexDigits[byte0 >>> 4 & 0xf]; + str[k++] = hexDigits[byte0 & 0xf]; + } + return new String(str); + } catch (Exception e) { + return null; + } + } +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/utils/NumberUtil.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/utils/NumberUtil.java new file mode 100644 index 0000000..21722be --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/utils/NumberUtil.java @@ -0,0 +1,46 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.utils; + +import org.dubhe.biz.base.exception.BusinessException; + +import java.util.regex.Pattern; + +/** + * @description 数字验证工具 + * @date 2020-05-18 + */ +public class NumberUtil { + + private static final String REGEX = "^[0-9]*$"; + + private NumberUtil() { + + } + + /** + * 判断是否为数字格式不限制位数 + * + * @param object 待校验参数 + */ + public static void isNumber(Object object) { + if (!((Pattern.compile(REGEX)).matcher(String.valueOf(object)).matches())) { + throw new BusinessException("parameter is incorrect"); + } + } +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/utils/PtModelUtil.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/utils/PtModelUtil.java new file mode 100644 index 0000000..8a521a6 --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/utils/PtModelUtil.java @@ -0,0 +1,59 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.utils; + +/** + * @description 模型管理工具类 + * @date 2020-07-17 + */ +public class PtModelUtil { + public static final int NUMBER_ZERO = 0; + + public static final int NUMBER_ONE = 1; + + public static final int NUMBER_TWO = 2; + + public static final int NUMBER_THREE = 3; + + public static final int NUMBER_FOUR = 4; + + public static final int NUMBER_FIVE = 5; + + public static final int NUMBER_EIGHT = 8; + + public static final int NUMBER_ONE_HUNDRED_TWENTY_EIGHT = 128; + + public static final int NUMBER_TWO_HUNDRED_FIFTY_FIVE = 255; + + public static final String ZIP = ".zip"; + + public static final String SORT_ASC = "asc"; + + public static final String SORT_DESC = "desc"; + + public static final String ID = "id"; + + public static final int USER_UPLOAD = 0; + + public static final int TRAINING_IMPORT = 1; + + public static final int MODEL_OPTIMIZATION = 2; + + public static final int RANDOM_LENGTH = 4; + +} \ No newline at end of file diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/utils/RandomUtil.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/utils/RandomUtil.java new file mode 100644 index 0000000..66e25a4 --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/utils/RandomUtil.java @@ -0,0 +1,37 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.utils; + + +/** + * @description 随机数工具类 + * @date 2020-06-01 + */ +public class RandomUtil { + + /** + * 生成随机6位数 + * + * @return 6位随机数 + */ + public static String randomCode() { + Integer res = (int) ((Math.random()) * 1000000); + return res + ""; + } + +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/utils/ReflectionUtils.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/utils/ReflectionUtils.java new file mode 100644 index 0000000..dfa330c --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/utils/ReflectionUtils.java @@ -0,0 +1,44 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.utils; + +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.List; + +/** + * @description 反射工具类 + * @date 2020-05-29 + **/ +public class ReflectionUtils { + + /** + * 获取所有字段集合 + * + * @param clazz 反射对象 + * @return List 字段集合 + **/ + public static List getFieldNames(Class clazz) { + Field[] fields = clazz.getDeclaredFields(); + List fieldNameList = new ArrayList<>(); + for (Field field : fields) { + fieldNameList.add(field.getName()); + } + return fieldNameList; + } +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/utils/RegexUtil.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/utils/RegexUtil.java new file mode 100644 index 0000000..99d00da --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/utils/RegexUtil.java @@ -0,0 +1,76 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.utils; + +import lombok.extern.slf4j.Slf4j; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * @description 正则匹配工具类 + * @date 2020-04-23 + */ +@Slf4j +public class RegexUtil { + private static final String DIGIT = "^[0-9]*$"; + private static final String FLOAT = "^[-+]?[0-9]*\\.?[0-9]+$"; + /** + * str待匹配文本 + * regex 正则表达式 + *返回str中匹配regex的第一个子串 + */ + public static String getMatcher(String str,String regex) { + try{ + if (StringUtils.isEmpty(str) || StringUtils.isEmpty(regex)){ + return ""; + } + Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE); + Matcher matcher = p.matcher(str); + matcher.find(); + return matcher.group(); + }catch (IllegalStateException e){ + log.error(e.getMessage(), e); + return ""; + } + } + + /** + * 数字匹配 + * @param str + * @return + */ + public static boolean isDigits(String str){ + if (StringUtils.isEmpty(str)){ + return false; + } + return str.matches(DIGIT); + } + + /** + * 浮点数匹配 + * @param str + * @return + */ + public static boolean isFloat(String str){ + if (StringUtils.isEmpty(str)){ + return false; + } + return str.matches(FLOAT); + } +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/utils/RsaEncrypt.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/utils/RsaEncrypt.java new file mode 100644 index 0000000..99f0510 --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/utils/RsaEncrypt.java @@ -0,0 +1,150 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.utils; + +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.codec.binary.Base64; + +import javax.crypto.Cipher; +import java.security.*; +import java.security.interfaces.RSAPrivateKey; +import java.security.interfaces.RSAPublicKey; +import java.security.spec.PKCS8EncodedKeySpec; +import java.security.spec.X509EncodedKeySpec; +import java.util.HashMap; +import java.util.Map; + +/** + * @description RSA对称加密工具 + * @date 2020-06-01 + */ +@Slf4j +public class RsaEncrypt { + /** + * 指定加密算法为RSA + */ + private static final String ALGORITHM = "RSA"; + /** + * 密钥长度,用来初始化 + */ + private static final int KEYSIZE = 1024; + /** + * 指定公钥存放文件 + */ + private static String PUBLIC_KEY_FILE = "PublicKey"; + /** + * 指定私钥存放文件 + */ + private static String PRIVATE_KEY_FILE = "PrivateKey"; + + /** + * 用于封装随机产生的公钥与私钥 + */ + + + /** + * 随机生成密钥对 + * + * @throws NoSuchAlgorithmException + */ + public static Map genKeyPair() throws NoSuchAlgorithmException { + // KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象 + KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(ALGORITHM); + // 初始化密钥对生成器,密钥大小为96-1024位 + keyPairGen.initialize(KEYSIZE, new SecureRandom()); + // 生成一个密钥对,保存在keyPair中 + KeyPair keyPair = keyPairGen.generateKeyPair(); + /*得到私钥*/ + RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); + // 得到公钥 + RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); + String publicKeyString = new String(Base64.encodeBase64(publicKey.getEncoded())); + // 得到私钥字符串 + String privateKeyString = new String(Base64.encodeBase64((privateKey.getEncoded()))); + Map keyMap = new HashMap(2); + // 将公钥和私钥保存到Map + keyMap.put(PUBLIC_KEY_FILE, publicKeyString); + keyMap.put(PRIVATE_KEY_FILE, privateKeyString); + return keyMap; + } + + /** + * 获取公钥 + * + * @param rasKeys + * @return + */ + public static String getPublicKey(Map rasKeys) { + return rasKeys.get(PUBLIC_KEY_FILE); + } + + /** + * 获取私钥 + * + * @param rasKeys + * @return + */ + public static String getPrivateKey(Map rasKeys) { + return rasKeys.get(PRIVATE_KEY_FILE); + } + + /** + * RSA公钥加密 + * + * @param str 加密字符串 + * @param publicKey 公钥 + * @return 密文 + * @throws Exception 加密过程中的异常信息 + */ + public static String encrypt(String str, String publicKey) throws Exception { + //base64编码的公钥 + byte[] decoded = Base64.decodeBase64(publicKey); + RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance(ALGORITHM).generatePublic(new X509EncodedKeySpec(decoded)); + //RSA加密 + Cipher cipher = Cipher.getInstance(ALGORITHM); + cipher.init(Cipher.ENCRYPT_MODE, pubKey); + String outStr = Base64.encodeBase64String(cipher.doFinal(str.getBytes("UTF-8"))); + return outStr; + } + + /** + * RSA私钥解密 + * + * @param str 加密字符串 + * @param privateKey 私钥 + * @return 铭文 + * @throws Exception 解密过程中的异常信息 + */ + public static String decrypt(String str, String privateKey) { + String outStr = null; + try { + //64位解码加密后的字符串 + byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8")); + //base64编码的私钥 + byte[] decoded = Base64.decodeBase64(privateKey); + RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance(ALGORITHM).generatePrivate(new PKCS8EncodedKeySpec(decoded)); + //RSA解密 + Cipher cipher = Cipher.getInstance(ALGORITHM); + cipher.init(Cipher.DECRYPT_MODE, priKey); + outStr = new String(cipher.doFinal(inputByte)); + } catch (Exception e) { + log.error("RSAEncrypt decrypt error:{} ", e); + } + return outStr; + } +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/utils/SpringContextHolder.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/utils/SpringContextHolder.java new file mode 100644 index 0000000..7c19c3d --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/utils/SpringContextHolder.java @@ -0,0 +1,94 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.utils; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.DisposableBean; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.stereotype.Component; + +/** + * @description 上下文工具类 + * @date 2020-03-25 + */ +@Slf4j +@Component +public class SpringContextHolder implements ApplicationContextAware, DisposableBean { + + private static ApplicationContext applicationContext = null; + + /** + * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型. + */ + @SuppressWarnings("unchecked") + public static T getBean(String name) { + assertContextInjected(); + return (T) applicationContext.getBean(name); + } + + /** + * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型. + */ + public static T getBean(Class requiredType) { + assertContextInjected(); + return applicationContext.getBean(requiredType); + } + + /** + * 检查ApplicationContext不为空. + */ + private static void assertContextInjected() { + if (applicationContext == null) { + throw new IllegalStateException("applicaitonContext属性未注入, 请在applicationContext" + + ".xml中定义SpringContextHolder或在SpringBoot启动类中注册SpringContextHolder."); + } + } + + /** + * 清除SpringContextHolder中的ApplicationContext为Null. + */ + private static void clearHolder() { + log.debug("清除SpringContextHolder中的ApplicationContext:" + + applicationContext); + applicationContext = null; + } + + @Override + public void destroy() { + SpringContextHolder.clearHolder(); + } + + @Override + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { + if (SpringContextHolder.applicationContext != null) { + log.warn("SpringContextHolder中的ApplicationContext被覆盖, 原有ApplicationContext为:" + SpringContextHolder.applicationContext); + } + SpringContextHolder.applicationContext = applicationContext; + } + + /** + * 获取当前环境 + * + * @return + */ + public static String getActiveProfile(){ + return applicationContext.getEnvironment().getActiveProfiles()[0]; + } +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/utils/StringUtils.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/utils/StringUtils.java new file mode 100644 index 0000000..9905cfd --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/utils/StringUtils.java @@ -0,0 +1,417 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.utils; + +import com.alibaba.fastjson.JSON; +import eu.bitwalker.useragentutils.Browser; +import eu.bitwalker.useragentutils.UserAgent; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.RandomStringUtils; +import org.dubhe.biz.base.constant.MagicNumConstant; +import org.dubhe.biz.base.constant.NumberConstant; +import org.dubhe.biz.base.constant.SymbolConstant; + +import javax.servlet.http.HttpServletRequest; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * @description 字符串工具类, 继承org.apache.commons.lang3.StringUtils类 + * @date 2020-03-25 + */ +@Slf4j +public class StringUtils extends org.apache.commons.lang3.StringUtils { + + private static final char SEPARATOR = '_'; + + private static final String UNKNOWN = "unknown"; + + private static Pattern linePattern = Pattern.compile("_(\\w)"); + + + /** + * 驼峰命名法工具 + * + * @return toCamelCase(" hello_world ") == "helloWorld" + * toCapitalizeCamelCase("hello_world") == "HelloWorld" + * toUnderScoreCase("helloWorld") = "hello_world" + */ + public static String toCamelCase(String s) { + if (s == null) { + return null; + } + + s = s.toLowerCase(); + + StringBuilder sb = new StringBuilder(s.length()); + boolean upperCase = false; + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + + if (c == SEPARATOR) { + upperCase = true; + } else if (upperCase) { + sb.append(Character.toUpperCase(c)); + upperCase = false; + } else { + sb.append(c); + } + } + + return sb.toString(); + } + + /** + * 驼峰命名法工具 + * + * @return toCamelCase(" hello_world ") == "helloWorld" + * toCapitalizeCamelCase("hello_world") == "HelloWorld" + * toUnderScoreCase("helloWorld") = "hello_world" + */ + public static String toCapitalizeCamelCase(String s) { + if (s == null) { + return null; + } + s = toCamelCase(s); + return s.substring(0, 1).toUpperCase() + s.substring(1); + } + + /** + * 驼峰命名法工具 + * + * @return toCamelCase(" hello_world ") == "helloWorld" + * toCapitalizeCamelCase("hello_world") == "HelloWorld" + * toUnderScoreCase("helloWorld") = "hello_world" + */ + static String toUnderScoreCase(String s) { + if (s == null) { + return null; + } + + StringBuilder sb = new StringBuilder(); + boolean upperCase = false; + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + + boolean nextUpperCase = true; + + if (i < (s.length() - 1)) { + nextUpperCase = Character.isUpperCase(s.charAt(i + 1)); + } + + if ((i > 0) && Character.isUpperCase(c)) { + if (!upperCase || !nextUpperCase) { + sb.append(SEPARATOR); + } + upperCase = true; + } else { + upperCase = false; + } + + sb.append(Character.toLowerCase(c)); + } + + return sb.toString(); + } + + + /** + * 获取ip地址 + * + * @param request + * @return + */ + public static String getIp(HttpServletRequest request) { + String ip = request.getHeader("x-forwarded-for"); + if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) { + ip = request.getHeader("Proxy-Client-IP"); + } + if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) { + ip = request.getHeader("WL-Proxy-Client-IP"); + } + if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) { + ip = request.getRemoteAddr(); + } + String comma = ","; + String localhost = "127.0.0.1"; + if (ip.contains(comma)) { + ip = ip.split(",")[0]; + } + if (localhost.equals(ip)) { + // 获取本机真正的ip地址 + try { + ip = InetAddress.getLocalHost().getHostAddress(); + } catch (UnknownHostException e) { + e.printStackTrace(); + } + } + return ip; + } + + public static String getBrowser(HttpServletRequest request) { + UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent")); + Browser browser = userAgent.getBrowser(); + return browser.getName(); + } + + + /** + * 获得当天是周几 + */ + public static String getWeekDay() { + String[] weekDays = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; + Calendar cal = Calendar.getInstance(); + cal.setTime(new Date()); + + int w = cal.get(Calendar.DAY_OF_WEEK) - 1; + if (w < 0) { + w = 0; + } + return weekDays[w]; + } + + /** + * 字符串匹配工具类(正则表达式) + * + * @param str + * @param regexp + * @return + */ + public static boolean stringMatch(String str, String regexp) { + Pattern pattern = Pattern.compile(regexp); + return pattern.matcher(str).find(); + } + + /** + * 字符串长度不够补位 + * + * @param sourceStr 源字符串 + * @param length 最终长度 + * @param type 补位方式 0:左边 1:右边 + * @return + */ + public static String stringFillIn(String sourceStr, int length, int type) { + if (sourceStr.length() > length) { + return sourceStr; + } + StringBuilder stringBuilder = new StringBuilder(""); + for (int i = 0; i < length - sourceStr.length(); i++) { + stringBuilder.append("0"); + } + + if (type == MagicNumConstant.ZERO) { + return stringBuilder.toString() + sourceStr; + } else { + return sourceStr + stringBuilder.toString(); + } + } + + + /** + * 从头截取string字符串 + * + * @param str 被截取字符串 + * @param truncationIndex 0 -> 截取长度 + * @return + */ + public static String truncationString(String str, int truncationIndex) { + if (str == null) { + return SymbolConstant.BLANK; + } else if (truncationIndex < 1 + || str.length() <= truncationIndex) { + return str; + } + return str.substring(0, truncationIndex); + } + + /** + * 字符串驼峰转下划线 + * + * @param str 被转字符串 + * @return String 转换后的字符串 + */ + public static String humpToLine(String str) { + StringBuilder stringBuilder = new StringBuilder(); + char[] chars = str.toCharArray(); + for (char character : chars) { + if (Character.isUpperCase(character)) { + stringBuilder.append("_"); + character = Character.toLowerCase(character); + } + stringBuilder.append(character); + } + return stringBuilder.toString(); + } + + /** + * 字符串下划线转驼峰 + * + * @param str 被转字符串 + * @return String 转换后的字符串 + */ + public static String lineToHump(String str) { + str = str.toLowerCase(); + Matcher matcher = linePattern.matcher(str); + StringBuffer sb = new StringBuffer(); + while (matcher.find()) { + matcher.appendReplacement(sb, matcher.group(1).toUpperCase()); + } + matcher.appendTail(sb); + return sb.toString(); + } + + + /** + * 字符串截取前 + * @param str + * @return + */ + public static String substringBefore(String str, String separator) { + + if (!isEmpty(str) && separator != null) { + if (separator.isEmpty()) { + return ""; + } else { + int pos = str.indexOf(separator); + return pos == -1 ? str : str.substring(0, pos); + } + } else { + return str; + } + } + + /** + * 字符串截取后 + * @param str + * @return + */ + public static String substringAfter(String str, String separator) { + + if (isEmpty(str)) { + return str; + } else if (separator == null) { + return ""; + } else { + int pos = str.indexOf(separator); + return pos == -1 ? "" : str.substring(pos + separator.length()); + } + } + + /** + * 获取UUID字符串 + * + * @return + */ + public static String getUUID() { + return UUID.randomUUID().toString().replace(SymbolConstant.HYPHEN, SymbolConstant.BLANK); + } + + /** + * 生成4位随机[a-z]字符串 + * + * @return + */ + public static String getRandomString() { + return RandomStringUtils.randomAlphabetic(NumberConstant.NUMBER_4).toLowerCase(); + } + + /** + * 生成时间戳 + 4位随机数 + * + * @return + */ + public static String getTimestamp() { + SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); + String dateStr = df.format(System.currentTimeMillis()); + return dateStr + getRandomString(); + } + + /** + * 往json字符串的map添加键值对 + * + * @param key 键 + * @param value 值 非null + * @param jsonStringMap json字符串的map + * @return + */ + public static String putIntoJsonStringMap(String key, String value, String jsonStringMap) { + if (StringUtils.isEmpty(key) || StringUtils.isEmpty(value)) { + return jsonStringMap; + } + try { + if (StringUtils.isEmpty(jsonStringMap)) { + jsonStringMap = JSON.toJSONString(new HashMap()); + } + Map map = JSON.parseObject(jsonStringMap, Map.class); + map.put(key, value); + return JSON.toJSONString(map); + } catch (Exception e) { + log.error(e.getMessage(), e); + } + return jsonStringMap; + } + + /** + * 删除json字符串的键值对 + * + * @param key 键 + * @param jsonStringMap json字符串的map + * @return + */ + public static String removeFromJsonStringMap(String key, String jsonStringMap) { + if (StringUtils.isEmpty(key) || StringUtils.isEmpty(jsonStringMap)) { + return jsonStringMap; + } + try { + Map map = JSON.parseObject(jsonStringMap, Map.class); + map.remove(key); + return JSON.toJSONString(map); + } catch (Exception e) { + log.error(e.getMessage(), e); + } + return jsonStringMap; + } + + /** + * 从json字符串的map中获取value + * + * @param key 键 + * @param jsonStringMap json字符串的map + * @return value + */ + public static String getValueFromJsonStringMap(String key, String jsonStringMap) { + if (StringUtils.isEmpty(key) || StringUtils.isEmpty(jsonStringMap)) { + return null; + } + try { + Map map = JSON.parseObject(jsonStringMap, Map.class); + return map.get(key); + } catch (Exception e) { + log.error(e.getMessage(), e); + } + return null; + } +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/utils/TimeTransferUtil.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/utils/TimeTransferUtil.java new file mode 100644 index 0000000..a602ee8 --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/utils/TimeTransferUtil.java @@ -0,0 +1,49 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.utils; + +import org.dubhe.biz.base.constant.MagicNumConstant; + +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; + +/** + * @description 时间格式转换工具类 + * @date 2020-05-20 + */ +public class TimeTransferUtil { + + private static final String UTC_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.sss'Z'"; + + /** + * Date转换为UTC时间 + * + * @param date + * @return utcTime + */ + public static String dateTransferToUtc(Date date){ + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + /**UTC时间与CST时间相差8小时**/ + calendar.set(Calendar.HOUR,calendar.get(Calendar.HOUR) - MagicNumConstant.EIGHT); + SimpleDateFormat utcSimpleDateFormat = new SimpleDateFormat(UTC_FORMAT); + Date utcDate = calendar.getTime(); + return utcSimpleDateFormat.format(utcDate); + } +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/vo/BaseVO.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/vo/BaseVO.java new file mode 100644 index 0000000..ef2b0b6 --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/vo/BaseVO.java @@ -0,0 +1,41 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.vo; + +import lombok.Data; + +import java.io.Serializable; +import java.sql.Timestamp; + +/** + * @description VO基础类 + * @date 2020-05-22 + */ +@Data +public class BaseVO implements Serializable { + + private static final long serialVersionUID = 1L; + + private Long createUserId; + + private Timestamp createTime; + + private Long updateUserId; + + private Timestamp updateTime; +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/vo/DataResponseBody.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/vo/DataResponseBody.java new file mode 100644 index 0000000..733f15a --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/vo/DataResponseBody.java @@ -0,0 +1,78 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.vo; + + +import lombok.Data; +import org.dubhe.biz.base.constant.ResponseCode; +import org.slf4j.MDC; + +import java.io.Serializable; + +/** + * @description 统一的公共响应体 + * @date 2020-03-16 + */ +@Data +public class DataResponseBody implements Serializable { + + /** + * 返回状态码 + */ + private Integer code; + /** + * 返回信息 + */ + private String msg; + /** + * 泛型数据 + */ + private T data; + /** + * 链路追踪ID + */ + private String traceId; + + public DataResponseBody() { + this(ResponseCode.SUCCESS, null); + } + + public DataResponseBody(T data) { + this(ResponseCode.SUCCESS, null, data); + } + + public DataResponseBody(Integer code, String msg) { + this(code, msg, null); + } + + public DataResponseBody(Integer code, String msg, T data) { + this.code = code; + this.msg = msg; + this.data = data; + this.traceId = MDC.get("traceId"); + } + + /** + * 判断是否响应成功 + * @return ture 成功,false 失败 + */ + public boolean succeed(){ + return ResponseCode.SUCCESS.equals(this.code); + } + +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/vo/DatasetVO.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/vo/DatasetVO.java new file mode 100644 index 0000000..14ff331 --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/vo/DatasetVO.java @@ -0,0 +1,160 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.vo; + +import lombok.Builder; +import lombok.Data; +import org.dubhe.biz.base.dto.TeamSmallDTO; +import org.dubhe.biz.base.dto.UserSmallDTO; + +import java.io.Serializable; +import java.sql.Timestamp; + +/** + * @description 数据集VO + * @date 2020-04-10 + */ +@Data +public class DatasetVO implements Serializable { + + /** + * 数据集ID + */ + private Long id; + + /** + * 数据集名称 + */ + private String name; + + /** + * 备注 + */ + private String remark; + + /** + * 类型 + */ + private Integer type; + + /** + * 数据集文件主目录 + */ + private String uri; + + /** + * 数据类型 + */ + private Integer dataType; + + /** + * 标注类型 + */ + private Integer annotateType; + + /** + * 数据集状态 + */ + private Integer status; + + /** + * 创建时间 + */ + private Timestamp createTime; + + /** + * 更新时间 + */ + private Timestamp updateTime; + + /** + * 团队信息 + */ + private TeamSmallDTO team; + + /** + * 创建人 + */ + private UserSmallDTO createUser; + + /** + * 更新人 + */ + private UserSmallDTO updateUser; + + /** + * 进度 + */ + private ProgressVO progress; + + /** + * 当前版本 + */ + private String currentVersionName; + + /** + * 是否导入 + */ + private boolean isImport; + + /** + * 解压状态 + */ + private Integer decompressState; + + /** + * 是否置顶 + */ + private boolean isTop; + + /** + * 标签组ID + */ + private Long labelGroupId; + + /** + * 标签组名称 + */ + private String labelGroupName; + + /** + * 标签组类型 + */ + private Integer labelGroupType; + + /** + * 是否自动标注 + */ + private boolean autoAnnotation; + + /** + * 数据转换状态 + */ + private Integer dataConversion; + + /** + * 源ID + */ + private Long sourceId; + + /** + * 文件数量 + */ + private Integer fileCount; + +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/vo/DictDetailVO.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/vo/DictDetailVO.java new file mode 100644 index 0000000..9de91ac --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/vo/DictDetailVO.java @@ -0,0 +1,67 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.vo; + +import lombok.Data; + +import java.io.Serializable; +import java.sql.Timestamp; + +/** + * @description 字典详情 + * @date 2020-12-23 + */ +@Data +public class DictDetailVO implements Serializable { + + private static final long serialVersionUID = 1L; + + /** + * 字典详情id + */ + private Long id; + + /** + * 字典id + */ + private Long dictId; + + /** + * 字典标签 + */ + private String label; + + /** + * 字典值 + */ + private String value; + + /** + * 排序 + */ + private String sort; + + /** + * 创建时间 + */ + private Timestamp createTime; + + /** + * 修改时间 + */ + private Timestamp updateTime; +} \ No newline at end of file diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/vo/DictVO.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/vo/DictVO.java new file mode 100644 index 0000000..bd5ba52 --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/vo/DictVO.java @@ -0,0 +1,43 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.vo; + +import lombok.Data; + +import java.io.Serializable; +import java.sql.Timestamp; +import java.util.List; + +/** + * @description 字典 + * @date 2021-01-19 + */ +@Data +public class DictVO implements Serializable { + + private static final long serialVersionUID = -1176729960392375726L; + private Long id; + + private String name; + + private String remark; + + private List dictDetails; + + private Timestamp createTime; +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/vo/ModelOptAlgorithmQureyVO.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/vo/ModelOptAlgorithmQureyVO.java new file mode 100644 index 0000000..03d750f --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/vo/ModelOptAlgorithmQureyVO.java @@ -0,0 +1,136 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.vo; + +import com.alibaba.fastjson.JSONObject; +import lombok.Data; +import lombok.experimental.Accessors; + +import java.io.Serializable; +import java.sql.Timestamp; + +/** + * @description 算法详情VO + * @date 2020-04-29 + */ +@Data +@Accessors(chain = true) +public class ModelOptAlgorithmQureyVO implements Serializable { + + private static final long serialVersionUID = 1L; + + /** + * 主键 + */ + private Long id; + + /** + * 算法名称 + */ + private String algorithmName; + + /** + * 算法描述 + */ + private String description; + + /** + * 算法来源(1为我的算法,2为预置算法) + */ + private Integer algorithmSource; + + /** + * 环境镜像名称 + */ + private String imageName; + + /** + * 代码目录 + */ + private String codeDir; + + /** + * 运行命令 + */ + private String runCommand; + + /** + * 运行参数 + */ + private JSONObject runParams; + + /** + * 算法用途 + */ + private String algorithmUsage; + + /** + * 算法精度 + */ + private String accuracy; + + /** + * P4推理速度(ms) + */ + private Integer p4InferenceSpeed; + + /** + * 训练输出结果(1是,0否) + */ + private Boolean isTrainModelOut; + + /** + * 训练输出(1是,0否) + */ + private Boolean isTrainOut; + + /** + * 可视化日志(1是,0否) + */ + private Boolean isVisualizedLog; + + /** + * 算法状态 + */ + private Integer algorithmStatus; + + /** + * 创建人ID + */ + private Integer createUserId; + + /** + * 修改人ID + */ + private Integer updateUserId; + + /** + * 创建时间 + */ + private Timestamp createTime; + + /** + * 修改时间 + */ + private Timestamp updateTime; + + /** + * 数据拥有人ID + */ + private Integer originUserId; +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/vo/ProgressVO.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/vo/ProgressVO.java new file mode 100644 index 0000000..02bb09f --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/vo/ProgressVO.java @@ -0,0 +1,51 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.vo; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.dubhe.biz.base.constant.MagicNumConstant; + +import java.io.Serializable; + +/** + * @description 数据集状态 + * @date 2020-04-10 + */ +@NoArgsConstructor +@AllArgsConstructor +@Data +@Builder +public class ProgressVO implements Serializable { + + private static final long serialVersionUID = 1L; + + @Builder.Default + private Long finished = MagicNumConstant.ZERO_LONG; + @Builder.Default + private Long unfinished = MagicNumConstant.ZERO_LONG; + @Builder.Default + private Long autoFinished = MagicNumConstant.ZERO_LONG; + @Builder.Default + private Long finishAutoTrack = MagicNumConstant.ZERO_LONG; + @Builder.Default + private Long annotationNotDistinguishFile = MagicNumConstant.ZERO_LONG; + +} \ No newline at end of file diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/vo/PtModelBranchQueryVO.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/vo/PtModelBranchQueryVO.java new file mode 100644 index 0000000..25c3685 --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/vo/PtModelBranchQueryVO.java @@ -0,0 +1,130 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.vo; + +import lombok.Data; +import lombok.experimental.Accessors; + +import java.io.Serializable; +import java.sql.Timestamp; + +/** + * @description 版本管理删除返回对应id + * @date 2020-5-15 + */ +@Data +@Accessors(chain = true) +public class PtModelBranchQueryVO implements Serializable { + + private static final long serialVersionUID = 1L; + + /** + * 版本ID + */ + private Long id; + + /** + * 父ID + */ + private Long parentId; + + /** + * 版本号 + */ + private String version; + + /** + * 模型地址 + */ + private String modelAddress; + + /** + * 模型路径 + */ + private String modelPath; + + /** + * 模型来源(0用户上传,1训练输出,2模型优化) + */ + private Integer modelSource; + + /** + * 算法ID + */ + private Long algorithmId; + + /** + * 算法名称 + */ + private String algorithmName; + + /** + * 算法来源(1为我的算法,2为预置算法) + */ + private Integer algorithmSource; + + /** + * 文件拷贝状态(0文件拷贝中,1文件拷贝成功,2文件拷贝失败) + */ + private Integer status; + + /** + * 团队ID + */ + private Integer teamId; + + /** + * 创建人ID + */ + private Long createUserId; + + /** + * 修改人ID + */ + private Long updateUserId; + + /** + * 创建时间 + */ + private Timestamp createTime; + + /** + * 修改时间 + */ + private Timestamp updateTime; + + /** + * 数据拥有人ID + */ + private Long originUserId; + + /** + * 模型名称 + */ + private String name; + + /** + * 模型描述 + */ + private String modelDescription; + + /** + * 是否能提供服务(true:能,false:否) + */ + private Boolean servingModel; +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/vo/PtModelInfoQueryVO.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/vo/PtModelInfoQueryVO.java new file mode 100644 index 0000000..5dd37d2 --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/vo/PtModelInfoQueryVO.java @@ -0,0 +1,127 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.vo; + +import lombok.Data; + +import java.io.Serializable; +import java.sql.Timestamp; + +/** + * @description 模型管理查询返回对应信息 + * @date 2020-5-15 + */ +@Data +public class PtModelInfoQueryVO implements Serializable { + private static final long serialVersionUID = 1L; + + /** + * 模型ID + */ + private Long id; + + /** + * 模型名称 + */ + private String name; + + /** + * 框架类型 + */ + private Integer frameType; + + /** + * 模型文件的格式(后缀名) + */ + private Integer modelType; + + /** + * 模型描述 + */ + private String modelDescription; + + /** + * 模型分类 + */ + private String modelClassName; + + /** + * 模型地址 + */ + private String modelAddress; + + /** + * 模型版本 + */ + private String version; + + /** + * 模型是否为预置模型(0默认模型,1预置模型) + */ + private Integer modelResource; + + /** + * 模型版本总的个数 + */ + private Integer totalNum; + + /** + * 团队ID + */ + private Integer teamId; + + /** + * 创建人ID + */ + private Long createUserId; + + /** + * 修改人ID + */ + private Long updateUserId; + + /** + * 创建时间 + */ + private Timestamp createTime; + + /** + * 修改时间 + */ + private Timestamp updateTime; + + /** + * 数据拥有人ID + */ + private Long originUserId; + + /** + * 模型是否已经打包 0未打包 1 已经打包(目前仅对炼知模型) + */ + private Integer packaged; + + /** + * 模型打包tags信息 + */ + private String tags; + + /** + * 是否能提供服务(true:能,false:否) + */ + private Boolean servingModel; +} diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/vo/QueryResourceSpecsVO.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/vo/QueryResourceSpecsVO.java new file mode 100644 index 0000000..bac1c42 --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/vo/QueryResourceSpecsVO.java @@ -0,0 +1,94 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.vo; + +import lombok.Data; +import lombok.experimental.Accessors; + +import java.io.Serializable; +import java.sql.Timestamp; + +/** + * @description 资源规格查询结果封装类 + * @date 2021-06-02 + */ +@Data +@Accessors(chain = true) +public class QueryResourceSpecsVO implements Serializable { + + private static final long serialVersionUID = 1L; + + /** + * 主键ID + */ + private Long id; + + /** + *规格名称 + */ + private String specsName; + + /** + *规格类型(0为CPU, 1为GPU) + */ + private Boolean resourcesPoolType; + + /** + *所属业务场景 + */ + private Integer module; + + /** + *CPU数量,单位:核 + */ + private Integer cpuNum; + + /** + *GPU数量,单位:核 + */ + private Integer gpuNum; + + /** + *内存大小,单位:M + */ + private Integer memNum; + + /** + *工作空间的存储配额,单位:M + */ + private Integer workspaceRequest; + + /** + *创建人 + */ + private Long createUserId; + + /** + *创建时间 + */ + private Timestamp createTime; + + /** + *更新人 + */ + private Long updateUserId; + + /** + *更新时间 + */ + private Timestamp updateTime; +} \ No newline at end of file diff --git a/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/vo/TrainAlgorithmQureyVO.java b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/vo/TrainAlgorithmQureyVO.java new file mode 100644 index 0000000..83eb8c0 --- /dev/null +++ b/dubhe-server/common-biz/base/src/main/java/org/dubhe/biz/base/vo/TrainAlgorithmQureyVO.java @@ -0,0 +1,136 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.base.vo; + +import com.alibaba.fastjson.JSONObject; +import lombok.Data; +import lombok.experimental.Accessors; + +import java.io.Serializable; +import java.sql.Timestamp; + +/** + * @description 算法 + * @date 2020-04-29 + */ +@Data +@Accessors(chain = true) +public class TrainAlgorithmQureyVO implements Serializable { + + private static final long serialVersionUID = 1L; + + /** + * 主键 + */ + private Long id; + + /** + * 算法名称 + */ + private String algorithmName; + + /** + * 算法描述 + */ + private String description; + + /** + * 算法来源(1为我的算法,2为预置算法) + */ + private Integer algorithmSource; + + /** + * 环境镜像名称 + */ + private String imageName; + + /** + * 代码目录 + */ + private String codeDir; + + /** + * 运行命令 + */ + private String runCommand; + + /** + * 运行参数 + */ + private JSONObject runParams; + + /** + * 算法用途 + */ + private String algorithmUsage; + + /** + * 算法精度 + */ + private String accuracy; + + /** + * P4推理速度(ms) + */ + private Integer p4InferenceSpeed; + + /** + * 训练输出结果(1是,0否) + */ + private Boolean isTrainModelOut; + + /** + * 训练输出(1是,0否) + */ + private Boolean isTrainOut; + + /** + * 可视化日志(1是,0否) + */ + private Boolean isVisualizedLog; + + /** + * 算法状态 + */ + private Integer algorithmStatus; + + /** + * 创建人ID + */ + private Long createUserId; + + /** + * 修改人ID + */ + private Long updateUserId; + + /** + * 创建时间 + */ + private Timestamp createTime; + + /** + * 修改时间 + */ + private Timestamp updateTime; + + /** + * 数据拥有人ID + */ + private Long originUserId; +} diff --git a/dubhe-server/common-biz/data-permission/pom.xml b/dubhe-server/common-biz/data-permission/pom.xml new file mode 100644 index 0000000..e4588a7 --- /dev/null +++ b/dubhe-server/common-biz/data-permission/pom.xml @@ -0,0 +1,39 @@ + + + 4.0.0 + + + org.dubhe.biz + common-biz + 0.0.1-SNAPSHOT + + data-permission + 0.0.1-SNAPSHOT + Biz 数据权限 + Data permission for Dubhe Server + + + + + org.dubhe.biz + db + ${org.dubhe.biz.db.version} + + + + org.dubhe.biz + log + ${org.dubhe.biz.log.version} + + + org.dubhe.cloud + swagger + ${org.dubhe.cloud.swagger.version} + + + + + + \ No newline at end of file diff --git a/dubhe-server/common-biz/data-permission/src/main/java/org/dubhe/biz/permission/annotation/DataPermissionMethod.java b/dubhe-server/common-biz/data-permission/src/main/java/org/dubhe/biz/permission/annotation/DataPermissionMethod.java new file mode 100644 index 0000000..ea58274 --- /dev/null +++ b/dubhe-server/common-biz/data-permission/src/main/java/org/dubhe/biz/permission/annotation/DataPermissionMethod.java @@ -0,0 +1,48 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.permission.annotation; + + +import org.dubhe.biz.base.enums.DatasetTypeEnum; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * @description 数据权限方法注解 + * @date 2020-11-25 + */ +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +public @interface DataPermissionMethod { + + /** + * 是否需要拦截标识 true: 不拦截 false: 拦截 + * + * @return 拦截标识 + */ + boolean interceptFlag() default false; + + /** + * 数据类型 + * + * @return 数据集类型 + */ + DatasetTypeEnum dataType() default DatasetTypeEnum.PRIVATE; +} diff --git a/dubhe-server/common-biz/data-permission/src/main/java/org/dubhe/biz/permission/annotation/RolePermission.java b/dubhe-server/common-biz/data-permission/src/main/java/org/dubhe/biz/permission/annotation/RolePermission.java new file mode 100644 index 0000000..28daf7a --- /dev/null +++ b/dubhe-server/common-biz/data-permission/src/main/java/org/dubhe/biz/permission/annotation/RolePermission.java @@ -0,0 +1,34 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.permission.annotation; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; +import java.lang.annotation.RetentionPolicy; + +/** + * @description 角色权限注解(验证是否具有管理员权限) + * @date 2021-03-10 + */ +@Target({ElementType.METHOD, ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface RolePermission { + +} diff --git a/dubhe-server/common-biz/data-permission/src/main/java/org/dubhe/biz/permission/aspect/PermissionAspect.java b/dubhe-server/common-biz/data-permission/src/main/java/org/dubhe/biz/permission/aspect/PermissionAspect.java new file mode 100644 index 0000000..cc755de --- /dev/null +++ b/dubhe-server/common-biz/data-permission/src/main/java/org/dubhe/biz/permission/aspect/PermissionAspect.java @@ -0,0 +1,122 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.permission.aspect; + +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.annotation.Around; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Pointcut; +import org.aspectj.lang.reflect.MethodSignature; +import org.dubhe.biz.base.context.DataContext; +import org.dubhe.biz.permission.annotation.DataPermissionMethod; +import org.dubhe.biz.base.context.UserContext; +import org.dubhe.biz.base.dto.CommonPermissionDataDTO; +import org.dubhe.biz.base.enums.DatasetTypeEnum; +import org.dubhe.biz.base.service.UserContextService; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.springframework.stereotype.Component; + +import javax.annotation.Resource; +import java.lang.reflect.Method; +import java.util.HashSet; +import java.util.Objects; +import java.util.Set; + +/** + * @description 数据权限切面 + * @date 2020-11-26 + */ +@Aspect +@Component +public class PermissionAspect { + + @Resource + private UserContextService userContextService; + + /** + * 公共数据的有用户ID + */ + public static final Long PUBLIC_DATA_USER_ID = 0L; + + /** + * 基于注解的切面方法 + */ + @Pointcut("@annotation(org.dubhe.biz.permission.annotation.DataPermissionMethod)") + private void cutMethod() { + + } + + /** + *环绕通知 + * @param joinPoint 切入参数对象 + * @return 返回方法结果集 + * @throws Throwable + */ + @Around("cutMethod()") + public Object around(ProceedingJoinPoint joinPoint) throws Throwable { + // 获取方法传入参数 + Object[] params = joinPoint.getArgs(); + DataPermissionMethod dataPermissionMethod = getDeclaredAnnotation(joinPoint); + UserContext curUser = userContextService.getCurUser(); + + if (!Objects.isNull(curUser) && !Objects.isNull(dataPermissionMethod)) { + Set ids = new HashSet<>(); + ids.add(curUser.getId()); + CommonPermissionDataDTO commonPermissionDataDTO = CommonPermissionDataDTO.builder().type(dataPermissionMethod.interceptFlag()).resourceUserIds(ids).build(); + if (DatasetTypeEnum.PUBLIC.equals(dataPermissionMethod.dataType())) { + ids.add(PUBLIC_DATA_USER_ID); + commonPermissionDataDTO.setResourceUserIds(ids); + } + DataContext.set(commonPermissionDataDTO); + } + // 执行源方法 + try { + return joinPoint.proceed(params); + } finally { + if(!Objects.isNull(DataContext.get())){ + DataContext.remove(); + } + } + } + + /** + * 获取方法中声明的注解 + * + * @param joinPoint 切入参数对象 + * @return DataPermissionMethod 方法注解类型 + */ + public DataPermissionMethod getDeclaredAnnotation(ProceedingJoinPoint joinPoint){ + // 获取方法名 + String methodName = joinPoint.getSignature().getName(); + // 反射获取目标类 + Class targetClass = joinPoint.getTarget().getClass(); + // 拿到方法对应的参数类型 + Class[] parameterTypes = ((MethodSignature) joinPoint.getSignature()).getParameterTypes(); + // 根据类、方法、参数类型(重载)获取到方法的具体信息 + Method objMethod = null; + try { + objMethod = targetClass.getMethod(methodName, parameterTypes); + } catch (NoSuchMethodException e) { + LogUtil.error(LogEnum.BIZ_DATASET,"获取注解方法参数异常 error:{}",e); + } + // 拿到方法定义的注解信息 + DataPermissionMethod annotation = objMethod.getDeclaredAnnotation(DataPermissionMethod.class); + // 返回 + return annotation; + } +} diff --git a/dubhe-server/common-biz/data-permission/src/main/java/org/dubhe/biz/permission/aspect/RolePermissionAspect.java b/dubhe-server/common-biz/data-permission/src/main/java/org/dubhe/biz/permission/aspect/RolePermissionAspect.java new file mode 100644 index 0000000..61bff69 --- /dev/null +++ b/dubhe-server/common-biz/data-permission/src/main/java/org/dubhe/biz/permission/aspect/RolePermissionAspect.java @@ -0,0 +1,57 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.permission.aspect; + +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Before; +import org.aspectj.lang.annotation.Pointcut; +import org.dubhe.biz.base.enums.BaseErrorCodeEnum; +import org.dubhe.biz.base.exception.BusinessException; +import org.dubhe.biz.permission.base.BaseService; +import org.springframework.stereotype.Component; + +/** + * @description 角色权限切面(验证是否具有管理员权限) + * @date 2020-11-26 + */ +@Aspect +@Component +public class RolePermissionAspect { + + + /** + * 基于注解的切面方法 + */ + @Pointcut("@annotation(org.dubhe.biz.permission.annotation.RolePermission)") + public void cutMethod() { + + } + /** + * 前置通知 验证是否具有管理员权限 + * + * @param point 切入参数对象 + * @return 返回方法结果集 + */ + @Before(value = "cutMethod()") + public void before(JoinPoint point) { + if (!BaseService.isAdmin()) { + throw new BusinessException(BaseErrorCodeEnum.DATASET_ADMIN_PERMISSION_ERROR); + } + } + +} diff --git a/dubhe-server/common-biz/data-permission/src/main/java/org/dubhe/biz/permission/base/BaseService.java b/dubhe-server/common-biz/data-permission/src/main/java/org/dubhe/biz/permission/base/BaseService.java new file mode 100644 index 0000000..a21192a --- /dev/null +++ b/dubhe-server/common-biz/data-permission/src/main/java/org/dubhe/biz/permission/base/BaseService.java @@ -0,0 +1,81 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.permission.base; + +import org.dubhe.biz.base.context.DataContext; +import org.dubhe.biz.base.context.UserContext; +import org.dubhe.biz.base.enums.BaseErrorCodeEnum; +import org.dubhe.biz.base.exception.BusinessException; +import org.dubhe.biz.base.service.UserContextService; +import org.dubhe.biz.base.utils.SpringContextHolder; +import org.dubhe.biz.permission.util.SqlUtil; +import org.springframework.util.CollectionUtils; + +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; + +/** + * @description 服务层基础数据公共方法类 + * @date 2020-03-27 + */ +public class BaseService { + + private BaseService(){} + + /** + * 校验是否具有管理员权限 + */ + public static void checkAdminPermission() { + UserContextService userContextService = SpringContextHolder.getBean(UserContextService.class); + if(!isAdmin(userContextService.getCurUser())){ + throw new BusinessException(BaseErrorCodeEnum.DATASET_ADMIN_PERMISSION_ERROR); + } + } + + /** + * 校验是否具有管理员权限 + */ + public static Boolean isAdmin() { + UserContextService userContextService = SpringContextHolder.getBean(UserContextService.class); + return isAdmin(userContextService.getCurUser()); + } + + /** + * 校验是否是管理管理员 + * + * @return 校验标识 + */ + public static Boolean isAdmin(UserContext userContext) { + if (!CollectionUtils.isEmpty(userContext.getRoles())) { + List roleIds = userContext.getRoles().stream().map(a -> a.getId()).collect(Collectors.toList()); + return SqlUtil.isAdmin(roleIds); + } + return false; + } + + + /** + * 清除本地线程数据权限数据 + */ + public static void removeContext(){ + if( !Objects.isNull(DataContext.get())){ + DataContext.remove(); + } + } + +} diff --git a/dubhe-server/common-biz/data-permission/src/main/java/org/dubhe/biz/permission/config/MetaHandlerConfig.java b/dubhe-server/common-biz/data-permission/src/main/java/org/dubhe/biz/permission/config/MetaHandlerConfig.java new file mode 100644 index 0000000..f5aaf6d --- /dev/null +++ b/dubhe-server/common-biz/data-permission/src/main/java/org/dubhe/biz/permission/config/MetaHandlerConfig.java @@ -0,0 +1,80 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.permission.config; + +import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; +import org.apache.ibatis.reflection.MetaObject; +import org.dubhe.biz.base.service.UserContextService; +import org.dubhe.biz.base.utils.DateUtil; +import org.dubhe.biz.db.constant.MetaHandlerConstant; +import org.springframework.stereotype.Component; + +import javax.annotation.Resource; +import java.util.Objects; + +/** + * @description 处理新增和更新的基础数据填充,配合BaseEntity和MyBatisPlusConfig使用 + * @date 2020-11-26 + */ +@Component +public class MetaHandlerConfig implements MetaObjectHandler { + + + @Resource + private UserContextService userContextService; + + /** + * 新增数据执行 + * + * @param metaObject 基础数据 + */ + @Override + public void insertFill(MetaObject metaObject) { + if (Objects.isNull(getFieldValByName(MetaHandlerConstant.CREATE_TIME, metaObject))) { + this.setFieldValByName(MetaHandlerConstant.CREATE_TIME, DateUtil.getCurrentTimestamp(), metaObject); + } + if (Objects.isNull(getFieldValByName(MetaHandlerConstant.UPDATE_TIME, metaObject))) { + this.setFieldValByName(MetaHandlerConstant.UPDATE_TIME, DateUtil.getCurrentTimestamp(), metaObject); + } + if (Objects.isNull(getFieldValByName(MetaHandlerConstant.UPDATE_USER_ID, metaObject))) { + this.setFieldValByName(MetaHandlerConstant.UPDATE_USER_ID, userContextService.getCurUserId(), metaObject); + } + if (Objects.isNull(getFieldValByName(MetaHandlerConstant.CREATE_USER_ID, metaObject))) { + this.setFieldValByName(MetaHandlerConstant.CREATE_USER_ID, userContextService.getCurUserId(), metaObject); + } + if (Objects.isNull(getFieldValByName(MetaHandlerConstant.ORIGIN_USER_ID, metaObject))) { + this.setFieldValByName(MetaHandlerConstant.ORIGIN_USER_ID, userContextService.getCurUserId(), metaObject); + } + if (Objects.isNull(getFieldValByName(MetaHandlerConstant.DELETED, metaObject))) { + this.setFieldValByName(MetaHandlerConstant.DELETED, false, metaObject); + } + } + + /** + * 更新数据执行 + * + * @param metaObject 基础数据 + */ + @Override + public void updateFill(MetaObject metaObject) { + this.setFieldValByName(MetaHandlerConstant.UPDATE_TIME, DateUtil.getCurrentTimestamp(), metaObject); + this.setFieldValByName(MetaHandlerConstant.UPDATE_USER_ID, userContextService.getCurUserId(), metaObject); + } + + +} diff --git a/dubhe-server/common-biz/data-permission/src/main/java/org/dubhe/biz/permission/config/MybatisPlusConfig.java b/dubhe-server/common-biz/data-permission/src/main/java/org/dubhe/biz/permission/config/MybatisPlusConfig.java new file mode 100644 index 0000000..52499db --- /dev/null +++ b/dubhe-server/common-biz/data-permission/src/main/java/org/dubhe/biz/permission/config/MybatisPlusConfig.java @@ -0,0 +1,44 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.permission.config; + +import org.dubhe.biz.permission.interceptor.PaginationInterceptor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +/** + * @description mybatis plus拦截器 + * @date 2020-11-26 + */ +@EnableTransactionManagement +@Configuration +public class MybatisPlusConfig { + + /** + * 注入 MybatisPlus 分页拦截器 + * + * @return 自定义MybatisPlus分页拦截器 + */ + @Bean + public PaginationInterceptor paginationInterceptor() { + PaginationInterceptor paginationInterceptor = new PaginationInterceptor(); + return paginationInterceptor; + } +} + diff --git a/dubhe-server/common-biz/data-permission/src/main/java/org/dubhe/biz/permission/interceptor/CustomerSqlInterceptor.java b/dubhe-server/common-biz/data-permission/src/main/java/org/dubhe/biz/permission/interceptor/CustomerSqlInterceptor.java new file mode 100644 index 0000000..967796b --- /dev/null +++ b/dubhe-server/common-biz/data-permission/src/main/java/org/dubhe/biz/permission/interceptor/CustomerSqlInterceptor.java @@ -0,0 +1,117 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.permission.interceptor; + +import org.apache.ibatis.executor.statement.StatementHandler; +import org.apache.ibatis.mapping.BoundSql; +import org.apache.ibatis.mapping.MappedStatement; +import org.apache.ibatis.plugin.*; +import org.apache.ibatis.reflection.DefaultReflectorFactory; +import org.apache.ibatis.reflection.MetaObject; +import org.apache.ibatis.reflection.SystemMetaObject; +import org.dubhe.biz.base.annotation.DataPermission; +import org.dubhe.biz.base.context.DataContext; +import org.dubhe.biz.base.context.UserContext; +import org.dubhe.biz.base.enums.OperationTypeEnum; +import org.dubhe.biz.base.service.UserContextService; +import org.dubhe.biz.permission.util.SqlUtil; +import org.springframework.stereotype.Component; + +import javax.annotation.Resource; +import java.lang.reflect.Field; +import java.sql.Connection; +import java.util.Arrays; +import java.util.Objects; +import java.util.Properties; + + +/** + * @description mybatis拦截器 + * @date 2020-11-25 + */ +@Component +@Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})}) +public class CustomerSqlInterceptor implements Interceptor { + + @Resource + private UserContextService userContextService; + + @Override + public Object intercept(Invocation invocation) throws Throwable { + + StatementHandler statementHandler = (StatementHandler) invocation.getTarget(); + MetaObject metaObject = MetaObject.forObject(statementHandler, SystemMetaObject.DEFAULT_OBJECT_FACTORY, + SystemMetaObject.DEFAULT_OBJECT_WRAPPER_FACTORY, new DefaultReflectorFactory()); + /* + * 先拦截到RoutingStatementHandler,里面有个StatementHandler类型的delegate变量,其实现类是BaseStatementHandler, + * 然后就到BaseStatementHandler的成员变量mappedStatement + */ + MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("delegate.mappedStatement"); + //id为执行的mapper方法的全路径名,如com.uv.dao.UserDao.selectPageVo + String id = mappedStatement.getId(); + //sql语句类型 select、delete、insert、update + String sqlCommandType = mappedStatement.getSqlCommandType().toString(); + BoundSql boundSql = statementHandler.getBoundSql(); + + //获取到原始sql语句 + String sql = boundSql.getSql(); + String mSql = sql; + + //注解逻辑判断 添加注解了才拦截 + Class classType = Class.forName(mappedStatement.getId().substring(0, mappedStatement.getId().lastIndexOf("."))); + String mName = mappedStatement.getId().substring(mappedStatement.getId().lastIndexOf(".") + 1, mappedStatement.getId().length()); + + //获取类注解 获取需要忽略拦截的方法名称 + DataPermission dataAnnotation = classType.getAnnotation(DataPermission.class); + if (!Objects.isNull(dataAnnotation)) { + UserContext curUser = userContextService.getCurUser(); + String[] ignores = dataAnnotation.ignoresMethod(); + //校验拦截忽略方法名 忽略新增方法 忽略回调/定时方法 + if ((!Objects.isNull(ignores) && Arrays.asList(ignores).contains(mName)) + || OperationTypeEnum.INSERT.getType().equals(sqlCommandType.toLowerCase()) + || Objects.isNull(curUser) + || (!Objects.isNull(DataContext.get()) && DataContext.get().getType()) + ) { + return invocation.proceed(); + } else { + //拦截所有sql操作类型 + mSql = SqlUtil.buildTargetSql(sql, SqlUtil.getResourceIds(curUser),curUser); + } + } + + //通过反射修改sql语句 + Field field = boundSql.getClass().getDeclaredField("sql"); + field.setAccessible(true); + field.set(boundSql, mSql); + return invocation.proceed(); + } + + @Override + public Object plugin(Object target) { + if (target instanceof StatementHandler) { + return Plugin.wrap(target, this); + } else { + return target; + } + } + + @Override + public void setProperties(Properties properties) { + + } + +} \ No newline at end of file diff --git a/dubhe-server/common-biz/data-permission/src/main/java/org/dubhe/biz/permission/interceptor/PaginationInterceptor.java b/dubhe-server/common-biz/data-permission/src/main/java/org/dubhe/biz/permission/interceptor/PaginationInterceptor.java new file mode 100644 index 0000000..f785952 --- /dev/null +++ b/dubhe-server/common-biz/data-permission/src/main/java/org/dubhe/biz/permission/interceptor/PaginationInterceptor.java @@ -0,0 +1,463 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.permission.interceptor; + + +import com.baomidou.mybatisplus.annotation.DbType; +import com.baomidou.mybatisplus.core.MybatisDefaultParameterHandler; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.core.metadata.OrderItem; +import com.baomidou.mybatisplus.core.parser.ISqlParser; +import com.baomidou.mybatisplus.core.parser.SqlInfo; +import com.baomidou.mybatisplus.core.toolkit.CollectionUtils; +import com.baomidou.mybatisplus.core.toolkit.ExceptionUtils; +import com.baomidou.mybatisplus.core.toolkit.PluginUtils; +import com.baomidou.mybatisplus.core.toolkit.StringUtils; +import com.baomidou.mybatisplus.extension.handlers.AbstractSqlParserHandler; +import com.baomidou.mybatisplus.extension.plugins.pagination.DialectFactory; +import com.baomidou.mybatisplus.extension.plugins.pagination.DialectModel; +import com.baomidou.mybatisplus.extension.plugins.pagination.dialects.IDialect; +import com.baomidou.mybatisplus.extension.toolkit.JdbcUtils; +import com.baomidou.mybatisplus.extension.toolkit.SqlParserUtils; +import net.sf.jsqlparser.JSQLParserException; +import net.sf.jsqlparser.parser.CCJSqlParserUtil; +import net.sf.jsqlparser.schema.Column; +import net.sf.jsqlparser.statement.select.*; +import org.apache.ibatis.executor.statement.StatementHandler; +import org.apache.ibatis.logging.Log; +import org.apache.ibatis.logging.LogFactory; +import org.apache.ibatis.mapping.*; +import org.apache.ibatis.plugin.*; +import org.apache.ibatis.reflection.MetaObject; +import org.apache.ibatis.reflection.SystemMetaObject; +import org.apache.ibatis.scripting.defaults.DefaultParameterHandler; +import org.apache.ibatis.session.Configuration; +import org.dubhe.biz.base.annotation.DataPermission; +import org.dubhe.biz.base.context.DataContext; +import org.dubhe.biz.base.context.UserContext; +import org.dubhe.biz.base.enums.OperationTypeEnum; +import org.dubhe.biz.base.service.UserContextService; +import org.dubhe.biz.permission.util.SqlUtil; + +import javax.annotation.Resource; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.*; +import java.util.stream.Collectors; + +/** + * @description MybatisPlus 分页拦截器 + * @date 2020-11-25 + */ +@Intercepts({@Signature( + type = StatementHandler.class, + method = "prepare", + args = {Connection.class, Integer.class} +)}) +public class PaginationInterceptor extends AbstractSqlParserHandler implements Interceptor { + protected static final Log logger = LogFactory.getLog(PaginationInterceptor.class); + + + @Resource + private UserContextService userContextService; + + /** + * COUNT SQL 解析 + */ + protected ISqlParser countSqlParser; + /** + * 溢出总页数,设置第一页 + */ + protected boolean overflow = false; + /** + * 单页限制 500 条,小于 0 如 -1 不受限制 + */ + protected long limit = 500L; + /** + * 数据类型 + */ + private DbType dbType; + /** + * 方言 + */ + private IDialect dialect; + /** + * 方言类型 + */ + @Deprecated + protected String dialectType; + /** + * 方言实现类 + */ + @Deprecated + protected String dialectClazz; + + public PaginationInterceptor() { + } + + /** + * 构建分页sql + * + * @param originalSql 原生sql + * @param page 分页参数 + * @return 构建后 sql + */ + public static String concatOrderBy(String originalSql, IPage page) { + if (CollectionUtils.isNotEmpty(page.orders())) { + try { + List orderList = page.orders(); + Select selectStatement = (Select) CCJSqlParserUtil.parse(originalSql); + List orderByElements; + List orderByElementsReturn; + if (selectStatement.getSelectBody() instanceof PlainSelect) { + PlainSelect plainSelect = (PlainSelect) selectStatement.getSelectBody(); + orderByElements = plainSelect.getOrderByElements(); + orderByElementsReturn = addOrderByElements(orderList, orderByElements); + plainSelect.setOrderByElements(orderByElementsReturn); + return plainSelect.toString(); + } + + if (selectStatement.getSelectBody() instanceof SetOperationList) { + SetOperationList setOperationList = (SetOperationList) selectStatement.getSelectBody(); + orderByElements = setOperationList.getOrderByElements(); + orderByElementsReturn = addOrderByElements(orderList, orderByElements); + setOperationList.setOrderByElements(orderByElementsReturn); + return setOperationList.toString(); + } + + if (selectStatement.getSelectBody() instanceof WithItem) { + return originalSql; + } + + return originalSql; + } catch (JSQLParserException var7) { + logger.error("failed to concat orderBy from IPage, exception=", var7); + } + } + + return originalSql; + } + + /** + * 添加分页排序规则 + * + * @param orderList 分页规则 + * @param orderByElements 分页排序元素 + * @return 分页规则 + */ + private static List addOrderByElements(List orderList, List orderByElements) { + orderByElements = CollectionUtils.isEmpty(orderByElements) ? new ArrayList(orderList.size()) : orderByElements; + List orderByElementList = orderList.stream().filter((item) -> { + return StringUtils.isNotBlank(item.getColumn()); + }).map((item) -> { + OrderByElement element = new OrderByElement(); + element.setExpression(new Column(item.getColumn())); + element.setAsc(item.isAsc()); + element.setAscDescPresent(true); + return element; + }).collect(Collectors.toList()); + ( orderByElements).addAll(orderByElementList); + return orderByElements; + } + + /** + * 执行sql查询逻辑 + * + * @param invocation mybatis 调用类 + * @return + * @throws Throwable + */ + @Override + public Object intercept(Invocation invocation) throws Throwable { + StatementHandler statementHandler = (StatementHandler) PluginUtils.realTarget(invocation.getTarget()); + MetaObject metaObject = SystemMetaObject.forObject(statementHandler); + this.sqlParser(metaObject); + MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("delegate.mappedStatement"); + if (SqlCommandType.SELECT == mappedStatement.getSqlCommandType() && StatementType.CALLABLE != mappedStatement.getStatementType()) { + BoundSql boundSql = (BoundSql) metaObject.getValue("delegate.boundSql"); + Object paramObj = boundSql.getParameterObject(); + IPage page = null; + if (paramObj instanceof IPage) { + page = (IPage) paramObj; + } else if (paramObj instanceof Map) { + Iterator var8 = ((Map) paramObj).values().iterator(); + + while (var8.hasNext()) { + Object arg = var8.next(); + if (arg instanceof IPage) { + page = (IPage) arg; + break; + } + } + } + + if (null != page && page.getSize() >= 0L) { + if (this.limit > 0L && this.limit <= page.getSize()) { + this.handlerLimit(page); + } + + String originalSql = boundSql.getSql(); + + //注解逻辑判断 添加注解了才拦截 + Class classType = Class.forName(mappedStatement.getId().substring(0, mappedStatement.getId().lastIndexOf("."))); + String mName = mappedStatement.getId().substring(mappedStatement.getId().lastIndexOf(".") + 1, mappedStatement.getId().length()); + + + String sqlCommandType = mappedStatement.getSqlCommandType().toString(); + //获取类注解 获取需要忽略拦截的方法名称 + DataPermission dataAnnotation = classType.getAnnotation(DataPermission.class); + if (!Objects.isNull(dataAnnotation)) { + UserContext curUser = userContextService.getCurUser(); + String[] ignores = dataAnnotation.ignoresMethod(); + //校验拦截忽略方法名 忽略新增方法 忽略回调/定时方法 + if (!((!Objects.isNull(ignores) && Arrays.asList(ignores).contains(mName)) + || OperationTypeEnum.INSERT.getType().equals(sqlCommandType.toLowerCase()) + || Objects.isNull(curUser) + || (!Objects.isNull(DataContext.get()) && DataContext.get().getType())) + + + ) { + originalSql = SqlUtil.buildTargetSql(originalSql, SqlUtil.getResourceIds(curUser), curUser); + } + } + + Connection connection = (Connection) invocation.getArgs()[0]; + if (page.isSearchCount() && !page.isHitCount()) { + SqlInfo sqlInfo = SqlParserUtils.getOptimizeCountSql(page.optimizeCountSql(), this.countSqlParser, originalSql); + this.queryTotal(sqlInfo.getSql(), mappedStatement, boundSql, page, connection); + if (page.getTotal() <= 0L) { + return null; + } + } + + DbType dbType = Optional.ofNullable(this.dbType).orElse(JdbcUtils.getDbType(connection.getMetaData().getURL())); + IDialect dialect = Optional.ofNullable(this.dialect).orElse(DialectFactory.getDialect(dbType)); + String buildSql = concatOrderBy(originalSql, page); + DialectModel model = dialect.buildPaginationSql(buildSql, page.offset(), page.getSize()); + Configuration configuration = mappedStatement.getConfiguration(); + List mappings = new ArrayList(boundSql.getParameterMappings()); + Map additionalParameters = (Map) metaObject.getValue("delegate.boundSql.additionalParameters"); + model.consumers(mappings, configuration, additionalParameters); + metaObject.setValue("delegate.boundSql.sql", model.getDialectSql()); + metaObject.setValue("delegate.boundSql.parameterMappings", mappings); + return invocation.proceed(); + } else { + return invocation.proceed(); + } + } else { + return invocation.proceed(); + } + } + + /** + * 处理分页数量 + * + * @param page 分页参数 + */ + protected void handlerLimit(IPage page) { + page.setSize(this.limit); + } + + /** + * 查询总数量 + * + * @param sql sql语句 + * @param mappedStatement 映射语句包装类 + * @param boundSql sql包装类 + * @param page 分页参数 + * @param connection JDBC连接包装类 + */ + protected void queryTotal(String sql, MappedStatement mappedStatement, BoundSql boundSql, IPage page, Connection connection) { + try { + PreparedStatement statement = connection.prepareStatement(sql); + Throwable var7 = null; + + try { + DefaultParameterHandler parameterHandler = new MybatisDefaultParameterHandler(mappedStatement, boundSql.getParameterObject(), boundSql); + parameterHandler.setParameters(statement); + long total = 0L; + ResultSet resultSet = statement.executeQuery(); + Throwable var12 = null; + + try { + if (resultSet.next()) { + total = resultSet.getLong(1); + } + } catch (Throwable var37) { + var12 = var37; + throw var37; + } finally { + if (resultSet != null) { + if (var12 != null) { + try { + resultSet.close(); + } catch (Throwable var36) { + var12.addSuppressed(var36); + } + } else { + resultSet.close(); + } + } + + } + + page.setTotal(total); + if (this.overflow && page.getCurrent() > page.getPages()) { + this.handlerOverflow(page); + } + } catch (Throwable var39) { + var7 = var39; + throw var39; + } finally { + if (statement != null) { + if (var7 != null) { + try { + statement.close(); + } catch (Throwable var35) { + var7.addSuppressed(var35); + } + } else { + statement.close(); + } + } + + } + + } catch (Exception var41) { + throw ExceptionUtils.mpe("Error: Method queryTotal execution error of sql : \n %s \n", var41, new Object[]{sql}); + } + } + + /** + * 设置默认当前页 + * + * @param page 分页参数 + */ + protected void handlerOverflow(IPage page) { + page.setCurrent(1L); + } + + /** + * MybatisPlus拦截器实现自定义插件 + * + * @param target 拦截目标对象 + * @return + */ + @Override + public Object plugin(Object target) { + return target instanceof StatementHandler ? Plugin.wrap(target, this) : target; + } + + /** + * MybatisPlus拦截器实现自定义属性设置 + * + * @param prop 属性参数 + */ + @Override + public void setProperties(Properties prop) { + String dialectType = prop.getProperty("dialectType"); + String dialectClazz = prop.getProperty("dialectClazz"); + if (StringUtils.isNotBlank(dialectType)) { + this.setDialectType(dialectType); + } + + if (StringUtils.isNotBlank(dialectClazz)) { + this.setDialectClazz(dialectClazz); + } + + } + + /** + * 设置数据源类型 + * + * @param dialectType 数据源类型 + */ + @Deprecated + public void setDialectType(String dialectType) { + this.setDbType(DbType.getDbType(dialectType)); + } + + + /** + * 设置方言实现类配置 + * + * @param dialectClazz 方言实现类 + */ + @Deprecated + public void setDialectClazz(String dialectClazz) { + this.setDialect(DialectFactory.getDialect(dialectClazz)); + } + + /** + * 设置获取总数的sql解析器 + * + * @param countSqlParser 总数的sql解析器 + * @return 自定义MybatisPlus拦截器 + */ + public PaginationInterceptor setCountSqlParser(final ISqlParser countSqlParser) { + this.countSqlParser = countSqlParser; + return this; + } + + /** + * 溢出总页数,设置第一页 + * + * @param overflow 溢出总页数 + * @return 自定义MybatisPlus拦截器 + */ + public PaginationInterceptor setOverflow(final boolean overflow) { + this.overflow = overflow; + return this; + } + + /** + * 设置分页规则 + * + * @param limit 分页数量 + * @return 自定义MybatisPlus拦截器 + */ + public PaginationInterceptor setLimit(final long limit) { + this.limit = limit; + return this; + } + + /** + * 设置数据类型 + * + * @param dbType 数据类型 + * @return 自定义MybatisPlus拦截器 + */ + public PaginationInterceptor setDbType(final DbType dbType) { + this.dbType = dbType; + return this; + } + + /** + * 设置方言 + * + * @param dialect 方言 + * @return 自定义MybatisPlus拦截器 + */ + public PaginationInterceptor setDialect(final IDialect dialect) { + this.dialect = dialect; + return this; + } + + +} + diff --git a/dubhe-server/common-biz/data-permission/src/main/java/org/dubhe/biz/permission/util/SqlUtil.java b/dubhe-server/common-biz/data-permission/src/main/java/org/dubhe/biz/permission/util/SqlUtil.java new file mode 100644 index 0000000..cd14bdb --- /dev/null +++ b/dubhe-server/common-biz/data-permission/src/main/java/org/dubhe/biz/permission/util/SqlUtil.java @@ -0,0 +1,114 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.permission.util; + +import org.apache.commons.lang3.StringUtils; +import org.dubhe.biz.base.context.DataContext; +import org.dubhe.biz.base.context.UserContext; +import org.dubhe.biz.base.enums.BaseErrorCodeEnum; +import org.dubhe.biz.base.exception.BusinessException; +import org.dubhe.biz.db.constant.PermissionConstant; +import org.springframework.util.CollectionUtils; + +import java.util.*; +import java.util.stream.Collectors; + +/** + * @description sql语句转换的工具类 + * @date 2020-11-25 + */ +public class SqlUtil { + + + /** + * 获取资源拥有着ID + * + * @return 资源拥有者id集合 + */ + public static Set getResourceIds(UserContext curUser) { + if (!Objects.isNull(DataContext.get())) { + return DataContext.get().getResourceUserIds(); + } + Set ids = new HashSet<>(); + ids.add(curUser.getId()); + return ids; + + } + + + /** + * 构建目标sql语句 + * + * @param originSql 原生sql + * @param resourceUserIds 所属资源用户ids + * @return 目标sql + */ + public static String buildTargetSql(String originSql, Set resourceUserIds, UserContext userContext) { + if(Objects.isNull(userContext)){ + throw new BusinessException(BaseErrorCodeEnum.SYSTEM_USER_IS_NOT_EXISTS.getCode(), + BaseErrorCodeEnum.SYSTEM_USER_IS_NOT_EXISTS.getMsg()); + + } + if (isAdmin(userContext.getRoles().stream().map(a->a.getId()).collect(Collectors.toList()))) { + return originSql; + } + String sqlWhereBefore = StringUtils.substringBefore(originSql.toLowerCase(), "where"); + String sqlWhereAfter = StringUtils.substringAfter(originSql.toLowerCase(), "where"); + StringBuffer buffer = new StringBuffer(); + //操作的sql拼接 + String targetSql = buffer.append(sqlWhereBefore).append(" where ").append(" origin_user_id in (") + .append(StringUtils.join(resourceUserIds, ",")).append(") and ").append(sqlWhereAfter).toString(); + + return targetSql; + } + + + /** + * 校验是否是管理管理员 (待权限添加获取角色再修改 默认都是管理员角色访问) + * + * @return 校验标识 + */ + public static Boolean isAdmin(List roleIds) { + return !CollectionUtils.isEmpty(roleIds) && roleIds.contains(PermissionConstant.ADMIN_ROLE_ID) ? true: false; + } + /** + * 将数组转换成in('1','2')的形式 + * + * @param objs + * @return + */ + public static String integerlistToString(Integer[] objs) { + + if (objs != null && objs.length > 0) { + StringBuilder sb = new StringBuilder("("); + for (Object obj : objs) { + if (obj != null) { + sb.append("'" + obj.toString() + "',"); + } + } + sb.deleteCharAt(sb.length() - 1); + sb.append(")"); + return sb.toString(); + } + return ""; + } + + + + +} diff --git a/dubhe-server/common-biz/data-response/pom.xml b/dubhe-server/common-biz/data-response/pom.xml new file mode 100644 index 0000000..7687f91 --- /dev/null +++ b/dubhe-server/common-biz/data-response/pom.xml @@ -0,0 +1,48 @@ + + + 4.0.0 + + org.dubhe.biz + common-biz + 0.0.1-SNAPSHOT + + data-response + 0.0.1-SNAPSHOT + Biz 统一Rest返回工具结构 + Data response for Dubhe Server + + + + + + org.dubhe.biz + base + ${org.dubhe.biz.base.version} + + + + org.dubhe.biz + log + ${org.dubhe.biz.log.version} + + + + org.springframework + spring-web + + + + org.springframework.security + spring-security-core + + + + + + + + + + + diff --git a/dubhe-server/common-biz/data-response/src/main/java/org/dubhe/biz/dataresponse/exception/handler/GlobalExceptionHandler.java b/dubhe-server/common-biz/data-response/src/main/java/org/dubhe/biz/dataresponse/exception/handler/GlobalExceptionHandler.java new file mode 100644 index 0000000..744bbbc --- /dev/null +++ b/dubhe-server/common-biz/data-response/src/main/java/org/dubhe/biz/dataresponse/exception/handler/GlobalExceptionHandler.java @@ -0,0 +1,155 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.dataresponse.exception.handler; + +import lombok.extern.slf4j.Slf4j; +import org.dubhe.biz.base.constant.ResponseCode; +import org.dubhe.biz.base.enums.BaseErrorCodeEnum; +import org.dubhe.biz.base.exception.BusinessException; +import org.dubhe.biz.base.exception.CaptchaException; +import org.dubhe.biz.base.exception.FeignException; +import org.dubhe.biz.base.exception.OAuthResponseError; +import org.dubhe.biz.base.vo.DataResponseBody; +import org.dubhe.biz.dataresponse.factory.DataResponseFactory; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +import java.util.Objects; + + +/** + * @description 全局异常处理器 + * @date 2020-02-23 + */ +@Slf4j +@RestControllerAdvice +public class GlobalExceptionHandler { + + + /** + * 处理自定义异常 + */ + @ExceptionHandler(value = AccessDeniedException.class) + public ResponseEntity loginException(AccessDeniedException e) { + // 打印堆栈信息 + LogUtil.error(LogEnum.SYS_ERR, "未授权引起异常的堆栈信息:{}", e); + return buildResponseEntity(HttpStatus.UNAUTHORIZED, + DataResponseFactory.failed(BaseErrorCodeEnum.UNAUTHORIZED.getCode(),BaseErrorCodeEnum.UNAUTHORIZED.getMsg())); + } + + + /** + * 处理自定义异常 + */ + @ExceptionHandler(value = IllegalStateException.class) + public ResponseEntity illegalStateException(IllegalStateException e) { + // 打印堆栈信息 + LogUtil.error(LogEnum.SYS_ERR, "服务未发现引起异常的堆栈信息:{}", e); + return buildResponseEntity(HttpStatus.NOT_FOUND, DataResponseFactory.failed(e.getMessage())); + } + + /** + * 处理OAuth2 授权异常 + */ + @ExceptionHandler(value = OAuthResponseError.class) + public ResponseEntity oAuth2ResponseError(OAuthResponseError e) { + // 打印堆栈信息 + LogUtil.error(LogEnum.SYS_ERR, "OAuth2 授权异常引发的异常的堆栈信息:{}", e); + return buildResponseEntity(e.getStatusCode(), e.getResponseBody()); + } + + + /** + * 处理所有不可知的异常 + */ + @ExceptionHandler(Throwable.class) + public ResponseEntity handleException(Throwable e) { + // 打印堆栈信息 + LogUtil.error(LogEnum.SYS_ERR, "引发的异常的堆栈信息:{}", e); + return buildResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR, + DataResponseFactory.failed(e.getMessage())); + } + + + /** + * 处理自定义异常 + */ + @ExceptionHandler(value = BusinessException.class) + public ResponseEntity badRequestException(BusinessException e) { + // 打印堆栈信息 + LogUtil.error(LogEnum.SYS_ERR, "引发的异常的堆栈信息:{}", e); + return buildResponseEntity(HttpStatus.OK, e.getResponseBody()); + } + + /** + * 处理所有接口数据验证异常 + */ + @ExceptionHandler(MethodArgumentNotValidException.class) + public ResponseEntity handleMethodArgumentNotValidException(MethodArgumentNotValidException e) { + // 打印堆栈信息 + LogUtil.error(LogEnum.SYS_ERR, "引起异常的堆栈信息:{}", e); + String[] str = Objects.requireNonNull(e.getBindingResult().getAllErrors().get(0).getCodes())[1].split("\\."); + String message = e.getBindingResult().getAllErrors().get(0).getDefaultMessage(); + String msg = "不能为空"; + if (msg.equals(message)) { + message = str[1] + ":" + message; + } + return buildResponseEntity(HttpStatus.BAD_REQUEST, new DataResponseBody(ResponseCode.ERROR, message)); + } + + /** + * 远程调用异常 + */ + @ExceptionHandler(FeignException.class) + public ResponseEntity feignException(FeignException e) { + // 打印堆栈信息 + LogUtil.error(LogEnum.SYS_ERR, "引发的异常的堆栈信息:{}", e); + return buildResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR, + DataResponseFactory.failed(e.getResponseBody().getMsg())); + } + + + /** + * 验证码异常 + */ + @ExceptionHandler(CaptchaException.class) + public ResponseEntity captchaException(CaptchaException e) { + // 打印堆栈信息 + LogUtil.error(LogEnum.SYS_ERR, "引发的异常的堆栈信息:{}", e); + return buildResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR, + DataResponseFactory.failed(e.getResponseBody().getMsg())); + } + + /** + * 统一返回 + * + * @param httpStatus + * @param responseBody + * @return + */ + private ResponseEntity buildResponseEntity(HttpStatus httpStatus, DataResponseBody responseBody) { + return new ResponseEntity<>(responseBody, httpStatus); + } + +} diff --git a/dubhe-server/common-biz/data-response/src/main/java/org/dubhe/biz/dataresponse/factory/DataResponseFactory.java b/dubhe-server/common-biz/data-response/src/main/java/org/dubhe/biz/dataresponse/factory/DataResponseFactory.java new file mode 100644 index 0000000..47c6c23 --- /dev/null +++ b/dubhe-server/common-biz/data-response/src/main/java/org/dubhe/biz/dataresponse/factory/DataResponseFactory.java @@ -0,0 +1,123 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.dataresponse.factory; + + +import org.dubhe.biz.base.vo.DataResponseBody; +import org.dubhe.biz.base.constant.ResponseCode; + +/** + * @description DataResponseBody 工厂类 + * @date 2020-05-28 + */ +public class DataResponseFactory { + + private DataResponseFactory(){ + + } + + /** + * 成功响应 + * + * @param + * @return + */ + public static DataResponseBody success(){ + return success(null,null); + } + + /** + * 成功响应 + * + * @param data + * @param + * @return + */ + public static DataResponseBody success(T data){ + return success(null,data); + } + + /** + * 成功响应 + * + * @param msg + * @return + */ + public static DataResponseBody successWithMsg(String msg){ + return success(msg,null); + } + + /** + * 成功响应 + * + * @param msg + * @param data + * @param + * @return + */ + public static DataResponseBody success(String msg, T data){ + return new DataResponseBody(ResponseCode.SUCCESS,msg,data); + } + + /** + * 失败响应 msg + * + * @param msg + * @return + */ + public static DataResponseBody failed(String msg){ + return failed(ResponseCode.ERROR,msg,null); + } + + /** + * 失败响应 + * + * @param failedCode + * @param msg + * @return + */ + public static DataResponseBody failed(Integer failedCode, String msg){ + return failed(failedCode,msg,null); + } + + /** + * 失败响应 + * + * @param failedCode + * @return + */ + public static DataResponseBody failed(Integer failedCode){ + return failed(failedCode,null,null); + } + + /** + * 失败响应 + * + * @param failedCode + * @param msg + * @param data + * @param + * @return + */ + public static DataResponseBody failed(Integer failedCode, String msg, T data){ + return new DataResponseBody(failedCode,msg,data); + } + + + +} diff --git a/dubhe-server/common-biz/db/pom.xml b/dubhe-server/common-biz/db/pom.xml new file mode 100644 index 0000000..34c09a9 --- /dev/null +++ b/dubhe-server/common-biz/db/pom.xml @@ -0,0 +1,62 @@ + + + + common-biz + org.dubhe.biz + 0.0.1-SNAPSHOT + + 4.0.0 + Biz 持久层操作 + db + + + + + mysql + mysql-connector-java + ${mysql.version} + runtime + + + com.alibaba + druid-spring-boot-starter + ${druid.version} + + + + com.baomidou + mybatis-plus-boot-starter + ${mybatis-plus.version} + + + com.baomidou + mybatis-plus + ${mybatis-plus.version} + + + + org.projectlombok + lombok + ${lombok.version} + + + jakarta.validation + jakarta.validation-api + + + org.dubhe.biz + base + 0.0.1-SNAPSHOT + compile + + + io.swagger + swagger-annotations + 1.5.20 + compile + + + + \ No newline at end of file diff --git a/dubhe-server/common-biz/db/src/main/java/org/dubhe/biz/db/annotation/Query.java b/dubhe-server/common-biz/db/src/main/java/org/dubhe/biz/db/annotation/Query.java new file mode 100644 index 0000000..409bdda --- /dev/null +++ b/dubhe-server/common-biz/db/src/main/java/org/dubhe/biz/db/annotation/Query.java @@ -0,0 +1,68 @@ +/** + * Copyright 2019-2020 Zheng Jie + * + * Licensed 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 org.dubhe.biz.db.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * @description 构建Wrapper的注解 + * @date 2020-03-26 + */ +@Target(ElementType.FIELD) +@Retention(RetentionPolicy.RUNTIME) +public @interface Query { + + + String propName() default ""; + + Type type() default Type.EQ; + + + String blurry() default ""; + + enum Type { + // 相等 + EQ + // 不等于 + , NE + // 大于 + , GT + // 大于等于 + , GE + // 小于 + , LT + // 小于等于 + , LE, + BETWEEN, + NOT_BETWEEN, + LIKE, + NOT_LIKE, + LIkE_LEFT, + LIKE_RIGHT, + IS_NULL, + IS_NOT_NULL, + IN, + NOT_IN, + INSQL, + NOT_INSQL, + ORDER_BY + } + +} + diff --git a/dubhe-server/common-biz/db/src/main/java/org/dubhe/biz/db/base/BaseConvert.java b/dubhe-server/common-biz/db/src/main/java/org/dubhe/biz/db/base/BaseConvert.java new file mode 100644 index 0000000..608267a --- /dev/null +++ b/dubhe-server/common-biz/db/src/main/java/org/dubhe/biz/db/base/BaseConvert.java @@ -0,0 +1,58 @@ +/** + * Copyright 2019-2020 Zheng Jie + * + * Licensed 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 org.dubhe.biz.db.base; + +import java.util.List; + +/** + * @description DTO Entity 转换 + * @date 2020-03-15 + */ +public interface BaseConvert { + + /** + * DTO转Entity + * + * @param dto / + * @return / + */ + E toEntity(D dto); + + /** + * Entity转DTO + * + * @param entity / + * @return / + */ + D toDto(E entity); + + /** + * DTO集合转Entity集合 + * + * @param dtoList / + * @return / + */ + List toEntity(List dtoList); + + /** + * Entity集合转DTO集合 + * + * @param entityList / + * @return / + */ + List toDto(List entityList); + +} diff --git a/dubhe-server/common-biz/db/src/main/java/org/dubhe/biz/db/base/PageQueryBase.java b/dubhe-server/common-biz/db/src/main/java/org/dubhe/biz/db/base/PageQueryBase.java new file mode 100644 index 0000000..e1208b3 --- /dev/null +++ b/dubhe-server/common-biz/db/src/main/java/org/dubhe/biz/db/base/PageQueryBase.java @@ -0,0 +1,63 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.db.base; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import lombok.Data; +import lombok.experimental.Accessors; + +/** + * @description 分页基类 + * @date 2020-05-08 + */ +@Data +@Accessors(chain = true) +public class PageQueryBase { + + /** + * 分页-当前页数 + */ + private Integer current; + + /** + * 分页-每页展示数 + */ + private Integer size; + + /** + * 排序字段 + */ + private String sort; + + /** + * 排序方式,asc | desc + */ + private String order; + + public Page toPage() { + Page page = new Page(); + if (this.current != null) { + page.setCurrent(this.current); + } + if (this.size != null && this.size < 2000) { + page.setSize(this.size); + } + return page; + } + +} diff --git a/dubhe-server/common-biz/db/src/main/java/org/dubhe/biz/db/constant/MetaHandlerConstant.java b/dubhe-server/common-biz/db/src/main/java/org/dubhe/biz/db/constant/MetaHandlerConstant.java new file mode 100644 index 0000000..39f50d3 --- /dev/null +++ b/dubhe-server/common-biz/db/src/main/java/org/dubhe/biz/db/constant/MetaHandlerConstant.java @@ -0,0 +1,53 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.db.constant; + +/** + * @description 元数据枚举 + * @date 2020-11-26 + */ +public final class MetaHandlerConstant { + + /** + * 创建时间字段 + */ + public static final String CREATE_TIME = "createTime"; + /** + *更新时间字段 + */ + public static final String UPDATE_TIME = "updateTime"; + /** + *更新人id字段 + */ + public static final String UPDATE_USER_ID = "updateUserId"; + /** + *创建人id字段 + */ + public static final String CREATE_USER_ID = "createUserId"; + /** + *资源拥有人id字段 + */ + public static final String ORIGIN_USER_ID = "originUserId"; + /** + *删除字段 + */ + public static final String DELETED = "deleted"; + + private MetaHandlerConstant() { + } +} diff --git a/dubhe-server/common-biz/db/src/main/java/org/dubhe/biz/db/constant/PermissionConstant.java b/dubhe-server/common-biz/db/src/main/java/org/dubhe/biz/db/constant/PermissionConstant.java new file mode 100644 index 0000000..13eca95 --- /dev/null +++ b/dubhe-server/common-biz/db/src/main/java/org/dubhe/biz/db/constant/PermissionConstant.java @@ -0,0 +1,41 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.db.constant; + +import lombok.Data; +import org.springframework.stereotype.Component; + +/** + * @description 权限常量 + * @date 2020-05-25 + */ +@Component +@Data +public class PermissionConstant { + + /** + * 超级用户ID + */ + public static final long ADMIN_USER_ID = 1L; + + /** + * 超级用户角色ID + */ + public static final long ADMIN_ROLE_ID = 1L; + +} diff --git a/dubhe-server/common-biz/db/src/main/java/org/dubhe/biz/db/entity/BaseEntity.java b/dubhe-server/common-biz/db/src/main/java/org/dubhe/biz/db/entity/BaseEntity.java new file mode 100644 index 0000000..ae3aca6 --- /dev/null +++ b/dubhe-server/common-biz/db/src/main/java/org/dubhe/biz/db/entity/BaseEntity.java @@ -0,0 +1,76 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.db.entity; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import lombok.Data; +import org.apache.commons.lang3.builder.ToStringBuilder; + +import java.io.Serializable; +import java.lang.reflect.Field; +import java.sql.Timestamp; + +/** + * @description Entity基础类 + * @date 2020-11-26 + */ +@Data +public class BaseEntity implements Serializable { + + private static final long serialVersionUID = 1L; + + /** + * 删除标识 + **/ + @TableField(value = "deleted",fill = FieldFill.INSERT) + @TableLogic + private Boolean deleted = false; + + @TableField(value = "create_user_id",fill = FieldFill.INSERT) + private Long createUserId; + + @TableField(value = "update_user_id",fill = FieldFill.INSERT_UPDATE) + private Long updateUserId; + + @TableField(value = "create_time",fill = FieldFill.INSERT) + private Timestamp createTime; + + + @TableField(value = "update_time",fill = FieldFill.INSERT_UPDATE) + private Timestamp updateTime; + + @Override + public String toString() { + ToStringBuilder builder = new ToStringBuilder(this); + Field[] fields = this.getClass().getDeclaredFields(); + try { + for (Field f : fields) { + f.setAccessible(true); + builder.append(f.getName(), f.get(this)).append("\n"); + } + } catch (Exception e) { + builder.append("toString builder encounter an error"); + } + return builder.toString(); + } + + public @interface Update { + } +} diff --git a/dubhe-server/common-biz/db/src/main/java/org/dubhe/biz/db/utils/PageUtil.java b/dubhe-server/common-biz/db/src/main/java/org/dubhe/biz/db/utils/PageUtil.java new file mode 100644 index 0000000..c11cb04 --- /dev/null +++ b/dubhe-server/common-biz/db/src/main/java/org/dubhe/biz/db/utils/PageUtil.java @@ -0,0 +1,78 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.db.utils; + +import com.baomidou.mybatisplus.core.metadata.IPage; + +import java.util.*; +import java.util.function.Function; + +/** + * @description 分页工具 + * @date 2020-03-13 + */ +public class PageUtil extends cn.hutool.core.util.PageUtil { + + /** + * List 分页 + */ + public static List toPage(int page, int size, List list) { + int fromIndex = page * size; + int toIndex = page * size + size; + if (fromIndex > list.size()) { + return new ArrayList(); + } else if (toIndex >= list.size()) { + return list.subList(fromIndex, list.size()); + } else { + return list.subList(fromIndex, toIndex); + } + } + + /** + * Page 数据处理,预防redis反序列化报错 + */ + public static Map toPage(IPage page) { + return toPage(page, page.getRecords()); + } + + /** + * 自定义分页 + */ + public static Map toPage(IPage page, Function function) { + return toPage(page, function.apply(page.getRecords())); + } + + /** + * 自定义分页 + */ + public static Map toPage(IPage page, Collection data) { + Map map = new LinkedHashMap<>(2); + map.put("result", data); + map.put("page", buildPagination(page)); + return map; + } + + private static Map buildPagination(IPage page) { + Map map = new HashMap<>(2); + map.put("current", page.getCurrent()); + map.put("size", page.getSize()); + map.put("total", page.getTotal()); + return map; + } + +} diff --git a/dubhe-server/common-biz/db/src/main/java/org/dubhe/biz/db/utils/WrapperHelp.java b/dubhe-server/common-biz/db/src/main/java/org/dubhe/biz/db/utils/WrapperHelp.java new file mode 100644 index 0000000..a3cb553 --- /dev/null +++ b/dubhe-server/common-biz/db/src/main/java/org/dubhe/biz/db/utils/WrapperHelp.java @@ -0,0 +1,162 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.db.utils; + +import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import lombok.extern.slf4j.Slf4j; +import org.dubhe.biz.db.annotation.Query; + +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; + +/** + * @description 构建Wrapper + * @date 2020-03-15 + */ +@Slf4j +public class WrapperHelp { + + public static QueryWrapper getWrapper(T query) { + QueryWrapper queryWrapper = new QueryWrapper<>(); + if (query == null) { + return queryWrapper; + } + try { + List fields = getAllFields(query.getClass(), new ArrayList<>()); + for (Field field : fields) { + field.setAccessible(true); + Query q = field.getAnnotation(Query.class); + if (q != null) { + String propName = q.propName(); + String attributeName = isBlank(propName) ? field.getName() : propName; + Object val = field.get(query); + if (val == null) { + continue; + } + // 模糊多字段 + String blurry = q.blurry(); + if (ObjectUtil.isNotEmpty(blurry)) { + String[] blurrys = blurry.split(","); + queryWrapper.and(qw -> { + for (int i = 0; i < blurrys.length; i++) { + if (i == 0) { + qw.like(blurrys[i], val); + } else { + qw.or().like(blurrys[i], val); + } + } + }); + continue; + } + switch (q.type()) { + case EQ: + queryWrapper = queryWrapper.eq(attributeName, val); + break; + case NE: + queryWrapper = queryWrapper.ne(attributeName, val); + break; + case GE: + queryWrapper = queryWrapper.ge(attributeName, val); + break; + case GT: + queryWrapper = queryWrapper.gt(attributeName, val); + break; + case LT: + queryWrapper = queryWrapper.lt(attributeName, val); + break; + case LE: + queryWrapper = queryWrapper.le(attributeName, val); + break; + case BETWEEN: + List between = new ArrayList<>((List) val); + queryWrapper = queryWrapper.between(attributeName, between.get(0), between.get(1)); + break; + case NOT_BETWEEN: + List notBetween = new ArrayList<>((List) val); + queryWrapper = queryWrapper.notBetween(attributeName, notBetween.get(0), notBetween.get(1)); + break; + case LIKE: + queryWrapper = queryWrapper.like(attributeName, val); + break; + case NOT_LIKE: + queryWrapper = queryWrapper.notLike(attributeName, val); + break; + case LIkE_LEFT: + queryWrapper = queryWrapper.likeLeft(attributeName, val); + break; + case LIKE_RIGHT: + queryWrapper = queryWrapper.likeRight(attributeName, val); + break; + case IS_NULL: + queryWrapper = queryWrapper.isNull(attributeName); + break; + case IS_NOT_NULL: + queryWrapper = queryWrapper.isNotNull(attributeName); + break; + case IN: + queryWrapper = queryWrapper.in(attributeName, (Collection) val); + break; + case NOT_IN: + queryWrapper = queryWrapper.notIn(attributeName, (Collection) val); + break; + case INSQL: + queryWrapper = queryWrapper.inSql(attributeName, String.valueOf(val)); + break; + case NOT_INSQL: + queryWrapper = queryWrapper.notInSql(attributeName, String.valueOf(val)); + break; + case ORDER_BY: + queryWrapper = queryWrapper.last(" ORDER BY " + val); + break; + default: + break; + } + } + } + } catch (Exception e) { + log.error(e.getMessage(), e); + } + return queryWrapper; + } + + private static boolean isBlank(final CharSequence cs) { + int strLen; + if (cs == null || (strLen = cs.length()) == 0) { + return true; + } + for (int i = 0; i < strLen; i++) { + if (!Character.isWhitespace(cs.charAt(i))) { + return false; + } + } + return true; + } + + private static List getAllFields(Class clazz, List fields) { + if (clazz != null) { + fields.addAll(Arrays.asList(clazz.getDeclaredFields())); + getAllFields(clazz.getSuperclass(), fields); + } + return fields; + } + +} diff --git a/dubhe-server/common-biz/file/pom.xml b/dubhe-server/common-biz/file/pom.xml new file mode 100644 index 0000000..4f411e3 --- /dev/null +++ b/dubhe-server/common-biz/file/pom.xml @@ -0,0 +1,82 @@ + + + + common-biz + org.dubhe.biz + 0.0.1-SNAPSHOT + + 4.0.0 + + file + 0.0.1-SNAPSHOT + Biz file 工具 + File util for Dubhe Server + + + + + org.dubhe.biz + base + ${org.dubhe.biz.base.version} + + + org.dubhe.biz + log + ${org.dubhe.biz.log.version} + + + + org.projectlombok + lombok + ${lombok.version} + + + + org.springframework + spring-web + + + + + commons-io + commons-io + compile + + + + io.minio + minio + + + + org.apache.commons + commons-compress + + + + org.apache.commons + commons-pool2 + + + + com.emc.ecs + nfs-client + + + + org.apache.poi + poi + + + org.apache.poi + poi-ooxml + + + + + + + + + \ No newline at end of file diff --git a/dubhe-server/common-biz/file/src/main/java/org/dubhe/biz/file/api/FileStoreApi.java b/dubhe-server/common-biz/file/src/main/java/org/dubhe/biz/file/api/FileStoreApi.java new file mode 100644 index 0000000..8a2f6e4 --- /dev/null +++ b/dubhe-server/common-biz/file/src/main/java/org/dubhe/biz/file/api/FileStoreApi.java @@ -0,0 +1,237 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.file.api; + +import org.dubhe.biz.base.utils.StringUtils; +import org.dubhe.biz.file.dto.FilePageDTO; + +import javax.servlet.http.HttpServletResponse; +import java.io.BufferedInputStream; +import java.io.File; +import java.util.List; + +/** + * @description 文件存储接口 + * @date 2021-04-19 + */ +public interface FileStoreApi { + + /** + * 获取根路径 + * + * @return String 根路径 默认为空 + */ + default String getRootDir() { + return ""; + } + + /** + * 获取bucket + * + * @return String bucket 默认为空 + */ + default String getBucket() { + return ""; + } + + /** + * 替换路径中多余的 "/" + * + * @param path + * @return String + */ + default String formatPath(String path) { + if (!StringUtils.isEmpty(path)) { + return path.replaceAll("///*", File.separator); + } + return path; + } + + /** + * 绝对路径兼容 + * @param sourcePath 源路径 + * @return String + */ + default String compatibleAbsolutePath(String sourcePath) { + return formatPath(sourcePath.startsWith(getRootDir()) ? sourcePath : getRootDir() + sourcePath); + } + + + /** + * 校验文件或文件夹是否不存在(true为存在,false为不存在) + * + * @param path 文件路径 + * @return boolean + */ + boolean fileOrDirIsExist(String path); + + /** + * 校验是否是文件夹(true为文件夹,false为文件) + * + * @param path 文件路径 + * @return boolean + */ + boolean isDirectory(String path); + + /** + * 过滤路径下文件后缀名(不区分大小写)并返回符合条件的文件集合 + * + * @param path 文件夹路径 + * @param fileSuffix 文件后缀名(不区分大小写) + * @return List 返回符合条件的文件集合 + */ + List filterFileSuffix(String path,String fileSuffix); + + /** + * 创建指定目录 + * + * @param dir 需要创建的目录 例如:/abc/def + * @return boolean + */ + boolean createDir(String dir); + + /** + * 创建多个指定目录 + * + * @param paths + * @return boolean + */ + boolean createDirs(String... paths); + + /** + * 指定目录中创建文件 + * + * @param dir 需要创建的目录 例如:/abc/def + * @param fileName 需要创建的文件 例如:dd.txt + * @return boolean + */ + boolean createFile(String dir, String fileName); + + /** + * 新建或追加文件 + * + * @param filePath 文件绝对路径 + * @param content 文件内容 + * @param append 文件是否是追加 + * @return + */ + boolean createOrAppendFile(String filePath, String content, boolean append); + + /** + * 删除目录 或者文件 + * + * @param dirOrFile 需要删除的目录 或者文件 例如:/abc/def 或者 /abc/def/dd.txt + * @return boolean + */ + boolean deleteDirOrFile(String dirOrFile); + + /** + * 复制文件 到指定目录下 单个文件 + * + * @param sourceFile 需要复制的文件 例如:/abc/def/dd.txt + * @param targetPath 需要放置的目标目录 例如:/abc/dd + * @return boolean + */ + boolean copyFile(String sourceFile, String targetPath); + + /** + * 使用shell拷贝文件或路径 + * + * @param sourcePath 需要复制的文件或路径 例如:/abc/def/cc.txt or /abc/def* + * @param targetPath 需要放置的目标目录 例如:/abc/dd + * @param type CopyTypeEnum的 + * @return boolean + */ + boolean copyFile(String sourcePath, String targetPath, Integer type); + + /** + * 复制路径下文件并重命名 + * + * @param sourceFile 源文件 + * @param targetFile 目标文件全路径 + * @return boolean + */ + boolean copyFileAndRename(String sourceFile, String targetFile); + + /** + * 复制路径下文件及文件夹到指定目录下 多个文件 包含目录与文件并存情况 + * + * @param sourcePath 需要复制的文件目录 例如:/abc/def + * @param targetPath 需要放置的目标目录 例如:/abc/dd + * @return boolean + */ + boolean copyPath(String sourcePath, String targetPath); + + /** + * 复制文件夹到指定目录下 + * + * @param sourcePath 需要复制的文件夹 例如:/abc/def + * @param targetPath 需要放置的目标目录 例如:/abc/dd 复制成功路径/abc/dd/def* + * @return boolean + */ + boolean copyDir(String sourcePath, String targetPath); + + /** + * zip解压并删除压缩文件 + * @param sourceFile zip源文件 例如:/abc/z.zip + * @param targetPath 解压后的目标文件夹 例如:/abc/ + * @return boolean + */ + boolean unzip(String sourceFile, String targetPath); + + /** + * 解压压缩包 包含目录与子目录 + * + * @param sourceFile 需要复制的文件 例如:/abc/def/aaa.zip + * @return boolean + */ + boolean unzip(String sourceFile); + + /** + * 压缩 目录 或者文件 到压缩包 + * + * @param dirOrFile 目录或者文件 例如: /abc/def/aaa.txt , /abc/def + * @param zipPath 压缩包全路径名 例如: /abc/def/aa.zip + * @return boolean + */ + boolean zipDirOrFile(String dirOrFile, String zipPath); + + /** + * 获取NFS3File 对象文件的输入流 + * + * @param path 文件路径 + * @return BufferedInputStream + */ + BufferedInputStream getInputStream(String path); + + /** + * 下载 + * + * @param path 文件路径 + * @param response HTTP返回 + */ + void download(String path, HttpServletResponse response); + + /** + * 分页查询指定路径下的文件列表(需要支持分页) + * + * @param filePageDTO 查询以及相应参数实体 + */ + void filterFilePageWithPath(FilePageDTO filePageDTO); + +} diff --git a/dubhe-server/common-biz/file/src/main/java/org/dubhe/biz/file/api/impl/HostFileStoreApiImpl.java b/dubhe-server/common-biz/file/src/main/java/org/dubhe/biz/file/api/impl/HostFileStoreApiImpl.java new file mode 100644 index 0000000..2f46f67 --- /dev/null +++ b/dubhe-server/common-biz/file/src/main/java/org/dubhe/biz/file/api/impl/HostFileStoreApiImpl.java @@ -0,0 +1,666 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.file.api.impl; + +import cn.hutool.core.io.FileUtil; +import cn.hutool.core.io.IoUtil; +import cn.hutool.core.util.CharsetUtil; +import cn.hutool.core.util.ObjectUtil; +import cn.hutool.core.util.ZipUtil; +import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; +import org.apache.commons.compress.archivers.zip.ZipFile; +import org.apache.poi.util.IOUtils; +import org.dubhe.biz.base.constant.MagicNumConstant; +import org.dubhe.biz.base.constant.SymbolConstant; +import org.dubhe.biz.base.utils.StringUtils; +import org.dubhe.biz.file.api.FileStoreApi; +import org.dubhe.biz.file.dto.FileDTO; +import org.dubhe.biz.file.dto.FilePageDTO; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import org.springframework.util.FileCopyUtils; + +import javax.servlet.ServletOutputStream; +import javax.servlet.http.HttpServletResponse; +import java.io.*; +import java.util.ArrayList; +import java.util.Date; +import java.util.Enumeration; +import java.util.List; +import java.util.zip.ZipEntry; + +/** + * @description 本地文件存储接口实现类 + * @date 2021-04-23 + */ +@Component(value = "hostFileStoreApiImpl") +public class HostFileStoreApiImpl implements FileStoreApi { + + private static final String FILE_SEPARATOR = File.separator; + + private static final String ZIP = ".zip"; + + private static final String CHARACTER_GBK = "GBK"; + + private static final String OS_NAME = "os.name"; + + private static final String WINDOWS = "Windows"; + + @Value("${storage.file-store-root-path}") + private String rootDir; + + @Value("/${minio.bucketName}/") + private String bucket; + + @Value("${storage.file-store-root-windows-path}") + private String rootWindowsPath; + + @Override + public String getRootDir() { + return rootDir; + } + + @Override + public String getBucket() { + return bucket; + } + + /** + * 校验文件或文件夹是否不存在(true为存在,false为不存在) + * + * @param path 文件路径 + * @return boolean + */ + @Override + public boolean fileOrDirIsExist(String path) { + path = compatibleAbsolutePath(path); + if (StringUtils.isBlank(path)) { + return false; + } + File file = new File(path); + return file.exists(); + } + + /** + * 校验是否是文件夹(true为文件夹,false为文件) + * + * @param path 文件路径 + * @return boolean + */ + @Override + public boolean isDirectory(String path) { + path = compatibleAbsolutePath(path); + if (StringUtils.isBlank(path)) { + return false; + } + File file = new File(path); + return file.isDirectory(); + } + + /** + * 过滤路径下文件后缀名(不区分大小写)并返回符合条件的文件集合 + * + * @param path 文件夹路径 + * @param fileSuffix 文件后缀名(不区分大小写) + * @return List 返回符合条件的文件集合 + */ + @Override + public List filterFileSuffix(String path, String fileSuffix) { + if (StringUtils.isEmpty(path) || StringUtils.isEmpty(fileSuffix)) { + return null; + } + path = compatibleAbsolutePath(path); + File sourceFile = new File(path); + List filePaths = new ArrayList<>(); + if (!sourceFile.exists()) { + return null; + } + File[] files = sourceFile.listFiles(); + if (files != null && files.length != 0) { + for (File file : files) { + if (file.isFile()) { + if (file.getName().toLowerCase().endsWith(fileSuffix.toLowerCase())) { + filePaths.add(formatPath(path + FILE_SEPARATOR + file.getName())); + } + } + } + } + + return filePaths; + } + + + /** + * 创建指定目录 + * + * @param dir 需要创建的目录 例如:/abc/def + * @return boolean + */ + @Override + public boolean createDir(String dir) { + dir = compatibleAbsolutePath(dir); + try { + File file = FileUtil.mkdir(dir); + if (file != null) { + return true; + } + return false; + } catch (Exception e) { + LogUtil.error(LogEnum.FILE_UTIL, "创建文件夹异常: {}", e); + return false; + } + } + + /** + * 创建多个指定目录 + * + * @param paths + * @return boolean + */ + @Override + public boolean createDirs(String... paths) { + if (null == paths || paths.length < MagicNumConstant.ONE) { + return true; + } + for (String path : paths) { + if (path == null) { + continue; + } + if (!createDir(path)) { + return false; + } + } + return true; + } + + /** + * 指定目录中创建文件 + * + * @param dir 需要创建的目录 例如:/abc/def + * @param fileName 需要创建的文件 例如:dd.txt + * @return boolean + */ + @Override + public boolean createFile(String dir, String fileName) { + try { + File file = FileUtil.touch(dir + SymbolConstant.SLASH + fileName); + if (file != null) { + return true; + } + return false; + } catch (Exception e) { + LogUtil.error(LogEnum.FILE_UTIL, "创建文件异常: {}", e); + return false; + } + } + + /** + * 新建或追加文件 + * + * @param filePath 文件绝对路径 + * @param content 文件内容 + * @param append 文件是否是追加 + * @return + */ + @Override + public boolean createOrAppendFile(String filePath, String content, boolean append) { + File file = new File(filePath); + FileOutputStream outputStream = null; + try { + if (!file.exists()) { + file.createNewFile(); + } + outputStream = new FileOutputStream(file, append); + outputStream.write(content.getBytes(CharsetUtil.defaultCharset())); + outputStream.flush(); + } catch (IOException e) { + LogUtil.error(LogEnum.FILE_UTIL, e); + return false; + } finally { + if (outputStream != null) { + try { + outputStream.close(); + } catch (IOException e) { + LogUtil.error(LogEnum.FILE_UTIL, e); + } + } + } + return true; + } + + /** + * 删除目录 或者文件 + * + * @param dirOrFile 需要删除的目录 或者文件 例如:/abc/def 或者 /abc/def/dd.txt + * @return boolean + */ + @Override + public boolean deleteDirOrFile(String dirOrFile) { + return FileUtil.del(dirOrFile); + } + + /** + * 复制文件 到指定目录下 单个文件 + * + * @param sourceFile 需要复制的文件 例如:/abc/def/dd.txt + * @param targetPath 需要放置的目标目录 例如:/abc/dd + * @return boolean + */ + @Override + public boolean copyFile(String sourceFile, String targetPath) { + if (StringUtils.isEmpty(sourceFile) || StringUtils.isEmpty(targetPath)) { + return false; + } + sourceFile = compatibleAbsolutePath(sourceFile); + targetPath = compatibleAbsolutePath(targetPath); + try { + String fileName = sourceFile.substring(sourceFile.lastIndexOf(SymbolConstant.SLASH) + 1); + File file = FileUtil.copy(sourceFile, targetPath + SymbolConstant.SLASH + fileName, true); + if (file != null) { + return true; + } + return false; + } catch (Exception e) { + LogUtil.error(LogEnum.FILE_UTIL, "复制文件异常: {}", e); + return false; + } + } + + @Override + public boolean copyFile(String sourcePath, String targetPath, Integer type) { + return false; + } + + /** + * 复制路径下文件并重命名 + * + * @param sourceFile 需要复制的文件 例如:/abc/def/dd.txt + * @param targetFile 目标文件全路径 + * @return boolean + */ + @Override + public boolean copyFileAndRename(String sourceFile, String targetFile) { + if (StringUtils.isEmpty(sourceFile) || StringUtils.isEmpty(targetFile)) { + return false; + } + sourceFile = compatibleAbsolutePath(sourceFile); + targetFile = compatibleAbsolutePath(targetFile); + try { + File copyFile = FileUtil.copy(sourceFile, targetFile, true); + if (copyFile != null) { + return true; + } + return false; + } catch (Exception e) { + LogUtil.error(LogEnum.SERVING, " failed to copy file original path: {} ,target path: {} ,exception: {}", sourceFile, targetFile, e); + return false; + } + } + + /** + * 复制路径下文件及文件夹到指定目录下 多个文件 包含目录与文件并存情况 + * + * 通过本地文件复制方式 + * + * @param sourcePath 需要复制的文件目录 例如:/abc/def + * @param targetPath 需要放置的目标目录 例如:/abc/dd + * @return boolean + */ + @Override + public boolean copyPath(String sourcePath, String targetPath) { + if (StringUtils.isEmpty(sourcePath) || StringUtils.isEmpty(targetPath)) { + return false; + } + sourcePath = compatibleAbsolutePath(sourcePath); + targetPath = compatibleAbsolutePath(targetPath); + try { + return copyLocalPath(sourcePath, targetPath); + } catch (Exception e) { + LogUtil.error(LogEnum.FILE_UTIL, " failed to Copy file original path: {} ,target path: {} ,Exception: {}", sourcePath, targetPath, e); + return false; + } + } + + /** + * 复制文件夹到指定目录下 + * + * @param sourcePath 需要复制的文件夹 例如:/abc/def + * @param targetPath 需要放置的目标目录 例如:/abc/dd 复制成功路径/abc/dd/def* + * @return boolean + */ + @Override + public boolean copyDir(String sourcePath, String targetPath) { + if (StringUtils.isEmpty(sourcePath) || StringUtils.isEmpty(targetPath)) { + return false; + } + sourcePath = compatibleAbsolutePath(sourcePath); + targetPath = formatPath(compatibleAbsolutePath(targetPath) + FILE_SEPARATOR + new File(sourcePath).getName()); + try { + return copyLocalPath(sourcePath, targetPath); + } catch (Exception e) { + LogUtil.error(LogEnum.FILE_UTIL, " failed to Copy file original path: {} ,target path: {} ,Exception: {}", sourcePath, targetPath, e); + return false; + } + } + + /** + * 复制文件 到指定目录下 多个文件 包含目录与文件并存情况 + * + * @param sourcePath 需要复制的文件目录 例如:/abc/def + * @param targetPath 需要放置的目标目录 例如:/abc/dd + * @return boolean + */ + private boolean copyLocalPath(String sourcePath, String targetPath) { + if (!StringUtils.isEmpty(sourcePath) && !StringUtils.isEmpty(targetPath)) { + sourcePath = formatPath(sourcePath); + if (sourcePath.endsWith(FILE_SEPARATOR)) { + sourcePath = sourcePath.substring(MagicNumConstant.ZERO, sourcePath.lastIndexOf(FILE_SEPARATOR)); + } + targetPath = formatPath(targetPath); + File sourceFile = new File(sourcePath); + if (sourceFile.exists()) { + File[] files = sourceFile.listFiles(); + if (files != null && files.length != 0) { + for (File file : files) { + try { + if (file.isDirectory()) { + File fileDir = new File(targetPath + FILE_SEPARATOR + file.getName()); + if (!fileDir.exists()) { + fileDir.mkdirs(); + } + copyLocalPath(sourcePath + FILE_SEPARATOR + file.getName(), targetPath + FILE_SEPARATOR + file.getName()); + } + if (file.isFile()) { + File fileTargetPath = new File(targetPath); + if (!fileTargetPath.exists()) { + fileTargetPath.mkdirs(); + } + copyLocalFile(file.getAbsolutePath(), targetPath + FILE_SEPARATOR + file.getName()); + } + } catch (Exception e) { + LogUtil.error(LogEnum.FILE_UTIL, "failed to copy folder original path: {} , target path : {} ,Exception: {}", sourcePath, targetPath, e); + return false; + } + } + } + return true; + } + } + return false; + } + + /** + * 复制单个文件到指定目录下 单个文件 + * + * @param sourcePath 需要复制的文件 例如:/abc/def/cc.txt + * @param targetPath 需要放置的目标目录 例如:/abc/dd + * @return boolean + */ + private boolean copyLocalFile(String sourcePath, String targetPath) { + if (StringUtils.isEmpty(sourcePath) || StringUtils.isEmpty(targetPath)) { + return false; + } + sourcePath = formatPath(sourcePath); + targetPath = formatPath(targetPath); + try (InputStream input = new FileInputStream(sourcePath); + FileOutputStream output = new FileOutputStream(targetPath)) { + FileCopyUtils.copy(input, output); + return true; + } catch (IOException e) { + LogUtil.error(LogEnum.FILE_UTIL, " failed to copy file original path: {} ,target path: {} ,Exception:{} ", sourcePath, targetPath, e); + return false; + } + } + + /** + * zip解压并删除压缩文件 + * @param sourceFile zip源文件 例如:/abc/z.zip + */ + @Override + public boolean unzip(String sourceFile, String targetPath) { + if (StringUtils.isEmpty(sourceFile) || StringUtils.isEmpty(targetPath)) { + return false; + } + if (!sourceFile.toLowerCase().endsWith(ZIP)) { + return false; + } + //绝对路径 + String sourceAbsolutePath = getRootDir() + sourceFile; + String targetPathAbsolutePath = getRootDir() + targetPath; + ZipFile zipFile = null; + InputStream in = null; + OutputStream out = null; + File absoluteSourceFile = new File(compatiblePath(sourceAbsolutePath)); + File targetFileDir = new File(compatiblePath(targetPathAbsolutePath)); + if (!targetFileDir.exists()) { + boolean targetMkdir = targetFileDir.mkdirs(); + if (!targetMkdir) { + LogUtil.error(LogEnum.FILE_UTIL, "{} failed to create target folder before decompression", sourceAbsolutePath); + } + } + try { + zipFile = new ZipFile(absoluteSourceFile); + //判断压缩文件编码方式,并重新获取文件对象 + try { + zipFile.close(); + zipFile = new ZipFile(absoluteSourceFile, CHARACTER_GBK); + } catch (Exception e) { + zipFile.close(); + zipFile = new ZipFile(absoluteSourceFile); + LogUtil.error(LogEnum.FILE_UTIL, "{} the encoding mode of decompressed compressed file is changed to UTF-8,Exception:{}", sourceAbsolutePath, e); + } + ZipEntry entry; + Enumeration enumeration = zipFile.getEntries(); + while (enumeration.hasMoreElements()) { + entry = (ZipEntry) enumeration.nextElement(); + String entryName = entry.getName(); + File fileDir; + if (entry.isDirectory()) { + fileDir = new File(targetPathAbsolutePath + entry.getName()); + if (!fileDir.exists()) { + boolean fileMkdir = fileDir.mkdirs(); + if (!fileMkdir) { + LogUtil.error(LogEnum.FILE_UTIL, "failed to create folder {} while decompressing {}", fileDir, sourceAbsolutePath); + } + } + } else { + //若文件夹未创建则创建文件夹 + if (entryName.contains(FILE_SEPARATOR)) { + String zipDirName = entryName.substring(MagicNumConstant.ZERO, entryName.lastIndexOf(FILE_SEPARATOR)); + fileDir = new File(targetPathAbsolutePath + zipDirName); + if (!fileDir.exists()) { + boolean fileMkdir = fileDir.mkdirs(); + if (!fileMkdir) { + LogUtil.error(LogEnum.FILE_UTIL, "failed to create folder {} while decompressing {}", fileDir, sourceAbsolutePath); + } + } + } + in = zipFile.getInputStream((ZipArchiveEntry) entry); + out = new FileOutputStream(new File(targetPathAbsolutePath, entryName)); + org.apache.commons.io.IOUtils.copyLarge(in, out); + in.close(); + out.close(); + } + } + boolean deleteZipFile = absoluteSourceFile.delete(); + if (!deleteZipFile) { + LogUtil.error(LogEnum.FILE_UTIL, "{} compressed file deletion failed after decompression", sourceAbsolutePath); + } + return true; + } catch (IOException e) { + LogUtil.error(LogEnum.FILE_UTIL, "{} decompression failed,Exception: {}", sourceAbsolutePath, e); + return false; + } finally { + //关闭未关闭的io流 + closeIoFlow(sourceAbsolutePath, zipFile, in, out); + } + } + + /** + * windows 与 linux 的路径兼容 + * + * @param path linux下的路径 + * @return path 兼容windows后的路径 + */ + private String compatiblePath(String path) { + if (path == null) { + return null; + } + if (System.getProperties().getProperty(OS_NAME).contains(WINDOWS)) { + path = path.replace(getRootDir(), SymbolConstant.SLASH); + path = path.replace(SymbolConstant.SLASH, FILE_SEPARATOR); + path = rootWindowsPath + path; + } + return path; + } + + /** + * 关闭未关闭的io流 + * + * @param sourceAbsolutePath 源路径 + * @param zipFile 压缩文件对象 + * @param in 输入流 + * @param out 输出流 + */ + private void closeIoFlow(String sourceAbsolutePath, ZipFile zipFile, InputStream in, OutputStream out) { + if (in != null) { + try { + in.close(); + } catch (IOException e) { + LogUtil.error(LogEnum.FILE_UTIL, "{} input stream shutdown failed,Exception: {}", sourceAbsolutePath, e); + } + } + if (out != null) { + try { + out.close(); + } catch (IOException e) { + LogUtil.error(LogEnum.FILE_UTIL, "{} output stream shutdown failed,Exception: {}", sourceAbsolutePath, e); + } + } + if (zipFile != null) { + try { + zipFile.close(); + } catch (IOException e) { + LogUtil.error(LogEnum.FILE_UTIL, "{} input stream shutdown failed,Exception: {}", sourceAbsolutePath, e); + } + } + } + + /** + * 解压压缩包 包含目录与子目录 + * + * @param sourceFile 需要复制的文件 例如:/abc/def/aaa.rar + * @return boolean + */ + @Override + public boolean unzip(String sourceFile) { + try { + File file = ZipUtil.unzip(sourceFile); + if (file != null) { + return true; + } + return false; + } catch (Exception e) { + LogUtil.error(LogEnum.FILE_UTIL, "解压异常: {}", e); + return false; + } + } + + /** + * 压缩 目录 或者文件 到压缩包 + * + * @param dirOrFile 目录或者文件 例如: /abc/def/aaa.txt , /abc/def + * @param zipPath 压缩包全路径名 例如: /abc/def/aa.zip + * @return boolean + */ + @Override + public boolean zipDirOrFile(String dirOrFile, String zipPath) { + try { + File file = ZipUtil.zip(dirOrFile, zipPath); + if (file != null) { + return true; + } + return false; + } catch (Exception e) { + LogUtil.error(LogEnum.FILE_UTIL, "压缩异常: {}", e); + return false; + } + } + + @Override + public BufferedInputStream getInputStream(String path) { + return FileUtil.getInputStream(path); + } + + @Override + public void download(String path, HttpServletResponse response) { + if (path == null) { + return; + } + FileInputStream fis = null; + ServletOutputStream out = null; + try { + File file = new File(path); + fis = new FileInputStream(file); + out = response.getOutputStream(); + IOUtils.copy(fis, out); + response.flushBuffer(); + } catch (IOException e) { + e.printStackTrace(); + } finally { + if (fis != null) { + try { + fis.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + //此处记得关闭输出Servlet流 + IoUtil.close(out); + } + } + + @Override + public void filterFilePageWithPath(FilePageDTO filePageDTO) { + if (ObjectUtil.isEmpty(filePageDTO) || StringUtils.isEmpty(filePageDTO.getFilePath())) { + return; + } + File file = new File(filePageDTO.getFilePath()); + if (!file.exists()) { + return; + } + File[] files = file.listFiles(); + if (files.length > 0) { + filePageDTO.setTotal(Long.valueOf(files.length)); + int start = (filePageDTO.getPageNum() - 1) * filePageDTO.getPageSize(); + int end = filePageDTO.getPageNum() * filePageDTO.getPageSize(); + List fileDTOS = new ArrayList<>(); + for (int i = (start <= files.length ? start : files.length); i < (end <= files.length ? end : files.length); i++) { + FileDTO fileDTO = FileDTO.builder().name(files[i].getName()) + .path(files[i].getAbsolutePath()) + .lastModified(new Date(files[i].lastModified())) + .size(files[i].length()) + .dir(files[i].isDirectory()).build(); + fileDTOS.add(fileDTO); + } + filePageDTO.setRows(fileDTOS); + } + } +} diff --git a/dubhe-server/common-biz/file/src/main/java/org/dubhe/biz/file/api/impl/NfsFileStoreApiImpl.java b/dubhe-server/common-biz/file/src/main/java/org/dubhe/biz/file/api/impl/NfsFileStoreApiImpl.java new file mode 100644 index 0000000..ddbc792 --- /dev/null +++ b/dubhe-server/common-biz/file/src/main/java/org/dubhe/biz/file/api/impl/NfsFileStoreApiImpl.java @@ -0,0 +1,152 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.file.api.impl; + +import org.dubhe.biz.file.api.FileStoreApi; +import org.dubhe.biz.file.dto.FilePageDTO; +import org.dubhe.biz.file.utils.NfsUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import javax.servlet.http.HttpServletResponse; +import java.io.BufferedInputStream; +import java.util.List; + +/** + * @description Nfs文件存储接口 + * @date 2021-04-20 + */ +@Deprecated +@Component(value = "nfsFileStoreApiImpl") +public class NfsFileStoreApiImpl implements FileStoreApi { + + @Autowired + private NfsUtil nfsUtil; + + @Value("${storage.file-store-root-path}") + private String rootDir; + + @Value("/${minio.bucketName}/") + private String bucket; + + @Override + public String getRootDir(){ + return rootDir; + } + + @Override + public String getBucket(){ + return bucket; + } + + @Override + public boolean fileOrDirIsExist(String path) { + return nfsUtil.fileOrDirIsEmpty(path); + } + + @Override + public boolean isDirectory(String path) { + return false; + } + + @Override + public List filterFileSuffix(String path, String fileSuffix) { + return null; + } + + @Override + public boolean createDir(String dir) { + return nfsUtil.createDir(dir); + } + + @Override + public boolean createDirs(String... paths) { + return nfsUtil.createDirs(true,paths); + } + + @Override + public boolean createFile(String dir, String fileName) { + return nfsUtil.createFile(dir,fileName); + } + + @Override + public boolean createOrAppendFile(String filePath, String content, boolean append) { + return false; + } + + @Override + public boolean deleteDirOrFile(String dirOrFile) { + return nfsUtil.deleteDirOrFile(dirOrFile); + } + + @Override + public boolean copyFile(String sourceFile, String targetPath) { + return nfsUtil.copyFile(sourceFile,targetPath); + } + + @Override + public boolean copyFile(String sourceFile, String targetPath, Integer type) { + return false; + } + + @Override + public boolean copyFileAndRename(String sourceFile, String targetFile) { + return false; + } + + @Override + public boolean copyPath(String sourcePath, String targetPath) { + return nfsUtil.copyNfsPath(sourcePath, targetPath); + } + + @Override + public boolean copyDir(String sourcePath, String targetPath) { + return false; + } + + @Override + public boolean unzip(String sourceFile, String targetPath) { + return nfsUtil.unzip(sourceFile,targetPath); + } + + @Override + public boolean unzip(String sourceFile) { + return nfsUtil.unZip(sourceFile); + } + + @Override + public boolean zipDirOrFile(String dirOrFile, String zipName) { + return nfsUtil.zipDirOrFile(dirOrFile,zipName); + } + + @Override + public BufferedInputStream getInputStream(String path) { + return nfsUtil.getInputStream(path); + } + + @Override + public void download(String path, HttpServletResponse response) { + return; + } + + @Override + public void filterFilePageWithPath(FilePageDTO filePageDTO) { + + } +} diff --git a/dubhe-server/common-biz/file/src/main/java/org/dubhe/biz/file/api/impl/ShellFileStoreApiImpl.java b/dubhe-server/common-biz/file/src/main/java/org/dubhe/biz/file/api/impl/ShellFileStoreApiImpl.java new file mode 100644 index 0000000..74fc431 --- /dev/null +++ b/dubhe-server/common-biz/file/src/main/java/org/dubhe/biz/file/api/impl/ShellFileStoreApiImpl.java @@ -0,0 +1,267 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.file.api.impl; + +import org.dubhe.biz.file.api.FileStoreApi; +import org.dubhe.biz.file.dto.FilePageDTO; +import org.dubhe.biz.file.enums.CopyTypeEnum; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import javax.servlet.http.HttpServletResponse; +import java.io.*; +import java.util.List; +import java.util.Objects; + +/** + * @description 通过shell指令存储文件接口实现类 + * @date 2021-05-06 + */ +@Deprecated +@Component(value = "shellFileStoreApiImpl") +public class ShellFileStoreApiImpl implements FileStoreApi { + + /** + * 服务暴露的IP地址 + */ + @Value("${storage.file-store}") + private String ip; + + /** + * 文件存储服务器用户名 + */ + @Value("${data.server.userName}") + private String userName; + + /** + * 拷贝源路径下文件或文件夹命令 + */ + public static final String COPY_COMMAND = "ssh %s@%s \"mkdir -p %s && cp -rf %s %s && echo success\""; + /** + * 拷贝多文件夹下文件命令 + */ + public static final String COPY_DIR_COMMAND = "ssh %s@%s \"mkdir -p %s && cp -rf %s* %s && echo success\""; + + /** + * 删除服务器无效文件(大文件) + * 示例:rsync --delete-before -d /空目录 /需要回收的源目录 + */ + public static final String DEL_COMMAND = "ssh %s@%s \"mkdir -p %s; rsync --delete-before -d %s %s; rmdir %s %s\""; + + /** + * 拷贝文件并重命名 + */ + public static final String COPY_RENAME_COMMAND = "ssh %s@%s \"cp -rf %s %s && echo success\""; + + /** + * 文件复制 + * rsync -avP --exclude={'dir'} sourcePath targetPath 将原路径复制到目标路径下,过滤dir目录 + * 示例:rsync -avP --exclude={'V0001'} /root/test/ /root/test2/ + */ + public static final String COPY_AVP_COMMAND = "ssh %s@%s rsync -avP --exclude={'%s'} %s %s"; + + /** + * 修改文件夹名称 + * mv sourcePathName targetPathName 将原目录名称修改为目标目录名称 + * 示例:mv /root/test2/versionFile/V0002 /root/test2/versionFile/V0001 + */ + public static final String UPDATE_NAME_COMMAND = "ssh %s@%s mv %s %s"; + + @Value("${storage.file-store-root-path}") + private String rootDir; + + @Value("/${minio.bucketName}/") + private String bucket; + + @Override + public String getRootDir() { + return rootDir; + } + + @Override + public String getBucket() { + return bucket; + } + + @Override + public boolean fileOrDirIsExist(String path) { + return false; + } + + @Override + public boolean isDirectory(String path) { + return false; + } + + @Override + public List filterFileSuffix(String path, String fileSuffix) { + return null; + } + + @Override + public boolean createDir(String dir) { + return false; + } + + @Override + public boolean createDirs(String... paths) { + return false; + } + + @Override + public boolean createFile(String dir, String fileName) { + return false; + } + + @Override + public boolean createOrAppendFile(String filePath, String content, boolean append) { + return false; + } + + @Override + public boolean deleteDirOrFile(String dirOrFile) { + return false; + } + + @Override + public boolean copyFile(String sourceFile, String targetPath) { + return false; + } + + /** + * 使用shell拷贝文件或路径 + * + * @param sourcePath 需要复制的文件或路径 例如:/abc/def/cc.txt or /abc/def* + * @param targetPath 需要放置的目标目录 例如:/abc/dd + * @param type CopyTypeEnum的 + * @return boolean + */ + @Override + public boolean copyFile(String sourcePath, String targetPath, Integer type) { + //绝对路径 + String sourceAbsolutePath = formatPath(getRootDir() + sourcePath); + String targetPathAbsolutePath = formatPath(getRootDir() + targetPath); + String[] command; + if (CopyTypeEnum.COPY_FILE.getKey().equals(type)) { + command = new String[]{"/bin/sh", "-c", String.format(COPY_COMMAND, userName, ip, targetPathAbsolutePath, sourceAbsolutePath, targetPathAbsolutePath)}; + } else { + command = new String[]{"/bin/sh", "-c", String.format(COPY_DIR_COMMAND, userName, ip, targetPathAbsolutePath, sourceAbsolutePath, targetPathAbsolutePath)}; + } + boolean flag = false; + Process process; + try { + process = Runtime.getRuntime().exec(command); + if (isCopySuccess(process)) { + flag = true; + } + } catch (IOException e) { + LogUtil.error(LogEnum.FILE_UTIL, "copy file failed, filePath:{}, targetPath:{}", sourcePath, targetPath, e); + } + return flag; + } + + /** + * 判断拷贝结果 + * + * @param process + * @return + */ + public boolean isCopySuccess(Process process) { + try (InputStream stream = process.getInputStream(); + InputStreamReader iReader = new InputStreamReader(stream); + BufferedReader bReader = new BufferedReader(iReader)) { + String line; + while (Objects.nonNull(line = bReader.readLine())) { + boolean temp = line.contains("success"); + if (temp) { + return true; + } + } + } catch (Exception e) { + LogUtil.error(LogEnum.FILE_UTIL, "Read stream failed : {}", e); + } + return false; + } + + /** + * 拷贝文件并重命名 + * + * @param sourceFile 需要复制的文件 例如:/abc/def/aa.py + * @param targetFile 需要放置的目标目录 例如:/abc/dd/bb.py + * @return + */ + @Override + public boolean copyFileAndRename(String sourceFile, String targetFile) { + //绝对路径 + String sourceAbsolutePath = formatPath(rootDir + sourceFile); + String targetPathAbsolutePath = formatPath(rootDir + targetFile); + String[] command = new String[]{"/bin/sh", "-c", String.format(COPY_RENAME_COMMAND, userName, ip, sourceAbsolutePath, targetPathAbsolutePath)}; + boolean flag = false; + Process process; + try { + process = Runtime.getRuntime().exec(command); + if (isCopySuccess(process)) { + flag = true; + } + } catch (IOException e) { + LogUtil.error(LogEnum.FILE_UTIL, "copy file failed, filePath:{}, targetPath:{}, because:{}", sourceFile, targetFile, e); + } + return flag; + } + + @Override + public boolean copyPath(String sourcePath, String targetPath) { + return false; + } + + @Override + public boolean copyDir(String sourcePath, String targetPath) { + return false; + } + + @Override + public boolean unzip(String sourceFile, String targetPath) { + return false; + } + + @Override + public boolean unzip(String sourceFile) { + return false; + } + + @Override + public boolean zipDirOrFile(String dirOrFile, String zipPath) { + return false; + } + + @Override + public BufferedInputStream getInputStream(String path) { + return null; + } + + @Override + public void download(String path, HttpServletResponse response) { + + } + + @Override + public void filterFilePageWithPath(FilePageDTO filePageDTO) { + + } +} \ No newline at end of file diff --git a/dubhe-server/common-biz/file/src/main/java/org/dubhe/biz/file/config/NfsConfig.java b/dubhe-server/common-biz/file/src/main/java/org/dubhe/biz/file/config/NfsConfig.java new file mode 100644 index 0000000..5d269e4 --- /dev/null +++ b/dubhe-server/common-biz/file/src/main/java/org/dubhe/biz/file/config/NfsConfig.java @@ -0,0 +1,41 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.file.config; + +import lombok.Data; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +/** + * @description NFS config + * @date 2020-05-13 + */ +@Data +@Component +public class NfsConfig { + + @Value("${storage.file-store}") + private String nfsIp; + + @Value("${storage.file-store-root-path}") + private String rootDir; + + @Value("/${minio.bucketName}/") + private String bucket; + +} diff --git a/dubhe-server/common-biz/file/src/main/java/org/dubhe/biz/file/dto/FileDTO.java b/dubhe-server/common-biz/file/src/main/java/org/dubhe/biz/file/dto/FileDTO.java new file mode 100644 index 0000000..50bc603 --- /dev/null +++ b/dubhe-server/common-biz/file/src/main/java/org/dubhe/biz/file/dto/FileDTO.java @@ -0,0 +1,54 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.file.dto; + +import lombok.Builder; +import lombok.Data; +import java.io.Serializable; +import java.util.Date; + +/** + * @description 文件详情 + * @date 2021-05-07 + */ +@Builder +@Data +public class FileDTO implements Serializable { + + /** + * 文件名称 + */ + private String name; + /** + * 文件路径 + */ + private String path; + /** + * 文件最近一次修改时间 + */ + private Date lastModified; + /** + * 文件大小 + */ + private long size; + /** + * 是否文件夹 + */ + private boolean dir; + +} diff --git a/dubhe-server/common-biz/file/src/main/java/org/dubhe/biz/file/dto/FilePageDTO.java b/dubhe-server/common-biz/file/src/main/java/org/dubhe/biz/file/dto/FilePageDTO.java new file mode 100644 index 0000000..d381750 --- /dev/null +++ b/dubhe-server/common-biz/file/src/main/java/org/dubhe/biz/file/dto/FilePageDTO.java @@ -0,0 +1,51 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.file.dto; + +import lombok.Data; +import java.util.List; + +/** + * @description 文件分页查询相应实体 + * @date 2021-06-16 + */ +@Data +public class FilePageDTO { + + /** + * 查询路径 + */ + private String filePath; + /** + * 页码 + */ + private int pageNum; + /** + * 页容量 + */ + private int pageSize; + /** + * 记录数 + */ + private Long total; + /** + * 页集合 + */ + private List rows; + +} diff --git a/dubhe-server/common-biz/file/src/main/java/org/dubhe/biz/file/dto/MinioDownloadDTO.java b/dubhe-server/common-biz/file/src/main/java/org/dubhe/biz/file/dto/MinioDownloadDTO.java new file mode 100644 index 0000000..5c4ec21 --- /dev/null +++ b/dubhe-server/common-biz/file/src/main/java/org/dubhe/biz/file/dto/MinioDownloadDTO.java @@ -0,0 +1,60 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.file.dto; + +import lombok.Data; + +import java.util.HashMap; +import java.util.Map; + +/** + * @description minio下载参数实体 + * @date 2021-06-24 + */ +@Data +public class MinioDownloadDTO { + /** + * 下载压缩包请求token + */ + private String token; + /** + * 下载压缩包请求参数 + */ + private String body; + /** + * 下载压缩包请求需要的header + */ + private Map headers; + /** + * 下载压缩包文件名称 + */ + private String zipName; + + public MinioDownloadDTO() { + } + + public MinioDownloadDTO(String token, String body, String zipName) { + this.token = token; + this.body = body; + this.zipName = zipName; + Map headers = new HashMap<>(); + headers.put("Content-Type", "text/plain;charset=UTF-8"); + this.headers = headers; + } + +} diff --git a/dubhe-server/common-biz/file/src/main/java/org/dubhe/biz/file/enums/BizPathEnum.java b/dubhe-server/common-biz/file/src/main/java/org/dubhe/biz/file/enums/BizPathEnum.java new file mode 100644 index 0000000..ba5c5c3 --- /dev/null +++ b/dubhe-server/common-biz/file/src/main/java/org/dubhe/biz/file/enums/BizPathEnum.java @@ -0,0 +1,105 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.file.enums; + +import org.dubhe.biz.base.enums.BizEnum; + +import java.util.HashMap; +import java.util.Map; + +/** + * @description 业务NFS路径枚举 + * @date 2020-05-13 + */ +public enum BizPathEnum { + /** + * 模型开发 路径命名 + */ + NOTEBOOK(BizEnum.NOTEBOOK, "notebook"), + /** + * 算法管理 路径命名 + */ + ALGORITHM(BizEnum.ALGORITHM, "algorithm-manage"), + /** + * 模型管理 路径命名 + */ + MODEL(BizEnum.MODEL, "model"), + /** + * 模型优化 路径命名 + */ + MODEL_OPT(BizEnum.MODEL_OPT, "model-opt"), + + /** + * 度量管理 路径命名 + */ + MEASURE(BizEnum.MEASURE, "exported-metrics"); + + BizPathEnum(BizEnum bizEnum, String bizPath) { + this.bizEnum = bizEnum; + this.bizPath = bizPath; + } + + /** + * 业务模块 + */ + private BizEnum bizEnum; + /** + * 业务模块路径 + */ + private String bizPath; + + + private static final Map RESOURCE_ENUM_MAP = new HashMap() { + { + for (BizPathEnum enums : BizPathEnum.values()) { + put(enums.getCreateResource(), enums); + } + } + }; + + /** + * 根据createResource获取BizEnum + * + * @param createResource + * @return + */ + public static BizPathEnum getByCreateResource(int createResource) { + return RESOURCE_ENUM_MAP.get(createResource); + } + + + public String getBizName() { + return bizEnum == null ? null : bizEnum.getBizName(); + } + + public Integer getCreateResource() { + return bizEnum == null ? null : bizEnum.getCreateResource(); + } + + public String getBizPath() { + return bizPath; + } + + public BizEnum getBizEnum() { + return bizEnum; + } + + public String getBizCode() { + return bizEnum == null ? null : bizEnum.getBizCode(); + } +} diff --git a/dubhe-server/common-biz/file/src/main/java/org/dubhe/biz/file/enums/CopyTypeEnum.java b/dubhe-server/common-biz/file/src/main/java/org/dubhe/biz/file/enums/CopyTypeEnum.java new file mode 100644 index 0000000..149a3e9 --- /dev/null +++ b/dubhe-server/common-biz/file/src/main/java/org/dubhe/biz/file/enums/CopyTypeEnum.java @@ -0,0 +1,54 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.file.enums; + +/** + * @description 文件复制类型枚举 + * @date 2021-01-21 + */ +public enum CopyTypeEnum { + + COPY_FILE(0,"拷贝文件"), + COPY_DIR(1,"拷贝文件夹内文件") + ; + + private Integer key; + + private String value; + + CopyTypeEnum(Integer key, String value) { + this.key = key; + this.value = value; + } + + public Integer getKey() { + return key; + } + + public void setKey(Integer key) { + this.key = key; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } +} diff --git a/dubhe-server/common-biz/file/src/main/java/org/dubhe/biz/file/exception/NfsBizException.java b/dubhe-server/common-biz/file/src/main/java/org/dubhe/biz/file/exception/NfsBizException.java new file mode 100644 index 0000000..a5654eb --- /dev/null +++ b/dubhe-server/common-biz/file/src/main/java/org/dubhe/biz/file/exception/NfsBizException.java @@ -0,0 +1,42 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.file.exception; + +import lombok.Getter; +import org.dubhe.biz.base.exception.BusinessException; + +/** + * @description NFS utils 工具异常 + * @date 2020-06-15 + */ +@Getter +public class NfsBizException extends BusinessException { + + private static final long serialVersionUID = 1L; + + + public NfsBizException(Throwable cause){ + super(cause); + } + + public NfsBizException(String msg){ + super(msg); + } + + +} diff --git a/dubhe-server/common-biz/file/src/main/java/org/dubhe/biz/file/utils/DubheFileUtil.java b/dubhe-server/common-biz/file/src/main/java/org/dubhe/biz/file/utils/DubheFileUtil.java new file mode 100644 index 0000000..25e06a3 --- /dev/null +++ b/dubhe-server/common-biz/file/src/main/java/org/dubhe/biz/file/utils/DubheFileUtil.java @@ -0,0 +1,410 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.file.utils; + +import cn.hutool.core.codec.Base64; +import cn.hutool.core.io.IoUtil; +import cn.hutool.core.util.CharsetUtil; +import cn.hutool.core.util.IdUtil; +import cn.hutool.poi.excel.BigExcelWriter; +import cn.hutool.poi.excel.ExcelUtil; +import org.apache.poi.util.IOUtils; +import org.dubhe.biz.base.exception.BusinessException; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.springframework.web.multipart.MultipartFile; + +import javax.servlet.ServletOutputStream; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.*; +import java.security.MessageDigest; +import java.text.DecimalFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; +import java.util.Map; + +/** + * @description File工具类,扩展 hutool 工具包 + * @date 2020-03-14 + */ +public class DubheFileUtil extends cn.hutool.core.io.FileUtil { + + /** + * 定义GB的计算常量 + */ + private static final int GB = 1024 * 1024 * 1024; + /** + * 定义MB的计算常量 + */ + private static final int MB = 1024 * 1024; + /** + * 定义KB的计算常量 + */ + private static final int KB = 1024; + + /** + * 格式化小数 + */ + private static final DecimalFormat DF = new DecimalFormat("0.00"); + + /** + * MultipartFile转File + */ + public static File toFile(MultipartFile multipartFile) { + // 获取文件名 + String fileName = multipartFile.getOriginalFilename(); + // 获取文件后缀 + String prefix = "." + getExtensionName(fileName); + File file = null; + try { + // 用uuid作为文件名,防止生成的临时文件重复 + file = File.createTempFile(IdUtil.simpleUUID(), prefix); + // MultipartFile to File + multipartFile.transferTo(file); + } catch (IOException e) { + e.printStackTrace(); + } + return file; + } + + /** + * 获取文件扩展名,不带 . + */ + public static String getExtensionName(String filename) { + if ((filename != null) && (filename.length() > 0)) { + int dot = filename.lastIndexOf('.'); + if ((dot > -1) && (dot < (filename.length() - 1))) { + return filename.substring(dot + 1); + } + } + return filename; + } + + /** + * Java文件操作 获取不带扩展名的文件名 + */ + public static String getFileNameNoEx(String filename) { + if ((filename != null) && (filename.length() > 0)) { + int dot = filename.lastIndexOf('.'); + if ((dot > -1) && (dot < (filename.length()))) { + return filename.substring(0, dot); + } + } + return filename; + } + + /** + * 文件大小转换 + */ + public static String getSize(long size) { + String resultSize; + if (size / GB >= 1) { + //如果当前Byte的值大于等于1GB + resultSize = DF.format(size / (float) GB) + "GB "; + } else if (size / MB >= 1) { + //如果当前Byte的值大于等于1MB + resultSize = DF.format(size / (float) MB) + "MB "; + } else if (size / KB >= 1) { + //如果当前Byte的值大于等于1KB + resultSize = DF.format(size / (float) KB) + "KB "; + } else { + resultSize = size + "B "; + } + return resultSize; + } + + /** + * inputStream 转 File + */ + static File inputStreamToFile(InputStream ins, String name) throws Exception { + File file = new File(System.getProperty("java.io.tmpdir") + File.separator + name); + if (file.exists()) { + return file; + } + OutputStream os = new FileOutputStream(file); + int bytesRead; + int len = 8192; + byte[] buffer = new byte[len]; + while ((bytesRead = ins.read(buffer, 0, len)) != -1) { + os.write(buffer, 0, bytesRead); + } + os.close(); + ins.close(); + return file; + } + + /** + * 将文件名解析成文件的上传路径 + */ + public static File upload(MultipartFile file, String filePath) { + Date date = new Date(); + SimpleDateFormat format = new SimpleDateFormat("yyyyMMddhhmmssS"); + String name = getFileNameNoEx(file.getOriginalFilename()); + String suffix = getExtensionName(file.getOriginalFilename()); + String nowStr = "-" + format.format(date); + try { + String fileName = name + nowStr + "." + suffix; + String path = filePath + fileName; + // getCanonicalFile 可解析正确各种路径 + File dest = new File(path).getCanonicalFile(); + // 检测是否存在目录 + if (!dest.getParentFile().exists()) { + dest.getParentFile().mkdirs(); + } + // 文件写入 + file.transferTo(dest); + return dest; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public static String fileToBase64(File file) throws Exception { + FileInputStream inputFile = new FileInputStream(file); + String base64; + byte[] buffer = new byte[(int) file.length()]; + inputFile.read(buffer); + inputFile.close(); + base64 = Base64.encode(buffer); + return base64.replaceAll("[\\s*\t\n\r]", ""); + } + + /** + * 导出excel + */ + public static void downloadExcel(List> list, HttpServletResponse response) throws IOException { + String tempPath = System.getProperty("java.io.tmpdir") + IdUtil.fastSimpleUUID() + ".xlsx"; + File file = new File(tempPath); + BigExcelWriter writer = ExcelUtil.getBigWriter(file); + // 一次性写出内容,使用默认样式,强制输出标题 + writer.write(list, true); + //response为HttpServletResponse对象 + response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"); + //test.xls是弹出下载对话框的文件名,不能为中文,中文请自行编码 + response.setHeader("Content-Disposition", "attachment;filename=file.xlsx"); + ServletOutputStream out = response.getOutputStream(); + // 终止后删除临时文件 + file.deleteOnExit(); + writer.flush(out, true); + //此处记得关闭输出Servlet流 + IoUtil.close(out); + } + + /** + * 下载文件 + */ + public static void download(String path, HttpServletResponse response) { + if (path == null) { + return; + } + FileInputStream fis = null; + ServletOutputStream out = null; + try { + File file = new File(path); + fis = new FileInputStream(file); + out = response.getOutputStream(); + IOUtils.copy(fis, out); + response.flushBuffer(); + } catch (IOException e) { + e.printStackTrace(); + } finally { + if (fis != null) { + try { + fis.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + //此处记得关闭输出Servlet流 + IoUtil.close(out); + } + } + + public static String getFileType(String type) { + String documents = "txt doc pdf ppt pps xlsx xls docx"; + String music = "mp3 wav wma mpa ram ra aac aif m4a"; + String video = "avi mpg mpe mpeg asf wmv mov qt rm mp4 flv m4v webm ogv ogg"; + String image = "bmp dib pcp dif wmf gif jpg tif eps psd cdr iff tga pcd mpt png jpeg"; + if (image.contains(type)) { + return "图片"; + } else if (documents.contains(type)) { + return "文档"; + } else if (music.contains(type)) { + return "音乐"; + } else if (video.contains(type)) { + return "视频"; + } else { + return "其他"; + } + } + + public static void checkSize(long maxSize, long size) { + // 1M + int len = 1024 * 1024; + if (size > (maxSize * len)) { + throw new BusinessException("文件超出规定大小"); + } + } + + /** + * 判断两个文件是否相同 + */ + public static boolean check(File file1, File file2) { + String img1Md5 = getMd5(file1); + String img2Md5 = getMd5(file2); + return img1Md5.equals(img2Md5); + } + + /** + * 判断两个文件是否相同 + */ + public static boolean check(String file1Md5, String file2Md5) { + return file1Md5.equals(file2Md5); + } + + private static byte[] getByte(File file) { + // 得到文件长度 + byte[] b = new byte[(int) file.length()]; + try { + InputStream in = new FileInputStream(file); + try { + in.read(b); + } catch (IOException e) { + e.printStackTrace(); + } + } catch (FileNotFoundException e) { + e.printStackTrace(); + return null; + } + return b; + } + + private static String getMd5(byte[] bytes) { + // 16进制字符 + char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; + try { + MessageDigest mdTemp = MessageDigest.getInstance("MD5"); + mdTemp.update(bytes); + byte[] md = mdTemp.digest(); + int j = md.length; + char[] str = new char[j * 2]; + int k = 0; + // 移位 输出字符串 + for (byte byte0 : md) { + str[k++] = hexDigits[byte0 >>> 4 & 0xf]; + str[k++] = hexDigits[byte0 & 0xf]; + } + return new String(str); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + /** + * 下载文件 + * + * @param request / + * @param response / + * @param file / + */ + public static void downloadFile(HttpServletRequest request, HttpServletResponse response, File file, boolean deleteOnExit) { + response.setCharacterEncoding(request.getCharacterEncoding()); + response.setContentType("application/octet-stream"); + FileInputStream fis = null; + try { + fis = new FileInputStream(file); + response.setHeader("Content-Disposition", "attachment; filename=" + file.getName()); + IOUtils.copy(fis, response.getOutputStream()); + response.flushBuffer(); + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (fis != null) { + try { + fis.close(); + if (deleteOnExit) { + file.deleteOnExit(); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } + + public static String getMd5(File file) { + return getMd5(getByte(file)); + } + + + /** + * 生成文件 + * @param filePath 文件绝对路径 + * @param content 文件内容 + * @param append 文件是否是追加 + * @return + */ + public static boolean generateFile(String filePath,String content,boolean append){ + File file = new File(filePath); + FileOutputStream outputStream = null; + try { + if (!file.exists()){ + file.createNewFile(); + } + outputStream = new FileOutputStream(file,append); + outputStream.write(content.getBytes(CharsetUtil.defaultCharset())); + outputStream.flush(); + }catch (IOException e) { + LogUtil.error(LogEnum.FILE_UTIL,e); + return false; + }finally { + if (outputStream != null){ + try { + outputStream.close(); + } catch (IOException e) { + LogUtil.error(LogEnum.FILE_UTIL,e); + } + } + } + return true; + } + + + /** + * 压缩文件目录 + * + * @param zipDir 待压缩文件夹路径 + * @param zipFile 压缩完成zip文件绝对路径 + * @return + */ + public static boolean zipPath(String zipDir,String zipFile) { + if (zipDir == null) { + return false; + } + File zip = new File(zipFile); + cn.hutool.core.util.ZipUtil.zip(zip, CharsetUtil.defaultCharset(), true, + (f) -> !f.isDirectory(), + new File(zipDir).listFiles()); + return true; + } + +} diff --git a/dubhe-server/common-biz/file/src/main/java/org/dubhe/biz/file/utils/IOUtil.java b/dubhe-server/common-biz/file/src/main/java/org/dubhe/biz/file/utils/IOUtil.java new file mode 100644 index 0000000..51b09e6 --- /dev/null +++ b/dubhe-server/common-biz/file/src/main/java/org/dubhe/biz/file/utils/IOUtil.java @@ -0,0 +1,47 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.file.utils; + +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; + +import java.io.Closeable; +import java.io.IOException; + +/** + * @description IO流操作工具类 + * @date 2020-10-14 + */ +public class IOUtil { + + /** + * 循环的依次关闭流 + * + * @param closeableList 要被关闭的流集合 + */ + public static void close(Closeable... closeableList) { + for (Closeable closeable : closeableList) { + try { + if (closeable != null) { + closeable.close(); + } + } catch (IOException e) { + LogUtil.error(LogEnum.IO_UTIL, "关闭流异常,异常信息:{}", e); + } + } + } +} diff --git a/dubhe-server/common-biz/file/src/main/java/org/dubhe/biz/file/utils/LocalFileUtil.java b/dubhe-server/common-biz/file/src/main/java/org/dubhe/biz/file/utils/LocalFileUtil.java new file mode 100644 index 0000000..22fd076 --- /dev/null +++ b/dubhe-server/common-biz/file/src/main/java/org/dubhe/biz/file/utils/LocalFileUtil.java @@ -0,0 +1,434 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.file.utils; + +import cn.hutool.core.util.StrUtil; +import lombok.Getter; +import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; +import org.apache.commons.compress.archivers.zip.ZipFile; +import org.apache.commons.io.IOUtils; +import org.dubhe.biz.base.constant.MagicNumConstant; +import org.dubhe.biz.base.utils.StringUtils; +import org.dubhe.biz.file.config.NfsConfig; +import org.dubhe.biz.file.enums.CopyTypeEnum; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import org.springframework.util.FileCopyUtils; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.util.Enumeration; +import java.util.Objects; +import java.util.zip.ZipEntry; + +/** + * @description 本地文件操作工具类 + * @date 2020-08-19 + */ +@Component +@Getter +public class LocalFileUtil { + + @Autowired + private NfsConfig nfsConfig; + + private static final String FILE_SEPARATOR = File.separator; + + private static final String ZIP = ".zip"; + + private static final String CHARACTER_GBK = "GBK"; + + private static final String OS_NAME = "os.name"; + + private static final String WINDOWS = "Windows"; + + /** + * nfs服务暴露的IP地址 + */ + @Value("${storage.file-store}") + private String nfsIp; + + /** + * 文件存储服务器用户名 + */ + @Value("${data.server.userName}") + private String userName; + + /** + * 拷贝源路径下文件或文件夹命令 + */ + public static final String COPY_COMMAND = "ssh %s@%s \"mkdir -p %s && cp -rf %s %s && echo success\""; + /** + * 拷贝多文件夹下文件命令 + */ + public static final String COPY_DIR_COMMAND = "ssh %s@%s \"mkdir -p %s && cp -rf %s* %s && echo success\""; + /** + * 拷贝文件并重命名 + */ + public static final String COPY_RENAME_COMMAND = "ssh %s@%s \"cp -rf %s %s && echo success\""; + + @Value("${storage.file-store-root-path}") + private String nfsRootPath; + + @Value("${storage.file-store-root-windows-path}") + private String nfsRootWindowsPath; + + /** + * windows 与 linux 的路径兼容 + * + * @param path linux下的路径 + * @return path 兼容windows后的路径 + */ + private String compatiblePath(String path) { + if (path == null) { + return null; + } + if (System.getProperties().getProperty(OS_NAME).contains(WINDOWS)) { + path = path.replace(nfsRootPath, StrUtil.SLASH); + path = path.replace(StrUtil.SLASH, FILE_SEPARATOR); + path = nfsRootWindowsPath + path; + } + return path; + } + + + /** + * 本地解压zip包并删除压缩文件 + * + * @param sourcePath zip源文件 例如:/abc/z.zip + * @param targetPath 解压后的目标文件夹 例如:/abc/ + * @return boolean + */ + public boolean unzipLocalPath(String sourcePath, String targetPath) { + if (StringUtils.isEmpty(sourcePath) || StringUtils.isEmpty(targetPath)) { + return false; + } + if (!sourcePath.toLowerCase().endsWith(ZIP)) { + return false; + } + //绝对路径 + String sourceAbsolutePath = nfsConfig.getRootDir() + sourcePath; + String targetPathAbsolutePath = nfsConfig.getRootDir() + targetPath; + ZipFile zipFile = null; + InputStream in = null; + OutputStream out = null; + File sourceFile = new File(compatiblePath(sourceAbsolutePath)); + File targetFileDir = new File(compatiblePath(targetPathAbsolutePath)); + if (!targetFileDir.exists()) { + boolean targetMkdir = targetFileDir.mkdirs(); + if (!targetMkdir) { + LogUtil.error(LogEnum.LOCAL_FILE_UTIL, "{}failed to create target folder before decompression", sourceAbsolutePath); + } + } + try { + zipFile = new ZipFile(sourceFile); + //判断压缩文件编码方式,并重新获取文件对象 + try { + zipFile.close(); + zipFile = new ZipFile(sourceFile, CHARACTER_GBK); + } catch (Exception e) { + zipFile.close(); + zipFile = new ZipFile(sourceFile); + LogUtil.error(LogEnum.LOCAL_FILE_UTIL, "{}the encoding mode of decompressed compressed file is changed to UTF-8:{}", sourceAbsolutePath, e); + } + ZipEntry entry; + Enumeration enumeration = zipFile.getEntries(); + while (enumeration.hasMoreElements()) { + entry = (ZipEntry) enumeration.nextElement(); + String entryName = entry.getName(); + File fileDir; + if (entry.isDirectory()) { + fileDir = new File(targetPathAbsolutePath + entry.getName()); + if (!fileDir.exists()) { + boolean fileMkdir = fileDir.mkdirs(); + if (!fileMkdir) { + LogUtil.error(LogEnum.LOCAL_FILE_UTIL, "failed to create folder {} while decompressing {}", fileDir, sourceAbsolutePath); + } + } + } else { + //若文件夹未创建则创建文件夹 + if (entryName.contains(FILE_SEPARATOR)) { + String zipDirName = entryName.substring(MagicNumConstant.ZERO, entryName.lastIndexOf(FILE_SEPARATOR)); + fileDir = new File(targetPathAbsolutePath + zipDirName); + if (!fileDir.exists()) { + boolean fileMkdir = fileDir.mkdirs(); + if (!fileMkdir) { + LogUtil.error(LogEnum.LOCAL_FILE_UTIL, "failed to create folder {} while decompressing {}", fileDir, sourceAbsolutePath); + } + } + } + in = zipFile.getInputStream((ZipArchiveEntry) entry); + out = new FileOutputStream(new File(targetPathAbsolutePath, entryName)); + IOUtils.copyLarge(in, out); + in.close(); + out.close(); + } + } + boolean deleteZipFile = sourceFile.delete(); + if (!deleteZipFile) { + LogUtil.error(LogEnum.LOCAL_FILE_UTIL, "{}compressed file deletion failed after decompression", sourceAbsolutePath); + } + return true; + } catch (IOException e) { + LogUtil.error(LogEnum.LOCAL_FILE_UTIL, "{}decompression failed: {}", sourceAbsolutePath, e); + return false; + } finally { + //关闭未关闭的io流 + closeIoFlow(sourceAbsolutePath, zipFile, in, out); + } + + } + + /** + * 关闭未关闭的io流 + * + * @param sourceAbsolutePath 源路径 + * @param zipFile 压缩文件对象 + * @param in 输入流 + * @param out 输出流 + */ + private void closeIoFlow(String sourceAbsolutePath, ZipFile zipFile, InputStream in, OutputStream out) { + if (in != null) { + try { + in.close(); + } catch (IOException e) { + LogUtil.error(LogEnum.LOCAL_FILE_UTIL, "{}input stream shutdown failed: {}", sourceAbsolutePath, e); + } + } + if (out != null) { + try { + out.close(); + } catch (IOException e) { + LogUtil.error(LogEnum.LOCAL_FILE_UTIL, "{}output stream shutdown failed: {}", sourceAbsolutePath, e); + } + } + if (zipFile != null) { + try { + zipFile.close(); + } catch (IOException e) { + LogUtil.error(LogEnum.LOCAL_FILE_UTIL, "{}input stream shutdown failed: {}", sourceAbsolutePath, e); + } + } + } + + + /** + * 复制单个文件到指定目录下 单个文件 + * + * @param sourcePath 需要复制的文件 例如:/abc/def/cc.txt + * @param targetPath 需要放置的目标目录 例如:/abc/dd + * @return boolean + */ + private boolean copyLocalFile(String sourcePath, String targetPath) { + if (StringUtils.isEmpty(sourcePath) || StringUtils.isEmpty(targetPath)) { + return false; + } + sourcePath = formatPath(sourcePath); + targetPath = formatPath(targetPath); + try (InputStream input = new FileInputStream(sourcePath); + FileOutputStream output = new FileOutputStream(targetPath)) { + FileCopyUtils.copy(input, output); + return true; + } catch (IOException e) { + LogUtil.error(LogEnum.LOCAL_FILE_UTIL, " failed to copy file original path: {} ,target path: {} ,copyLocalFile:{} ", sourcePath, targetPath, e); + return false; + } + } + + /** + * NFS 复制目录到指定目录下 多个文件 包含目录与文件并存情况 + * + * 通过本地文件复制方式 + * + * @param sourcePath 需要复制的文件目录 例如:/abc/def + * @param targetPath 需要放置的目标目录 例如:/abc/dd + * @return boolean + */ + public boolean copyPath(String sourcePath, String targetPath) { + if (StringUtils.isEmpty(sourcePath) || StringUtils.isEmpty(targetPath)) { + return false; + } + sourcePath = formatPath(sourcePath); + targetPath = formatPath(targetPath); + try { + return copyLocalPath(nfsConfig.getRootDir() + sourcePath, nfsConfig.getRootDir() + targetPath); + } catch (Exception e) { + LogUtil.error(LogEnum.LOCAL_FILE_UTIL, " failed to Copy file original path: {} ,target path: {} ,copyPath: {}", sourcePath, targetPath, e); + return false; + } + } + + /** + * 复制文件 到指定目录下 多个文件 包含目录与文件并存情况 + * + * @param sourcePath 需要复制的文件目录 例如:/abc/def + * @param targetPath 需要放置的目标目录 例如:/abc/dd + * @return boolean + */ + private boolean copyLocalPath(String sourcePath, String targetPath) { + if (!StringUtils.isEmpty(sourcePath) && !StringUtils.isEmpty(targetPath)) { + sourcePath = formatPath(sourcePath); + if (sourcePath.endsWith(FILE_SEPARATOR)) { + sourcePath = sourcePath.substring(MagicNumConstant.ZERO, sourcePath.lastIndexOf(FILE_SEPARATOR)); + } + targetPath = formatPath(targetPath); + File sourceFile = new File(sourcePath); + if (sourceFile.exists()) { + File[] files = sourceFile.listFiles(); + if (files != null && files.length != 0) { + for (File file : files) { + try { + if (file.isDirectory()) { + File fileDir = new File(targetPath + FILE_SEPARATOR + file.getName()); + if (!fileDir.exists()) { + fileDir.mkdirs(); + } + copyLocalPath(sourcePath + FILE_SEPARATOR + file.getName(), targetPath + FILE_SEPARATOR + file.getName()); + } + if (file.isFile()) { + File fileTargetPath = new File(targetPath); + if (!fileTargetPath.exists()) { + fileTargetPath.mkdirs(); + } + copyLocalFile(file.getAbsolutePath(), targetPath + FILE_SEPARATOR + file.getName()); + } + } catch (Exception e) { + LogUtil.error(LogEnum.LOCAL_FILE_UTIL, "failed to copy folder original path: {} , target path : {} ,copyLocalPath: {}", sourcePath, targetPath, e); + return false; + } + } + } + return true; + } + } + return false; + } + + /** + * 替换路径中多余的 "/" + * + * @param path + * @return String + */ + public String formatPath(String path) { + if (!StringUtils.isEmpty(path)) { + return path.replaceAll("///*", FILE_SEPARATOR); + } + return path; + } + + /** + * 拷贝文件 + * + * @param sourcePath 需要复制的文件 例如:/abc/def/cc.txt + * @param targetPath 需要放置的目标目录 例如:/abc/dd + * @return + */ + public boolean copyFile(String sourcePath, String targetPath, Integer type) { + //绝对路径 + String sourceAbsolutePath = formatPath(nfsConfig.getRootDir() + sourcePath); + String targetPathAbsolutePath = formatPath(nfsConfig.getRootDir() + targetPath); + String[] command; + if (CopyTypeEnum.COPY_FILE.getKey().equals(type)) { + command = new String[]{"/bin/sh", "-c", String.format(COPY_COMMAND, userName, nfsIp, targetPathAbsolutePath, sourceAbsolutePath, targetPathAbsolutePath)}; + } else { + command = new String[]{"/bin/sh", "-c", String.format(COPY_DIR_COMMAND, userName, nfsIp, targetPathAbsolutePath, sourceAbsolutePath, targetPathAbsolutePath)}; + } + boolean flag = false; + Process process; + try { + process = Runtime.getRuntime().exec(command); + if (isCopySuccess(process)) { + flag = true; + } + } catch (IOException e) { + LogUtil.error(LogEnum.LOCAL_FILE_UTIL, "copy file failed, filePath:{}, targetPath:{}", sourcePath, targetPath, e); + } + return flag; + } + + /** + * 拷贝文件并重命名 + * + * @param sourcePath 需要复制的文件 例如:/abc/def/aa.py + * @param targetPath 需要放置的目标目录 例如:/abc/dd/bb.py + * @return + */ + public boolean copyFileAndRename(String sourcePath, String targetPath) { + //绝对路径 + String sourceAbsolutePath = formatPath(nfsConfig.getRootDir() + sourcePath); + String targetPathAbsolutePath = formatPath(nfsConfig.getRootDir() + targetPath); + String[] command = new String[]{"/bin/sh", "-c", String.format(COPY_RENAME_COMMAND, userName, nfsIp, sourceAbsolutePath, targetPathAbsolutePath)}; + boolean flag = false; + Process process; + try { + process = Runtime.getRuntime().exec(command); + if (isCopySuccess(process)) { + flag = true; + } + } catch (IOException e) { + LogUtil.error(LogEnum.LOCAL_FILE_UTIL, "copy file failed, filePath:{}, targetPath:{}", sourcePath, targetPath, e); + } + return flag; + } + + /** + * 判断拷贝结果 + * + * @param process + * @return + */ + public boolean isCopySuccess(Process process) { + boolean flag = false; + try (InputStream stream = process.getInputStream(); + InputStreamReader iReader = new InputStreamReader(stream); + BufferedReader bReader = new BufferedReader(iReader)) { + String line; + while (Objects.nonNull(line = bReader.readLine())) { + boolean temp = line.contains("success"); + if (temp) { + flag = true; + } + } + } catch (Exception e) { + LogUtil.error(LogEnum.LOCAL_FILE_UTIL, "Read stream failed : {}", e); + } + return flag; + } + + /** + * 路径是否存在 + * @param path 路径 + * @return true 存在 false 不存在 + */ + public boolean isExist(String path) { + if(StringUtils.isBlank(path)){ + return false; + } + File file = new File(path); + return file.exists(); + } +} \ No newline at end of file diff --git a/dubhe-server/common-biz/file/src/main/java/org/dubhe/biz/file/utils/MinioUtil.java b/dubhe-server/common-biz/file/src/main/java/org/dubhe/biz/file/utils/MinioUtil.java new file mode 100644 index 0000000..c73e6ca --- /dev/null +++ b/dubhe-server/common-biz/file/src/main/java/org/dubhe/biz/file/utils/MinioUtil.java @@ -0,0 +1,283 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.file.utils; + +import cn.hutool.core.io.IoUtil; +import io.minio.CopyConditions; +import io.minio.MinioClient; +import io.minio.PutObjectOptions; +import io.minio.Result; +import io.minio.errors.InvalidEndpointException; +import io.minio.errors.InvalidPortException; +import io.minio.messages.DeleteError; +import io.minio.messages.Item; +import org.apache.commons.lang.StringUtils; +import org.dubhe.biz.base.constant.MagicNumConstant; +import org.dubhe.biz.base.constant.NumberConstant; +import org.dubhe.biz.base.exception.BusinessException; +import org.dubhe.biz.file.dto.FileDTO; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import javax.annotation.PostConstruct; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.Charset; +import java.util.*; + +/** + * @description Minio工具类 + * @date 2020-05-09 + */ +@Service +public class MinioUtil { + + @Value("${minio.url}") + private String url; + @Value("${minio.accessKey}") + private String accessKey; + @Value("${minio.secretKey}") + private String secretKey; + + private MinioClient client; + + @PostConstruct + public void init() { + try { + client = new MinioClient(url, accessKey, secretKey); + } catch (InvalidEndpointException e) { + LogUtil.warn(LogEnum.BIZ_DATASET, "MinIO endpoint invalid. e, {}", e); + } catch (InvalidPortException e) { + LogUtil.warn(LogEnum.BIZ_DATASET, "MinIO endpoint port invalid. e, {}", e); + } + } + + /** + * 写文件 + * + * @param bucket 桶名称 + * @param fullFilePath 文件存储的全路径,包括文件名,非'/'开头. e.g. dataset/12/annotation/test.txt + * @param content file content. can not be null + */ + public void writeString(String bucket, String fullFilePath, String content) throws Exception { + boolean isExist = client.bucketExists(bucket); + if (!isExist) { + client.makeBucket(bucket); + } + InputStream inputStream = IoUtil.toUtf8Stream(content); + PutObjectOptions options = new PutObjectOptions(inputStream.available(), MagicNumConstant.NEGATIVE_ONE); + client.putObject(bucket, fullFilePath, inputStream, options); + } + + /** + * 读取文件 + * + * @param bucketName 桶 + * @param fullFilePath 文件存储的全路径,包括文件名,非'/'开头. e.g. dataset/12/annotation/test.txt + * @return String + */ + public String readString(String bucketName, String fullFilePath) throws Exception { + try (InputStream is = client.getObject(bucketName, fullFilePath)) { + return IoUtil.read(is, Charset.defaultCharset()); + } + } + + /** + * 文件删除 + * + * @param bucketName 桶 + * @param fullFilePath 文件存储的全路径,包括文件名,非'/'开头. e.g. dataset/12/annotation/test.txt + */ + public void del(String bucketName, String fullFilePath) throws Exception { + Iterable> items = client.listObjects(bucketName, fullFilePath); + Set files = new HashSet<>(); + for (Result item : items) { + files.add(item.get().objectName()); + } + Iterable> results = client.removeObjects(bucketName, files); + for (Result result : results) { + result.get(); + } + } + + /** + * 批量删除文件 + * + * @param bucketName 桶 + * @param objectNames 对象名称 + */ + public void delFiles(String bucketName, List objectNames) throws Exception { + Iterable> results = client.removeObjects(bucketName, objectNames); + for (Result result : results) { + result.get(); + } + } + + /** + * 获取对象名称 + * + * @param bucketName 桶名称 + * @param prefix 前缀 + * @return List 对象名称列表 + * @throws Exception + */ + public List getObjects(String bucketName, String prefix) throws Exception { + List fileNames = new ArrayList<>(); + Iterable> results = client.listObjects(bucketName, prefix); + for (Result result : results) { + Item item = result.get(); + fileNames.add(item.objectName()); + } + return fileNames; + } + + /** + * 获取路径下文件数量 + * + * @param bucketName 桶名称 + * @param prefix 前缀 + * @return InputStream 文件流 + * @throws Exception + */ + public int getCount(String bucketName, String prefix) throws Exception { + int count = NumberConstant.NUMBER_0; + Iterable> results = client.listObjects(bucketName, prefix); + for (Result result : results) { + count++; + } + return count; + } + + /** + * 获取文件流 + * + * @param bucketName 桶 + * @param objectName 对象名称 + * @return InputStream 文件流 + * @throws Exception + */ + public InputStream getObjectInputStream(String bucketName, String objectName) throws Exception { + return client.getObject(bucketName, objectName); + } + + /** + * 文件夹复制 + * + * @param bucketName 桶 + * @param sourceFiles 源文件 + * @param targetDir 目标文件夹 + */ + public void copyDir(String bucketName, List sourceFiles, String targetDir) { + sourceFiles.forEach(sourceFile -> { + InputStream inputStream = null; + try { + String sourceObjectName = sourceFile; + String targetObjectName = targetDir + "/" + StringUtils.substringAfterLast(sourceObjectName, "/"); + inputStream = client.getObject(bucketName, sourceObjectName); + byte[] buf = new byte[512]; + int bytesRead; + int count = MagicNumConstant.ZERO; + while ((bytesRead = inputStream.read(buf, MagicNumConstant.ZERO, buf.length)) >= MagicNumConstant.ZERO) { + count += bytesRead; + } + PutObjectOptions options = new PutObjectOptions(count, MagicNumConstant.ZERO); + client.putObject(bucketName, targetObjectName, client.getObject(bucketName, sourceObjectName), options); + } catch (Exception e) { + LogUtil.error(LogEnum.BIZ_DATASET, "MinIO file copy exception, {}", e); + } finally { + try { + if (inputStream != null) { + inputStream.close(); + } + } catch (IOException e) { + LogUtil.error(LogEnum.BIZ_DATASET, "MinIO file read stream closed failed, {}", e); + } + } + }); + } + + /** + * minio拷贝操作 + * + * @param bucketName 桶名 + * @param sourceFiles 需要复制的标注文件名 + * @param targetDir 目标文件夹路径 + */ + public void copyObject(String bucketName, List sourceFiles, String targetDir) { + CopyConditions copyConditions = new CopyConditions(); + sourceFiles.forEach(sourceFile -> { + try { + String targetName = targetDir + "/" + StringUtils.substringAfterLast(sourceFile, "/"); + client.copyObject(bucketName, targetName, null, null, bucketName, sourceFile, null, copyConditions); + } catch (Exception e) { + LogUtil.error(LogEnum.BIZ_DATASET, "MinIO file copy failed, {}", e); + } + }); + } + + /** + * 获取文件列表 + * + * @param bucketName 桶 + * @param prefix 前缀 + * @param recursive 是否递归查询 + * @return List 文件列表 + */ + public List fileList(String bucketName, String prefix, boolean recursive) { + List result = new ArrayList<>(); + Iterable> items = client.listObjects(bucketName, prefix, false); + for (Result resultItem : items) { + try { + Item item = resultItem.get(); + FileDTO fileDto = FileDTO.builder().dir(item.isDir()).size(item.size()).path(item.objectName()) + .name(item.objectName().substring(item.objectName().lastIndexOf("/") + 1, item.objectName().length())) + .build(); + if(!item.isDir()) { + fileDto.setLastModified(Date.from(item.lastModified().toInstant())); + } + result.add(fileDto); + } catch (Exception e) { + LogUtil.error(LogEnum.BIZ_DATASET, "get file list error {}", e); + } + } + return result; + } + + /** + * 生成一个给HTTP PUT请求用的presigned URL。浏览器/移动端的客户端可以用这个URL进行上传, + * 即使其所在的存储桶是私有的。这个presigned URL可以设置一个失效时间,默认值是7天 + * + * @param bucketName 存储桶名称 + * @param objectName 存储桶里的对象名称 + * @param expires 失效时间(以秒为单位),默认是7天,不得大于七天 + * @return String + */ + public String getEncryptedPutUrl(String bucketName, String objectName, Integer expires) { + if (StringUtils.isEmpty(objectName)) { + throw new BusinessException("object name cannot be empty"); + } + try { + return client.presignedPutObject(bucketName, objectName, expires); + } catch (Exception e) { + LogUtil.error(LogEnum.BIZ_DATASET, e.getMessage()); + throw new BusinessException("MinIO an error occurred, please contact the administrator"); + } + } + +} diff --git a/dubhe-server/common-biz/file/src/main/java/org/dubhe/biz/file/utils/MinioWebTokenBody.java b/dubhe-server/common-biz/file/src/main/java/org/dubhe/biz/file/utils/MinioWebTokenBody.java new file mode 100644 index 0000000..7aab91e --- /dev/null +++ b/dubhe-server/common-biz/file/src/main/java/org/dubhe/biz/file/utils/MinioWebTokenBody.java @@ -0,0 +1,81 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.file.utils; + +import cn.hutool.http.HttpRequest; +import com.alibaba.fastjson.JSONObject; +import lombok.Data; +import org.apache.commons.lang.StringUtils; +import org.dubhe.biz.file.dto.MinioDownloadDTO; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.List; + +/** + * @description Minio web访问token实体 + * @date 2020-05-09 + */ +@Data +@Service +public class MinioWebTokenBody { + + @Value("${minioweb.GetToken.url}") + private String tokenUrl; + @Value("${minioweb.GetToken.param.id}") + private int id; + @Value("${minioweb.GetToken.param.jsonrpc}") + private String jsonrpc; + @Value("${minioweb.GetToken.param.method}") + private String method; + @Value("${minioweb.zip.url}") + private String zipUrl; + @Value("${minio.accessKey}") + private String accessKey; + @Value("${minio.secretKey}") + private String secretKey; + @Value("${minio.url}") + private String url; + + /** + * 生成文件下载请求参数方法 + * + * @param bucketName 桶名称 + * @param prefix 前缀 + * @param objects 对象名称 + * @return MinioDownloadDto 下载请求参数 + */ + public MinioDownloadDTO getDownloadParam(String bucketName, String prefix, List objects, String zipName) { + String paramTemplate = "{\"id\":%d,\"jsonrpc\":\"%s\",\"params\":{\"username\":\"%s\",\"password\":\"%s\"},\"method\":\"%s\"}"; + String downloadBodyTemplate = "{\"bucketName\":\"%s\",\"prefix\":\"%s\",\"objects\":[%s]}"; + String param = String.format(paramTemplate, id, jsonrpc, accessKey, secretKey, method); + String result = HttpRequest.post(url + tokenUrl).contentType("application/json").body(param).execute().body(); + String token = JSONObject.parseObject(result).getJSONObject("result").getString("token"); + return new MinioDownloadDTO(token, String.format(downloadBodyTemplate, bucketName, prefix, getStrFromList(objects)), zipName); + } + + public String getStrFromList(List objects) { + List result = new ArrayList<>(); + objects.stream().forEach(s -> { + result.add("\"" + s + "\""); + }); + return StringUtils.join(result, ","); + } + +} \ No newline at end of file diff --git a/dubhe-server/common-biz/file/src/main/java/org/dubhe/biz/file/utils/NfsFactory.java b/dubhe-server/common-biz/file/src/main/java/org/dubhe/biz/file/utils/NfsFactory.java new file mode 100644 index 0000000..1b3a719 --- /dev/null +++ b/dubhe-server/common-biz/file/src/main/java/org/dubhe/biz/file/utils/NfsFactory.java @@ -0,0 +1,78 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.file.utils; + +import com.emc.ecs.nfsclient.nfs.nfs3.Nfs3; +import com.emc.ecs.nfsclient.rpc.CredentialUnix; +import org.apache.commons.pool2.PooledObject; +import org.apache.commons.pool2.PooledObjectFactory; +import org.apache.commons.pool2.impl.DefaultPooledObject; +import org.dubhe.biz.file.config.NfsConfig; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.springframework.stereotype.Component; + +import java.io.IOException; + +/** + * @description NFS工厂类 + * @date 2020-05-13 + */ +@Deprecated +@Component +public class NfsFactory implements PooledObjectFactory { + + private final NfsConfig nfsConfig; + + public NfsFactory(NfsConfig nfsConfig) { + this.nfsConfig = nfsConfig; + } + + @Override + public PooledObject makeObject() { + Nfs3 nfs3 = null; + try { + nfs3 = new Nfs3(nfsConfig.getNfsIp(), nfsConfig.getRootDir(), new CredentialUnix(0, 0, null), 3); + } catch (IOException e) { + LogUtil.error(LogEnum.NFS_UTIL, "创建NFS对象失败: ", e); + } + return new DefaultPooledObject<>(nfs3); + } + + @Override + public void destroyObject(PooledObject pooledObject) { + LogUtil.info(LogEnum.NFS_UTIL, "销毁NFS对象: ", pooledObject.getObject()); + } + + @Override + public boolean validateObject(PooledObject pooledObject) { + LogUtil.info(LogEnum.NFS_UTIL, "验证NFS对象: ", pooledObject.getObject()); + return true; + } + + @Override + public void activateObject(PooledObject pooledObject) { + LogUtil.info(LogEnum.NFS_UTIL, "激活NFS对象: ", pooledObject.getObject()); + + } + + @Override + public void passivateObject(PooledObject pooledObject) { + LogUtil.info(LogEnum.NFS_UTIL, "钝化NFS对象: ", pooledObject.getObject()); + } +} diff --git a/dubhe-server/common-biz/file/src/main/java/org/dubhe/biz/file/utils/NfsPool.java b/dubhe-server/common-biz/file/src/main/java/org/dubhe/biz/file/utils/NfsPool.java new file mode 100644 index 0000000..f971b83 --- /dev/null +++ b/dubhe-server/common-biz/file/src/main/java/org/dubhe/biz/file/utils/NfsPool.java @@ -0,0 +1,116 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.file.utils; + +import com.emc.ecs.nfsclient.nfs.nfs3.Nfs3; +import org.apache.commons.pool2.impl.GenericObjectPool; +import org.apache.commons.pool2.impl.GenericObjectPoolConfig; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.springframework.stereotype.Component; + +/** + * @description NFS3 连接池 + * @date 2020-05-18 + */ +@Deprecated +@Component +public class NfsPool { + /** + * NFS工厂对象 + */ + private NfsFactory nfsFactory; + /** + * GenericObjectPool对象 + */ + private final GenericObjectPool genericObjectPool; + /** + * 最大总共连接数 + */ + public static final int MAX_TOTAL = 300; + /** + * 最小连接数 + */ + public static final int MIN = 20; + /** + * 最大连接数 + */ + public static final int MAX = 300; + /** + * 最大等待时间 单位毫秒 + */ + public static final int MAX_WAIT_TIME = 3000; + + /** + * 初始化连接池 + * + * @param nfsFactory + */ + public NfsPool(NfsFactory nfsFactory) { + this.nfsFactory = nfsFactory; + GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig(); + poolConfig.setMaxTotal(MAX_TOTAL); + poolConfig.setMinIdle(MIN); + poolConfig.setMaxIdle(MAX); + poolConfig.setMaxWaitMillis(MAX_WAIT_TIME); + this.genericObjectPool = new GenericObjectPool<>(nfsFactory, poolConfig); + } + + /** + * 从连接池中取连接 + * + * @return nfs3 + */ + public Nfs3 getNfs() { + try { + LogUtil.info(LogEnum.NFS_UTIL,"NFS线程 活跃数量:{} ,空闲数量: {} , 等待队列数量 : {}",genericObjectPool.getNumActive(),genericObjectPool.getNumIdle(),genericObjectPool.getNumWaiters()); + return genericObjectPool.borrowObject(); + } catch (Exception e) { + LogUtil.error(LogEnum.NFS_UTIL, "获取NFS连接失败: {} ", e); + return null; + } + } + + /** + * 释放连接到连接池 + * + * @param nfs3 + */ + public void revertNfs(Nfs3 nfs3) { + try { + if(nfs3 != null){ + LogUtil.info(LogEnum.NFS_UTIL,"成功释放对象 : {} ", nfs3); + genericObjectPool.returnObject(nfs3); + } + } catch (Exception e) { + LogUtil.error(LogEnum.NFS_UTIL, " 释放NFS连接失败: ", e); + } + } + + /** + * 销毁公共池 + */ + public void destroyPool() { + try { + genericObjectPool.close(); + } catch (Exception e) { + LogUtil.error(LogEnum.NFS_UTIL, "销毁NFS连接失败: ", e); + } + } + +} diff --git a/dubhe-server/common-biz/file/src/main/java/org/dubhe/biz/file/utils/NfsUtil.java b/dubhe-server/common-biz/file/src/main/java/org/dubhe/biz/file/utils/NfsUtil.java new file mode 100644 index 0000000..b4cf344 --- /dev/null +++ b/dubhe-server/common-biz/file/src/main/java/org/dubhe/biz/file/utils/NfsUtil.java @@ -0,0 +1,776 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.file.utils; + +import cn.hutool.core.util.StrUtil; +import com.emc.ecs.nfsclient.nfs.io.Nfs3File; +import com.emc.ecs.nfsclient.nfs.io.NfsFileInputStream; +import com.emc.ecs.nfsclient.nfs.io.NfsFileOutputStream; +import lombok.Getter; +import org.apache.commons.compress.archivers.ArchiveInputStream; +import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream; +import org.apache.commons.io.IOUtils; +import org.dubhe.biz.base.constant.MagicNumConstant; +import org.dubhe.biz.base.utils.StringUtils; +import org.dubhe.biz.file.config.NfsConfig; +import org.dubhe.biz.file.exception.NfsBizException; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.util.CollectionUtils; + +import java.io.*; +import java.util.ArrayList; +import java.util.List; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; +import java.util.zip.ZipOutputStream; + +/** + * @description NFS Util + * !!!注意: 使用NFSFile 对象 业务上自行需要关闭 NFS 对象 + * @date 2020-05-12 + */ +@Deprecated +@Component +@Getter +public class NfsUtil { + + private final NfsConfig nfsConfig; + + private static final String FILE_SEPARATOR = "/"; + + private static final String ZIP = ".zip"; + + private static final String CHARACTER_GBK = "GBK"; + + private static final String CHARACTER_UTF_8 = "UTF-8"; + + private static final String UNDER_LINE = "_"; + + @Autowired + private NfsPool nfsPool; + + + public NfsUtil(NfsConfig nfsConfig) { + this.nfsConfig = nfsConfig; + } + + private String getReplaceRootPathRegex() { + String rootPath = nfsConfig.getRootDir(); + return "^" + rootPath.substring(MagicNumConstant.ZERO, rootPath.length() - MagicNumConstant.ONE); + } + + /** + * 获取NFS3File 对象 + * + * @param path 文件路径 + * @return Nfs3File + */ + public Nfs3File getNfs3File(String path) { + if (StringUtils.isEmpty(formatPath(path))) { + LogUtil.error(LogEnum.NFS_UTIL, "传入的NFS3初始化路径 {} ,无法初始化NFS3 ", path); + throw new NfsBizException("初始化路径:" + path + " 不合法"); + } + Nfs3File nfs3File; + try { + nfs3File = new Nfs3File(nfsPool.getNfs(), path); + LogUtil.info(LogEnum.NFS_UTIL, "成功获取NFS3File对象 : {} ", nfs3File.getName()); + } catch (IOException e) { + LogUtil.error(LogEnum.NFS_UTIL, "获取NFS3File对象失败 :", e); + throw new NfsBizException("未获取到NFS连接或者NFS连接池已满" + e.getMessage()); + } + return nfs3File; + } + + /** + * 获取NFS3File 对象文件的输入流 + * + * @param nfs3File + * @return BufferedInputStream + */ + public BufferedInputStream getInputStream(Nfs3File nfs3File) { + BufferedInputStream stream = null; + try { + if (!nfs3File.isFile()) { + throw new NfsBizException("此路径下查找到的对象不是文件类型,请检查文件类型是否正确!"); + } + stream = new BufferedInputStream(new NfsFileInputStream(nfs3File)); + } catch (IOException e) { + throw new NfsBizException("nfs获取对象输出流失败!"); + } + return stream; + } + + /** + * 获取NFS3File 对象文件的输入流 + * + * @param path 文件路径 + * @return BufferedInputStream + */ + public BufferedInputStream getInputStream(String path) { + Nfs3File nfs3File = getNfs3File(formatPath(path)); + if (nfs3File == null) { + throw new NfsBizException("此路径" + path + "下没有文件可以加载!"); + } + return getInputStream(nfs3File); + } + + /** + * 校验文件或文件夹是否不存在(true为不存在,false为存在) + * + * @param path 文件路径 + * @return boolean + */ + public boolean fileOrDirIsEmpty(String path) { + if (!StringUtils.isEmpty(path)) { + path = formatPath(path.startsWith(nfsConfig.getRootDir()) ? path.replaceFirst(nfsConfig.getRootDir(), StrUtil.SLASH) : path); + Nfs3File nfs3File = getNfs3File(path); + try { + if (nfs3File.exists()) { + return false; + } + } catch (IOException e) { + LogUtil.error(LogEnum.NFS_UTIL, "判断NFS File异常: ", e); + return true; + } finally { + nfsPool.revertNfs(nfs3File.getNfs()); + } + } + return true; + + } + + + /** + * 创建指定NFS目录 + * + * @param dir 需要创建的目录 例如:/abc/def + * @return boolean + */ + public boolean createDir(String dir) { + if (!StringUtils.isEmpty(dir)) { + dir = formatPath(dir); + String[] paths = dir.substring(MagicNumConstant.ONE).split(FILE_SEPARATOR); + StringBuilder sbPath = new StringBuilder(); + for (String path : paths) { + sbPath.append(FILE_SEPARATOR).append(path); + Nfs3File nfs3File = getNfs3File(sbPath.toString()); + try { + if (!nfs3File.exists()) { + nfs3File.mkdirs(); + } + } catch (IOException e) { + LogUtil.error(LogEnum.NFS_UTIL, "创建NFS目录失败:", e); + return false; + } finally { + nfsPool.revertNfs(nfs3File.getNfs()); + } + } + return true; + } + return false; + } + + /** + * 创建多个指定目录 + * + * @param removeNfsRootPath + * @param paths + * @return boolean + */ + private boolean createDir(boolean removeNfsRootPath, String... paths) { + for (String path : paths) { + if (path == null) { + continue; + } + String formatPath = path; + if (removeNfsRootPath) { + formatPath = formatPath.replaceAll(this.getReplaceRootPathRegex(), ""); + } + boolean res = createDir(formatPath); + if (!res) { + return false; + } + } + return true; + } + + + /** + * 创建指定NFS目录 + * + * @param paths 路径 例如:/nfs/abc/def/ /abc/def/ + * @param nfsRootPath 是否包含nfs根目录 true:包含 false:不包含 + * @return boolean + */ + public boolean createDirs(boolean nfsRootPath, String... paths) { + if (null == paths || paths.length < MagicNumConstant.ONE) { + return true; + } + for (String path : paths) { + if (path == null) { + continue; + } + String formatPath = path; + if (nfsRootPath) { + formatPath = formatPath.replaceAll(this.getReplaceRootPathRegex(), ""); + } + if (!createDir(formatPath)) { + return false; + } + } + return true; + } + + /** + * 指定目录NFS中创建文件 + * + * @param dir 需要创建的目录 例如:/abc/def + * @param fileName 需要创建的文件 例如:dd.txt + * @return boolean + */ + public boolean createFile(String dir, String fileName) { + if (!StringUtils.isEmpty(dir) && !StringUtils.isEmpty(fileName)) { + dir = formatPath(dir); + Nfs3File nfs3File = getNfs3File(dir + FILE_SEPARATOR + fileName); + try { + if (!nfs3File.exists()) { + nfs3File.mkdirs(); + } + nfs3File.createNewFile(); + return true; + } catch (IOException e) { + LogUtil.error(LogEnum.NFS_UTIL, "创建NFS文件失败: ", e); + } finally { + nfsPool.revertNfs(nfs3File.getNfs()); + } + } + return false; + } + + /** + * 删除NFS目录 或者文件 + * + * @param dirOrFile 需要删除的目录 或者文件 例如:/abc/def 或者 /abc/def/dd.txt + * @return boolean + */ + public boolean deleteDirOrFile(String dirOrFile) { + if (!StringUtils.isEmpty(dirOrFile)) { + dirOrFile = formatPath(dirOrFile); + try { + List nfs3FileList = getNfs3File(dirOrFile).listFiles(); + //删除目录下的子文件 + if (!CollectionUtils.isEmpty(nfs3FileList)) { + for (Nfs3File nfs3File : nfs3FileList) { + if (nfs3File.isDirectory()) { + deleteDirOrFile(nfs3File.getPath()); + } else if (nfs3File.isFile()) { + try { + nfs3File.delete(); + } finally { + nfsPool.revertNfs(nfs3File.getNfs()); + } + } + } + } + Nfs3File sourceNfsFile = getNfs3File(dirOrFile); + try { + sourceNfsFile.delete(); + } finally { + nfsPool.revertNfs(sourceNfsFile.getNfs()); + } + return true; + } catch (Exception e) { + LogUtil.error(LogEnum.NFS_UTIL, "删除NFS目录失败:", e); + } + } + return false; + } + + + /** + * 上传文件到 NFS 指定目录 + * + * @param sourceFile 本地文件 包含路径 例如:/abc/def/gg.txt + * @param targetDir 指定目录 例如:/abc/def + * @return boolean + */ + public boolean uploadFileToNfs(String sourceFile, String targetDir) { + if (StringUtils.isEmpty(sourceFile) || StringUtils.isEmpty(targetDir)) { + return false; + } + sourceFile = formatPath(sourceFile); + targetDir = formatPath(targetDir); + //本地文件对象 + File localFile = new File(sourceFile); + Nfs3File nfs3File = getNfs3File(targetDir + FILE_SEPARATOR + localFile.getName()); + try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(localFile)); + BufferedOutputStream outputStream = new BufferedOutputStream(new NfsFileOutputStream(nfs3File))) { + IOUtils.copyLarge(inputStream, outputStream); + return true; + } catch (IOException e) { + LogUtil.error(LogEnum.NFS_UTIL, "上传失败: ", e); + } finally { + nfsPool.revertNfs(nfs3File.getNfs()); + } + return false; + } + + /** + * 下载NFS文件到本地目录 + * + * @param sourceFile 指定文件 例如:/abc/def/dd.txt + * @param targetPath 目标目录 例如: /abc/dd + * @return boolean + */ + public boolean downFileFormNfs(String sourceFile, String targetPath) { + if (StringUtils.isEmpty(sourceFile) || StringUtils.isEmpty(targetPath)) { + return false; + } + sourceFile = formatPath(sourceFile); + targetPath = formatPath(targetPath); + Nfs3File nfsFile = getNfs3File(sourceFile); + if (nfsFile != null) { + try (InputStream inputStream = new BufferedInputStream(new NfsFileInputStream(nfsFile)); + OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(new File(targetPath + FILE_SEPARATOR + nfsFile.getName())))) { + IOUtils.copyLarge(inputStream, outputStream); + return true; + } catch (IOException e) { + LogUtil.error(LogEnum.NFS_UTIL, "下载失败:", e); + } finally { + nfsPool.revertNfs(nfsFile.getNfs()); + } + } + return false; + } + + + /** + * NFS 复制文件 到指定目录下 单个文件 + * + * @param sourceFile 需要复制的文件 例如:/abc/def/dd.txt + * @param targetPath 需要放置的目标目录 例如:/abc/dd + * @return boolean + */ + public boolean copyFile(String sourceFile, String targetPath) { + if (StringUtils.isEmpty(sourceFile) || StringUtils.isEmpty(targetPath)) { + return false; + } + sourceFile = formatPath(sourceFile); + targetPath = formatPath(targetPath); + Nfs3File sourceNfsFile = null; + Nfs3File targetNfsFileNew = null; + try { + sourceNfsFile = getNfs3File(sourceFile); + targetNfsFileNew = getNfs3File(targetPath + FILE_SEPARATOR + sourceNfsFile.getName()); + if (!targetNfsFileNew.exists()) { + createDir(targetPath); + } + } catch (IOException e) { + LogUtil.error(LogEnum.NFS_UTIL, "创建目标文件失败: ", e); + } + try (InputStream inputStream = new BufferedInputStream(new NfsFileInputStream(sourceNfsFile)); + OutputStream outputStream = new BufferedOutputStream(new NfsFileOutputStream(targetNfsFileNew))) { + targetNfsFileNew.createNewFile(); + IOUtils.copyLarge(inputStream, outputStream); + return true; + } catch (IOException e) { + LogUtil.error(LogEnum.NFS_UTIL, "复制失败:", e); + return false; + } finally { + nfsPool.revertNfs(sourceNfsFile.getNfs()); + nfsPool.revertNfs(targetNfsFileNew.getNfs()); + } + } + + + /** + * NFS 复制目录到指定目录下 多个文件 包含目录与文件并存情况 + * + * 通过NFS文件复制方式 可能存在NFS RPC协议超时情况 + * + * @param sourcePath 需要复制的文件目录 例如:/abc/def + * @param targetPath 需要放置的目标目录 例如:/abc/dd + * @return boolean + */ + public boolean copyNfsPath(String sourcePath, String targetPath) { + if (StringUtils.isEmpty(sourcePath) || StringUtils.isEmpty(targetPath)) { + return false; + } + sourcePath = formatPath(sourcePath); + targetPath = formatPath(targetPath); + try { + Nfs3File sourceNfsFile = getNfs3File(sourcePath); + List nfs3FileList = sourceNfsFile.listFiles(); + if (CollectionUtils.isEmpty(nfs3FileList)) { + createDir(targetPath + sourcePath.substring(sourcePath.lastIndexOf(FILE_SEPARATOR))); + } else { + for (Nfs3File nfs3File : nfs3FileList) { + if (nfs3File.isDirectory()) { + String newTargetPath = nfs3File.getPath().substring(nfs3File.getPath().lastIndexOf(FILE_SEPARATOR)); + Nfs3File newNfs3File = getNfs3File(newTargetPath); + try { + if (!newNfs3File.exists()) { + createDir(targetPath + newTargetPath); + } + copyNfsPath(nfs3File.getPath(), targetPath + newTargetPath); + } finally { + nfsPool.revertNfs(newNfs3File.getNfs()); + } + } + if (nfs3File.isFile()) { + copyFile(sourcePath + FILE_SEPARATOR + nfs3File.getName(), targetPath); + } + } + } + return true; + } catch (IOException e) { + LogUtil.error(LogEnum.NFS_UTIL, "复制失败: ", e); + return false; + } + } + + /** + * zip解压并删除压缩文件 + * 当压缩包文件较多时,可能会因为RPC超时而解压失败 + * 该方法已废弃,请使用org.dubhe.utils.LocalFileUtil类的unzipLocalPath方法来替代 + * @param sourcePath zip源文件 例如:/abc/z.zip + * @param targetPath 解压后的目标文件夹 例如:/abc/ + * @return boolean + */ + @Deprecated + public boolean unzip(String sourcePath, String targetPath) { + if (StringUtils.isEmpty(sourcePath) || StringUtils.isEmpty(targetPath)) { + return false; + } + sourcePath = formatPath(sourcePath); + targetPath = formatPath(targetPath); + if (!sourcePath.toLowerCase().endsWith(ZIP)) { + return false; + } + ArchiveInputStream zIn = null; + Nfs3File sourceNfsFile = getNfs3File(sourcePath); + try { + zIn = new ZipArchiveInputStream(new BufferedInputStream(new NfsFileInputStream(sourceNfsFile)), CHARACTER_GBK, false, true); + //判断压缩文件编码方式,并重新获取NFS对象流 + try { + zIn.getNextEntry(); + zIn.close(); + zIn = new ZipArchiveInputStream(new BufferedInputStream(new NfsFileInputStream(sourceNfsFile)), CHARACTER_GBK, false, true); + } catch (Exception e) { + zIn.close(); + zIn = new ZipArchiveInputStream(new BufferedInputStream(new NfsFileInputStream(sourceNfsFile)), CHARACTER_UTF_8, false, true); + } + ZipEntry entry; + while ((entry = (ZipEntry) zIn.getNextEntry()) != null) { + if (entry.isDirectory()) { + createDir(targetPath + FILE_SEPARATOR + entry.getName()); + } else { + //若文件夹未创建则创建文件夹 + if (entry.getName().contains(FILE_SEPARATOR)) { + String entryName = entry.getName(); + String zipDirName = entryName.substring(MagicNumConstant.ZERO, entryName.lastIndexOf(FILE_SEPARATOR)); + createDir(targetPath + FILE_SEPARATOR + zipDirName); + } + Nfs3File nfs3File = getNfs3File(targetPath + FILE_SEPARATOR + entry.getName()); + try { + if (!nfs3File.exists()) { + nfs3File.createNewFile(); + } + BufferedOutputStream bos = new BufferedOutputStream(new NfsFileOutputStream(nfs3File)); + IOUtils.copyLarge(zIn, bos); + bos.flush(); + bos.close(); + } finally { + nfsPool.revertNfs(nfs3File.getNfs()); + } + } + } + sourceNfsFile.delete(); + return true; + } catch (IOException e) { + LogUtil.error(LogEnum.NFS_UTIL, "解压失败: ", e); + return false; + } finally { + nfsPool.revertNfs(sourceNfsFile.getNfs()); + if (zIn != null) { + try { + zIn.close(); + } catch (IOException e) { + LogUtil.error(LogEnum.NFS_UTIL, "输入流关闭失败: ", e); + } + } + } + + } + + /** + * NFS 解压压缩包 包含目录与子目录 + * + * @param sourcePath 需要复制的文件 例如:/abc/def/aaa.rar + * @return boolean + */ + public boolean unZip(String sourcePath) { + sourcePath = formatPath(sourcePath); + if (StringUtils.isEmpty(sourcePath)) { + return false; + } + String fileDir = sourcePath.substring(MagicNumConstant.ZERO, sourcePath.lastIndexOf(FILE_SEPARATOR)); + ZipEntry zipEntry = null; + try (ZipInputStream zipInputStream = new ZipInputStream(new NfsFileInputStream(getNfs3File(sourcePath)))) { + while ((zipEntry = zipInputStream.getNextEntry()) != null) { + if (zipEntry.isDirectory()) { + createDir(fileDir + FILE_SEPARATOR + zipEntry.getName()); + continue; + } + Nfs3File targetNfsFileNew = getNfs3File(fileDir + FILE_SEPARATOR + zipEntry.getName()); + try (BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new NfsFileOutputStream(targetNfsFileNew))) { + targetNfsFileNew.createNewFile(); + IOUtils.copyLarge(zipInputStream, bufferedOutputStream); + } finally { + nfsPool.revertNfs(targetNfsFileNew.getNfs()); + } + } + return true; + } catch (IOException e) { + LogUtil.error(LogEnum.NFS_UTIL, "解压文件失败 : ", e); + return false; + } + } + + /** + * 压缩NFS 目录 或者文件 到压缩包 + * + * @param dirOrFile 目录或者文件 例如: /abc/def/aaa.txt , /abc/def + * @param zipName 压缩包名称 例如: aa,bb,cc + * @return boolean + */ + public boolean zipDirOrFile(String dirOrFile, String zipName) { + Nfs3File nfs3File = getNfs3File(formatPath(dirOrFile)); + try (ZipOutputStream zipOutputStream = getFileZipOutputStream(getNfsFilePath(formatPath(dirOrFile)), zipName)) { + zipFiles(zipOutputStream, nfs3File); + return true; + } catch (IOException e) { + LogUtil.error(LogEnum.NFS_UTIL, "压缩文件失败 : ", e); + return false; + } finally { + nfsPool.revertNfs(nfs3File.getNfs()); + } + } + + /** + * 获取NFS 文件压缩目录 + * + * @param dirOrFile + * @return String + */ + private String getNfsFilePath(String dirOrFile) throws IOException { + Nfs3File nfs3File = getNfs3File(formatPath(dirOrFile)); + if (nfs3File.isFile()) { + nfsPool.revertNfs(nfs3File.getNfs()); + return dirOrFile.substring(MagicNumConstant.ZERO, dirOrFile.lastIndexOf(FILE_SEPARATOR)); + } + return dirOrFile; + } + + /** + * 根据文件路劲 获取Zip文件流 + * + * @param dirOrFile + * @param zipName + * @return ZipOutputStream + */ + private ZipOutputStream getFileZipOutputStream(String dirOrFile, String zipName) throws IOException { + Nfs3File targetNfsFileNew = getNfs3File(getNfsFilePath(formatPath(dirOrFile)) + FILE_SEPARATOR + zipName + ZIP); + targetNfsFileNew.createNewFile(); + return new ZipOutputStream(new NfsFileOutputStream(targetNfsFileNew)); + } + + /** + * 压缩文件和文件夹 + * + * @param zipOutputStream + * @param nfs3File + * @return boolean + */ + public boolean zipFiles(ZipOutputStream zipOutputStream, Nfs3File nfs3File) { + try { + if (nfs3File.isFile()) { + compressZip(zipOutputStream, nfs3File, ""); + } else { + List nfs3FileList = nfs3File.listFiles(); + if (!CollectionUtils.isEmpty(nfs3FileList)) { + for (Nfs3File nfs3FileChildren : nfs3FileList) { + zipFiles(zipOutputStream, nfs3FileChildren); + } + } + } + return true; + } catch (IOException e) { + LogUtil.error(LogEnum.NFS_UTIL, "压缩文件失败 : ", e); + return false; + } + } + + /** + * 单个文件压缩 + * + * @param zipOutputStream + * @param nfs3File + */ + public void compressZip(ZipOutputStream zipOutputStream, Nfs3File nfs3File, String childPath) { + try (InputStream inputStream = new BufferedInputStream(new NfsFileInputStream(nfs3File))) { + if (StringUtils.isEmpty(childPath)) { + zipOutputStream.putNextEntry(new ZipEntry(nfs3File.getName())); + } else { + zipOutputStream.putNextEntry(new ZipEntry(childPath + FILE_SEPARATOR + nfs3File.getName())); + } + byte[] buffer = new byte[1024 * 10]; + int length; + while ((length = inputStream.read(buffer, MagicNumConstant.ZERO, buffer.length)) != -1) { + zipOutputStream.write(buffer, MagicNumConstant.ZERO, length); + } + } catch (IOException e) { + LogUtil.error(LogEnum.NFS_UTIL, "解压单个文件异常: ", e); + } finally { + nfsPool.revertNfs(nfs3File.getNfs()); + } + } + + /** + * 复制文件夹(或文件)到另一个文件夹 + * + * @param sourcePath 复制文件夹 /abc/def 复制文件:/abc/def/dd.txt + * @param targetPath /abc/dd/def + * @return boolean + */ + public boolean copyDirs(String sourcePath, String targetPath) { + Nfs3File sourceNfsFile = getNfs3File(formatPath(sourcePath)); + try { + if (!sourceNfsFile.exists()) { + LogUtil.error(LogEnum.NFS_UTIL, "sourcePath不存在, 如下{} ", sourcePath); + return false; + } + if (sourceNfsFile.isFile()) { + return copyFile(sourcePath, targetPath); + } else if (sourceNfsFile.isDirectory()) { + targetPath = targetPath + FILE_SEPARATOR + sourceNfsFile.getName(); + boolean bool = createDir(formatPath(targetPath)); + if (!bool) { + LogUtil.error(LogEnum.NFS_UTIL, "{}文件夹创建失败... ", targetPath); + return false; + } + List files = sourceNfsFile.listFiles(); + for (Nfs3File file : files) { + copyDirs(file.getPath(), targetPath); + } + } + return true; + } catch (IOException e) { + LogUtil.error(LogEnum.NFS_UTIL, "copyDirs失败, sourcePath为 , targetPath为 , 失败原因 ", sourcePath, targetPath, e); + } finally { + nfsPool.revertNfs(sourceNfsFile.getNfs()); + } + return false; + } + + /** + * 找到倒数第二新的文件夹 + * + * @param parentPath 父文件夹 + * @return + */ + public String find2ndNewDir(String parentPath) { + Nfs3File parentNfsFile = getNfs3File(formatPath(parentPath)); + try { + if (!parentNfsFile.exists() || parentNfsFile.isFile()) { + LogUtil.error(LogEnum.NFS_UTIL, "sourcePath不存在, 如下{} ", parentPath); + return ""; + } + List files = parentNfsFile.listFiles(); + List dirs = new ArrayList<>(); + for (Nfs3File file : files) { + if (file.isDirectory()) { + dirs.add(file); + } + } + if (dirs.size() < MagicNumConstant.TWO) { + return ""; + } + dirs.sort((o1, o2) -> { + try { + return (int) (o2.lastModified() - o1.lastModified()); + } catch (IOException e) { + LogUtil.error(LogEnum.NFS_UTIL, "执行异常: {} ", e); + return MagicNumConstant.ZERO; + } + }); + return dirs.get(MagicNumConstant.ONE).getName(); + + } catch (IOException e) { + LogUtil.error(LogEnum.NFS_UTIL, "findSecNewDir失败, parentPath为{}, 失败原因{}", parentPath, e); + } finally { + nfsPool.revertNfs(parentNfsFile.getNfs()); + } + return ""; + } + + /** + * 重命名文件夹 + * + * @param sourcePath 原文件夹 + * @param targetPath 目标文件夹 + * @return + */ + public void renameDir(String sourcePath, String targetPath) { + Nfs3File sourceNfsFile = getNfs3File(formatPath(sourcePath)); + Nfs3File targetNfsFile = getNfs3File(formatPath(targetPath)); + try { + if (!sourceNfsFile.exists()) { + LogUtil.error(LogEnum.NFS_UTIL, "sourcePath不存在, 如下{} ", sourcePath); + } + sourceNfsFile.rename(targetNfsFile); + } catch (IOException e) { + LogUtil.error(LogEnum.NFS_UTIL, "renameDir失败, sourcePath为{}, targetPath为{}, 失败原因{}", sourcePath, targetPath, e); + } finally { + nfsPool.revertNfs(sourceNfsFile.getNfs()); + nfsPool.revertNfs(targetNfsFile.getNfs()); + } + } + + + /** + * 替换路劲中多余的 "/" + * + * @param path 文件路径 + * @return String + */ + public String formatPath(String path) { + if (!StringUtils.isEmpty(path)) { + return path.replaceAll("///*", FILE_SEPARATOR); + } + return path; + } + + public String getAbsolutePath(String relativePath) { + return nfsConfig.getRootDir() + nfsConfig.getBucket() + relativePath; + } + +} diff --git a/dubhe-server/common-biz/log/pom.xml b/dubhe-server/common-biz/log/pom.xml new file mode 100644 index 0000000..f049317 --- /dev/null +++ b/dubhe-server/common-biz/log/pom.xml @@ -0,0 +1,46 @@ + + + + common-biz + org.dubhe.biz + 0.0.1-SNAPSHOT + + 4.0.0 + + log + 0.0.1-SNAPSHOT + Biz log 工具 + Log for Dubhe Server + + + + + org.dubhe.biz + base + ${org.dubhe.biz.base.version} + + + + org.projectlombok + lombok + ${lombok.version} + + + org.springframework + spring-web + + + javax.servlet + javax.servlet-api + ${javax.servlet-api.version} + + + + + + + + + + \ No newline at end of file diff --git a/dubhe-server/common-biz/log/src/main/java/org/dubhe/biz/log/aspect/LogAspect.java b/dubhe-server/common-biz/log/src/main/java/org/dubhe/biz/log/aspect/LogAspect.java new file mode 100644 index 0000000..e01d0aa --- /dev/null +++ b/dubhe-server/common-biz/log/src/main/java/org/dubhe/biz/log/aspect/LogAspect.java @@ -0,0 +1,81 @@ +/** + * Copyright 2019-2020 Zheng Jie + * + * Licensed 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 org.dubhe.biz.log.aspect; + +import lombok.extern.slf4j.Slf4j; +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.annotation.Around; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Pointcut; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.slf4j.MDC; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; + +import java.util.UUID; + +/** + * @description 日志切面 + * @date 2020-04-10 + */ +@Component +@Aspect +@Slf4j +public class LogAspect { + + public static final String TRACE_ID = "traceId"; + + @Pointcut("execution(* org.dubhe..task..*.*(..)))") + public void serviceAspect() { + } + + @Pointcut("execution(* org.dubhe..rest..*.*(..))) ") + public void restAspect() { + } + + @Pointcut(" serviceAspect() ") + public void aroundAspect() { + } + + @Around("aroundAspect()") + public Object around(JoinPoint joinPoint) throws Throwable { + if (StringUtils.isEmpty(MDC.get(TRACE_ID))) { + MDC.put(TRACE_ID, UUID.randomUUID().toString()); + } + return ((ProceedingJoinPoint) joinPoint).proceed(); + } + + @Around("restAspect()") + public Object aroundRest(JoinPoint joinPoint) throws Throwable { + MDC.clear(); + MDC.put(TRACE_ID, UUID.randomUUID().toString()); + return combineLogInfo(joinPoint); + } + + private Object combineLogInfo(JoinPoint joinPoint) throws Throwable { + Object[] param = joinPoint.getArgs(); + LogUtil.info(LogEnum.LOG_ASPECT, "uri:{},input:{},==>begin", joinPoint.getSignature(), param); + long start = System.currentTimeMillis(); + Object result = ((ProceedingJoinPoint) joinPoint).proceed(); + long end = System.currentTimeMillis(); + LogUtil.info(LogEnum.LOG_ASPECT, "uri:{},output:{},proc_time:{}ms,<==end", joinPoint.getSignature().toString(), + result, end - start); + return result; + } + +} diff --git a/dubhe-server/common-biz/log/src/main/java/org/dubhe/biz/log/entity/LogInfo.java b/dubhe-server/common-biz/log/src/main/java/org/dubhe/biz/log/entity/LogInfo.java new file mode 100644 index 0000000..940f168 --- /dev/null +++ b/dubhe-server/common-biz/log/src/main/java/org/dubhe/biz/log/entity/LogInfo.java @@ -0,0 +1,59 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.log.entity; + +import cn.hutool.core.date.DateUtil; +import com.alibaba.fastjson.annotation.JSONField; +import lombok.Data; +import lombok.experimental.Accessors; +import org.dubhe.biz.base.constant.MagicNumConstant; + +import java.io.Serializable; + +/** + * @description 日志对象封装类 + * @date 2020-06-29 + */ +@Data +@Accessors(chain = true) +public class LogInfo implements Serializable { + + private static final long serialVersionUID = 5250395474667395607L; + + @JSONField(ordinal = MagicNumConstant.ONE) + private String traceId; + + @JSONField(ordinal = MagicNumConstant.TWO) + private String type; + + @JSONField(ordinal = MagicNumConstant.THREE) + private String level; + + @JSONField(ordinal = MagicNumConstant.FOUR) + private String location; + + @JSONField(ordinal = MagicNumConstant.FIVE) + private String time = DateUtil.now(); + + @JSONField(ordinal = MagicNumConstant.SIX) + private Object info; + + public void setInfo(Object info) { + this.info = info; + } +} diff --git a/dubhe-server/common-biz/log/src/main/java/org/dubhe/biz/log/enums/LogEnum.java b/dubhe-server/common-biz/log/src/main/java/org/dubhe/biz/log/enums/LogEnum.java new file mode 100644 index 0000000..0a09a89 --- /dev/null +++ b/dubhe-server/common-biz/log/src/main/java/org/dubhe/biz/log/enums/LogEnum.java @@ -0,0 +1,95 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.log.enums; + +import lombok.Getter; + +/** + * @description 日志类型枚举类 + * @date 2020-06-23 + */ +@Getter +public enum LogEnum { + + // 系统报错日志 + SYS_ERR, + // 用户请求日志 + REST_REQ, + //全局请求日志 + GLOBAL_REQ, + // 训练模块 + BIZ_TRAIN, + //算法管理模块 + BIZ_ALGORITHM, + // 系统模块 + BIZ_SYS, + // 模型模块 + BIZ_MODEL, + // 模型优化 + MODEL_OPT, + // 数据集模块 + BIZ_DATASET, + // k8s模块 + BIZ_K8S, + //note book + NOTE_BOOK, + //NFS UTILS + NFS_UTIL, + //localFileUtil + LOCAL_FILE_UTIL, + //FILE UTILS + FILE_UTIL, + //FILE UTILS + UPLOAD_TEMP, + //STATE MACHINE + STATE_MACHINE, + //全局垃圾回收 + GARBAGE_RECYCLE, + //DATA_SEQUENCE + DATA_SEQUENCE, + //IO UTIL + IO_UTIL, + // 日志切面 + LOG_ASPECT, + // 远程调用 + REMOTE_CALL, + // 网关 + GATEWAY, + // Redis + REDIS, + //镜像 + IMAGE, + //度量 + MEASURE, + //云端Serving + SERVING; + + /** + * 判断日志类型不能为空 + * + * @param logType 日志类型 + * @return boolean 返回类型 + */ + public static boolean isLogType(LogEnum logType) { + + if (logType != null) { + return true; + } + return false; + } +} diff --git a/dubhe-server/common-biz/log/src/main/java/org/dubhe/biz/log/filter/BaseLogFilter.java b/dubhe-server/common-biz/log/src/main/java/org/dubhe/biz/log/filter/BaseLogFilter.java new file mode 100644 index 0000000..1ea3c1c --- /dev/null +++ b/dubhe-server/common-biz/log/src/main/java/org/dubhe/biz/log/filter/BaseLogFilter.java @@ -0,0 +1,79 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.log.filter; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.filter.AbstractMatcherFilter; +import ch.qos.logback.core.spi.FilterReply; +import cn.hutool.core.util.StrUtil; +import org.slf4j.Marker; + +/** + * @description 自定义日志过滤器 + * @date 2020-07-21 + */ +public class BaseLogFilter extends AbstractMatcherFilter { + + Level level; + + /** + * 重写decide方法 + * + * @param iLoggingEvent event to decide upon. + * @return FilterReply + */ + @Override + public FilterReply decide(ILoggingEvent iLoggingEvent) { + if (!isStarted()) { + return FilterReply.NEUTRAL; + } + final String msg = iLoggingEvent.getMessage(); + //自定义级别 + if (checkLevel(iLoggingEvent) && msg != null && msg.startsWith(StrUtil.DELIM_START) && msg.endsWith(StrUtil.DELIM_END)) { + final Marker marker = iLoggingEvent.getMarker(); + if (marker != null && this.getName() != null && this.getName().contains(marker.getName())) { + return onMatch; + } + } + + return onMismatch; + } + + /** + * 检测日志级别 + * @param iLoggingEvent 日志事件 + * @return true 过滤当前级别 false 不过滤当前级别 + */ + protected boolean checkLevel(ILoggingEvent iLoggingEvent) { + return this.level != null + && iLoggingEvent.getLevel() != null + && iLoggingEvent.getLevel().toInt() == this.level.toInt(); + } + + public void setLevel(Level level) { + this.level = level; + } + + @Override + public void start() { + if (this.level != null) { + super.start(); + } + } +} \ No newline at end of file diff --git a/dubhe-server/common-biz/log/src/main/java/org/dubhe/biz/log/filter/ConsoleLogFilter.java b/dubhe-server/common-biz/log/src/main/java/org/dubhe/biz/log/filter/ConsoleLogFilter.java new file mode 100644 index 0000000..236dbcb --- /dev/null +++ b/dubhe-server/common-biz/log/src/main/java/org/dubhe/biz/log/filter/ConsoleLogFilter.java @@ -0,0 +1,50 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.log.filter; + +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.spi.FilterReply; +import org.dubhe.biz.log.utils.LogUtil; +import org.slf4j.MarkerFactory; + +/** + * @description 自定义日志过滤器 + * @date 2020-07-21 + */ +public class ConsoleLogFilter extends BaseLogFilter { + + @Override + public FilterReply decide(ILoggingEvent iLoggingEvent) { + if (!isStarted()) { + return FilterReply.NEUTRAL; + } + return checkLevel(iLoggingEvent) ? onMatch : onMismatch; + } + + @Override + protected boolean checkLevel(ILoggingEvent iLoggingEvent) { + + + return this.level != null + && iLoggingEvent.getLevel() != null + && iLoggingEvent.getLevel().toInt() >= this.level.toInt() + && !MarkerFactory.getMarker(LogUtil.K8S_CALLBACK_LEVEL).equals(iLoggingEvent.getMarker()) + && !MarkerFactory.getMarker(LogUtil.SCHEDULE_LEVEL).equals(iLoggingEvent.getMarker()) + && !"log4jdbc.log4j2".equals(iLoggingEvent.getLoggerName()); + } +} \ No newline at end of file diff --git a/dubhe-server/common-biz/log/src/main/java/org/dubhe/biz/log/filter/GlobalRequestLogFilter.java b/dubhe-server/common-biz/log/src/main/java/org/dubhe/biz/log/filter/GlobalRequestLogFilter.java new file mode 100644 index 0000000..8d42747 --- /dev/null +++ b/dubhe-server/common-biz/log/src/main/java/org/dubhe/biz/log/filter/GlobalRequestLogFilter.java @@ -0,0 +1,34 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.log.filter; + +import ch.qos.logback.classic.spi.ILoggingEvent; + +/** + * @description 全局请求 日志过滤器 + * @date 2020-08-13 + */ +public class GlobalRequestLogFilter extends BaseLogFilter { + + + @Override + public boolean checkLevel(ILoggingEvent iLoggingEvent) { + return this.level != null; + } + +} \ No newline at end of file diff --git a/dubhe-server/common-biz/log/src/main/java/org/dubhe/biz/log/handler/ScheduleTaskHandler.java b/dubhe-server/common-biz/log/src/main/java/org/dubhe/biz/log/handler/ScheduleTaskHandler.java new file mode 100644 index 0000000..0f12247 --- /dev/null +++ b/dubhe-server/common-biz/log/src/main/java/org/dubhe/biz/log/handler/ScheduleTaskHandler.java @@ -0,0 +1,45 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.log.handler; + + +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; + +/** + * @description 定时任务处理器, 主要做日志标识 + * @date 2020-08-13 + */ +public class ScheduleTaskHandler { + + + public static void process(Handler handler) { + LogUtil.startScheduleTrace(); + try { + handler.run(); + } catch (Exception e) { + LogUtil.error(LogEnum.BIZ_SYS, "There is something wrong in schedule task handler :{}", e); + } finally { + LogUtil.cleanTrace(); + } + } + + + public interface Handler { + void run(); + } +} diff --git a/dubhe-server/common-biz/log/src/main/java/org/dubhe/biz/log/utils/LogUtil.java b/dubhe-server/common-biz/log/src/main/java/org/dubhe/biz/log/utils/LogUtil.java new file mode 100644 index 0000000..8a4f6f3 --- /dev/null +++ b/dubhe-server/common-biz/log/src/main/java/org/dubhe/biz/log/utils/LogUtil.java @@ -0,0 +1,321 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.log.utils; + +import ch.qos.logback.classic.Level; +import com.alibaba.fastjson.JSON; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.exception.ExceptionUtils; +import org.dubhe.biz.base.utils.StringUtils; +import org.dubhe.biz.log.aspect.LogAspect; +import org.dubhe.biz.base.constant.MagicNumConstant; +import org.dubhe.biz.log.entity.LogInfo; +import org.dubhe.biz.log.enums.LogEnum; +import org.slf4j.MDC; +import org.slf4j.MarkerFactory; +import org.slf4j.helpers.MessageFormatter; + +import java.util.Arrays; +import java.util.UUID; + +/** + * @description 日志工具类 + * @date 2020-06-29 + */ +@Slf4j +public class LogUtil { + + private static final String TRACE_TYPE = "TRACE_TYPE"; + + public static final String SCHEDULE_LEVEL = "SCHEDULE"; + + public static final String K8S_CALLBACK_LEVEL = "K8S_CALLBACK"; + + private static final String GLOBAL_REQUEST_LEVEL = "GLOBAL_REQUEST"; + + private static final String TRACE_LEVEL = "TRACE"; + + private static final String DEBUG_LEVEL = "DEBUG"; + + private static final String INFO_LEVEL = "INFO"; + + private static final String WARN_LEVEL = "WARN"; + + private static final String ERROR_LEVEL = "ERROR"; + + + public static void startScheduleTrace() { + MDC.put(TRACE_TYPE, SCHEDULE_LEVEL); + } + + public static void startK8sCallbackTrace() { + MDC.put(TRACE_TYPE, K8S_CALLBACK_LEVEL); + } + + public static void cleanTrace() { + MDC.clear(); + } + + /** + * info级别的日志 + * + * @param logType 日志类型 + * @param object 打印的日志参数 + * @return void + */ + + public static void info(LogEnum logType, Object... object) { + + logHandle(logType, Level.INFO, object); + } + + /** + * debug级别的日志 + * + * @param logType 日志类型 + * @param object 打印的日志参数 + * @return void + */ + public static void debug(LogEnum logType, Object... object) { + logHandle(logType, Level.DEBUG, object); + } + + /** + * error级别的日志 + * + * @param logType 日志类型 + * @param object 打印的日志参数 + * @return void + */ + public static void error(LogEnum logType, Object... object) { + errorObjectHandle(object); + logHandle(logType, Level.ERROR, object); + } + + /** + * warn级别的日志 + * + * @param logType 日志类型 + * @param object 打印的日志参数 + * @return void + */ + public static void warn(LogEnum logType, Object... object) { + logHandle(logType, Level.WARN, object); + } + + /** + * trace级别的日志 + * + * @param logType 日志类型 + * @param object 打印的日志参数 + * @return void + */ + public static void trace(LogEnum logType, Object... object) { + logHandle(logType, Level.TRACE, object); + } + + /** + * 日志处理 + * + * @param logType 日志类型 + * @param level 日志级别 + * @param object 打印的日志参数 + * @return void + */ + private static void logHandle(LogEnum logType, Level level, Object[] object) { + + LogInfo logInfo = generateLogInfo(logType, level, object); + + switch (logInfo.getLevel()) { + case TRACE_LEVEL: + log.trace(MarkerFactory.getMarker(TRACE_LEVEL), logJsonStringLengthLimit(logInfo)); + break; + case DEBUG_LEVEL: + log.debug(MarkerFactory.getMarker(DEBUG_LEVEL), logJsonStringLengthLimit(logInfo)); + break; + case GLOBAL_REQUEST_LEVEL: + logInfo.setLevel(null); + logInfo.setType(null); + logInfo.setLocation(null); + log.info(MarkerFactory.getMarker(GLOBAL_REQUEST_LEVEL), logJsonStringLengthLimit(logInfo)); + break; + case SCHEDULE_LEVEL: + log.info(MarkerFactory.getMarker(SCHEDULE_LEVEL), logJsonStringLengthLimit(logInfo)); + break; + case K8S_CALLBACK_LEVEL: + log.info(MarkerFactory.getMarker(K8S_CALLBACK_LEVEL), logJsonStringLengthLimit(logInfo)); + break; + case INFO_LEVEL: + log.info(MarkerFactory.getMarker(INFO_LEVEL), logJsonStringLengthLimit(logInfo)); + break; + case WARN_LEVEL: + log.warn(MarkerFactory.getMarker(WARN_LEVEL), logJsonStringLengthLimit(logInfo)); + break; + case ERROR_LEVEL: + log.error(MarkerFactory.getMarker(ERROR_LEVEL), logJsonStringLengthLimit(logInfo)); + break; + default: + } + + } + + + /** + * 日志信息组装的内部方法 + * + * @param logType 日志类型 + * @param level 日志级别 + * @param object 打印的日志参数 + * @return LogInfo + */ + private static LogInfo generateLogInfo(LogEnum logType, Level level, Object[] object) { + + + LogInfo logInfo = new LogInfo(); + // 日志类型检测 + if (!LogEnum.isLogType(logType)) { + level = Level.ERROR; + object = new Object[MagicNumConstant.ONE]; + object[MagicNumConstant.ZERO] = "日志类型【".concat(String.valueOf(logType)).concat("】不正确!"); + logType = LogEnum.SYS_ERR; + } + + // 获取trace_id + if (StringUtils.isEmpty(MDC.get(LogAspect.TRACE_ID))) { + MDC.put(LogAspect.TRACE_ID, UUID.randomUUID().toString()); + } + // 设置logInfo的level,type,traceId属性 + logInfo.setLevel(level.levelStr) + .setType(logType.toString()) + .setTraceId(MDC.get(LogAspect.TRACE_ID)); + + + //自定义日志级别 + //LogEnum、 MDC中的 TRACE_TYPE 做日志分流标识 + if (Level.INFO.toInt() == level.toInt()) { + if (LogEnum.GLOBAL_REQ.equals(logType)) { + //info全局请求 + logInfo.setLevel(GLOBAL_REQUEST_LEVEL); + } else if (LogEnum.BIZ_K8S.equals(logType)) { + logInfo.setLevel(K8S_CALLBACK_LEVEL); + } else { + //schedule定时等 链路记录 + String traceType = MDC.get(TRACE_TYPE); + if (StringUtils.isNotBlank(traceType)) { + logInfo.setLevel(traceType); + } + } + } + + // 设置logInfo的堆栈信息 + setLogStackInfo(logInfo); + // 设置logInfo的info信息 + setLogInfo(logInfo, object); + // 截取logInfo的长度并转换成json字符串 + return logInfo; + } + + /** + * 设置loginfo的堆栈信息 + * + * @param logInfo 日志对象 + * @return void + */ + private static void setLogStackInfo(LogInfo logInfo) { + StackTraceElement[] elements = Thread.currentThread().getStackTrace(); + if (elements.length >= MagicNumConstant.SIX) { + StackTraceElement element = elements[MagicNumConstant.FIVE]; + logInfo.setLocation(String.format("%s#%s:%s", element.getClassName(), element.getMethodName(), element.getLineNumber())); + } + } + + /** + * 限制log日志的长度并转换成json + * + * @param logInfo 日志对象 + * @return String + */ + private static String logJsonStringLengthLimit(LogInfo logInfo) { + try { + + String jsonString = JSON.toJSONString(logInfo); + if (StringUtils.isBlank(jsonString)) { + return ""; + } + if (jsonString.length() > MagicNumConstant.TEN_THOUSAND) { + String trunk = logInfo.getInfo().toString().substring(MagicNumConstant.ZERO, MagicNumConstant.NINE_THOUSAND); + logInfo.setInfo(trunk); + jsonString = JSON.toJSONString(logInfo); + } + return jsonString; + + } catch (Exception e) { + logInfo.setLevel(Level.ERROR.levelStr).setType(LogEnum.SYS_ERR.toString()) + .setInfo("cannot serialize exception: " + ExceptionUtils.getStackTrace(e)); + return JSON.toJSONString(logInfo); + } + } + + /** + * 设置日志对象的info信息 + * + * @param logInfo 日志对象 + * @param object 打印的日志参数 + * @return void + */ + private static void setLogInfo(LogInfo logInfo, Object[] object) { + + if (object.length > MagicNumConstant.ONE) { + logInfo.setInfo(MessageFormatter.arrayFormat(object[MagicNumConstant.ZERO].toString(), + Arrays.copyOfRange(object, MagicNumConstant.ONE, object.length)).getMessage()); + + } else if (object.length == MagicNumConstant.ONE && object[MagicNumConstant.ZERO] instanceof Exception) { + logInfo.setInfo((ExceptionUtils.getStackTrace((Exception) object[MagicNumConstant.ZERO]))); + log.error((ExceptionUtils.getStackTrace((Exception) object[MagicNumConstant.ZERO]))); + } else if (object.length == MagicNumConstant.ONE) { + logInfo.setInfo(object[MagicNumConstant.ZERO] == null ? "" : object[MagicNumConstant.ZERO]); + } else { + logInfo.setInfo(""); + } + + } + + /** + * 处理Exception的情况 + * + * @param object 打印的日志参数 + * @return void + */ + private static void errorObjectHandle(Object[] object) { + + if (object.length == MagicNumConstant.TWO && object[MagicNumConstant.ONE] instanceof Exception) { + log.error(String.valueOf(object[MagicNumConstant.ZERO]), (Exception) object[MagicNumConstant.ONE]); + object[MagicNumConstant.ONE] = ExceptionUtils.getStackTrace((Exception) object[MagicNumConstant.ONE]); + + } else if (object.length >= MagicNumConstant.THREE) { + log.error(String.valueOf(object[MagicNumConstant.ZERO]), + Arrays.copyOfRange(object, MagicNumConstant.ONE, object.length)); + for (int i = 0; i < object.length; i++) { + if (object[i] instanceof Exception) { + object[i] = ExceptionUtils.getStackTrace((Exception) object[i]); + } + + } + } + } +} diff --git a/dubhe-server/common-biz/log/src/main/resources/logback.xml b/dubhe-server/common-biz/log/src/main/resources/logback.xml new file mode 100644 index 0000000..efb061f --- /dev/null +++ b/dubhe-server/common-biz/log/src/main/resources/logback.xml @@ -0,0 +1,262 @@ + + + + + + + + + + + + ${log.pattern} + ${log.charset} + + + INFO + INFO + ACCEPT + DENY + + + + + + + logs/${log.path}/info/dubhe-info.log + + logs/${log.path}/info/dubhe-${app.active}-info-%d{yyyy-MM-dd}.%i.log + + + 50MB + 7 + 250MB + + + %m%n + ${log.charset} + + + true + + INFO + INFO,K8S_CALLBACK + ACCEPT + DENY + + + + + + logs/${log.path}/debug/dubhe-debug.log + + logs/${log.path}/debug/dubhe-${app.active}-debug-%d{yyyy-MM-dd}.%i.log + + + 50MB + 7 + 250MB + + + %m%n + ${log.charset} + + + true + + DEBUG + DEBUG + ACCEPT + DENY + + + + + + logs/${log.path}/error/dubhe-error.log + + logs/${log.path}/error/dubhe-${app.active}-error-%d{yyyy-MM-dd}.%i.log + + + 50MB + 7 + 250MB + + + %m%n + ${log.charset} + + + true + + ERROR + ERROR + ACCEPT + DENY + + + + + + logs/${log.path}/warn/dubhe-warn.log + + logs/${log.path}/warn/dubhe-${app.active}-warn-%d{yyyy-MM-dd}.%i.log + + + 50MB + 7 + 250MB + + + %m%n + ${log.charset} + + + true + + + WARN + WARN + ACCEPT + DENY + + + + + + logs/${log.path}/trace/dubhe-trace.log + + logs/${log.path}/trace/dubhe-${app.active}-trace-%d{yyyy-MM-dd}.%i.log + + + 50MB + 7 + 250MB + + + %m%n + ${log.charset} + + + true + + TRACE + TRACE + ACCEPT + DENY + + + + + + + logs/${log.path}/info/dubhe-schedule.log + + logs/${log.path}/info/dubhe-${app.active}-schedule-%d{yyyy-MM-dd}.%i.log + + + 50MB + 7 + 250MB + + + %m%n + ${log.charset} + + + true + + INFO + SCHEDULE + ACCEPT + DENY + + + + + + logs/${log.path}/info/dubhe-request.log + + logs/${log.path}/info/dubhe-${app.active}-request-%d{yyyy-MM-dd}.%i.log + + + 50MB + 7 + 250MB + + + %m%n + ${log.charset} + + + true + + INFO + + GLOBAL_REQUEST + ACCEPT + DENY + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/dubhe-server/common-biz/pom.xml b/dubhe-server/common-biz/pom.xml new file mode 100644 index 0000000..d8a2c9b --- /dev/null +++ b/dubhe-server/common-biz/pom.xml @@ -0,0 +1,38 @@ + + + 4.0.0 + pom + + org.dubhe + server + 0.0.1-SNAPSHOT + + org.dubhe.biz + common-biz + 0.0.1-SNAPSHOT + 通用Business模块(Biz) + Dubhe Common for Business + + + base + data-response + file + db + log + data-permission + redis + state-machine + + + + + + + + + + + + + diff --git a/dubhe-server/common-biz/redis/pom.xml b/dubhe-server/common-biz/redis/pom.xml new file mode 100644 index 0000000..60960da --- /dev/null +++ b/dubhe-server/common-biz/redis/pom.xml @@ -0,0 +1,34 @@ + + + + common-biz + org.dubhe.biz + 0.0.1-SNAPSHOT + + 4.0.0 + + redis + 0.0.1-SNAPSHOT + Biz redis 工具 + Redis for Dubhe Server + + + + + org.dubhe.biz + log + ${org.dubhe.biz.log.version} + + + com.liferay + com.fasterxml.jackson.databind + + + + + + + + + \ No newline at end of file diff --git a/dubhe-server/common-biz/redis/src/main/java/org/dubhe/biz/redis/config/RedisConfig.java b/dubhe-server/common-biz/redis/src/main/java/org/dubhe/biz/redis/config/RedisConfig.java new file mode 100644 index 0000000..781b4f7 --- /dev/null +++ b/dubhe-server/common-biz/redis/src/main/java/org/dubhe/biz/redis/config/RedisConfig.java @@ -0,0 +1,215 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.redis.config; + +import cn.hutool.core.lang.Assert; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.serializer.SerializerFeature; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.codec.digest.DigestUtils; +import org.dubhe.biz.base.utils.StringUtils; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.data.redis.RedisProperties; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.cache.Cache; +import org.springframework.cache.annotation.CachingConfigurerSupport; +import org.springframework.cache.annotation.EnableCaching; +import org.springframework.cache.interceptor.CacheErrorHandler; +import org.springframework.cache.interceptor.KeyGenerator; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.redis.cache.RedisCacheConfiguration; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.core.RedisOperations; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.serializer.RedisSerializationContext; +import org.springframework.data.redis.serializer.RedisSerializer; + +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.HashMap; +import java.util.Map; + +/** + * @description redis配置类 + * @date 2020-03-25 + */ +@Slf4j +@Configuration +@EnableCaching +@ConditionalOnClass(RedisOperations.class) +@EnableConfigurationProperties(RedisProperties.class) +public class RedisConfig extends CachingConfigurerSupport { + + /** + * 设置 redis 数据默认过期时间,默认2小时 + * 设置@cacheable 序列化方式 + */ + @Bean + public RedisCacheConfiguration redisCacheConfiguration() { + FastJsonRedisSerializer fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class); + RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig(); + configuration = configuration.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(fastJsonRedisSerializer)).entryTtl(Duration.ofHours(2)); + return configuration; + } + + @SuppressWarnings("all") + @Bean(name = "redisTemplate") + @ConditionalOnMissingBean(name = "redisTemplate") + public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) { + RedisTemplate template = new RedisTemplate<>(); + //序列化 + FastJsonRedisSerializer fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class); + // value值的序列化采用fastJsonRedisSerializer + template.setValueSerializer(fastJsonRedisSerializer); + template.setHashValueSerializer(fastJsonRedisSerializer); + // 全局开启AutoType,这里方便开发,使用全局的方式 + ParserConfig.getGlobalInstance().setAutoTypeSupport(true); + // 建议使用这种方式,小范围指定白名单 + // ParserConfig.getGlobalInstance().addAccept("org.dubhe.domain"); + // key的序列化采用StringRedisSerializer + template.setKeySerializer(new StringRedisSerializer()); + template.setHashKeySerializer(new StringRedisSerializer()); + template.setConnectionFactory(redisConnectionFactory); + return template; + } + + /** + * 自定义缓存key生成策略,默认将使用该策略 + */ + @Bean + @Override + public KeyGenerator keyGenerator() { + return (target, method, params) -> { + Map container = new HashMap<>(3); + Class targetClassClass = target.getClass(); + // 类地址 + container.put("class", targetClassClass.toGenericString()); + // 方法名称 + container.put("methodName", method.getName()); + // 包名称 + container.put("package", targetClassClass.getPackage()); + // 参数列表 + for (int i = 0; i < params.length; i++) { + container.put(String.valueOf(i), params[i]); + } + // 转为JSON字符串 + String jsonString = JSON.toJSONString(container); + // 做SHA256 Hash计算,得到一个SHA256摘要作为Key + return DigestUtils.sha256Hex(jsonString); + }; + } + + @Bean + @Override + public CacheErrorHandler errorHandler() { + // 异常处理,当Redis发生异常时,打印日志,但是程序正常走 + log.info("初始化 -> [{}]", "Redis CacheErrorHandler"); + return new CacheErrorHandler() { + @Override + public void handleCacheGetError(RuntimeException e, Cache cache, Object key) { + log.error("Redis occur handleCacheGetError:key -> [{}]", key, e); + } + + @Override + public void handleCachePutError(RuntimeException e, Cache cache, Object key, Object value) { + log.error("Redis occur handleCachePutError:key -> [{}];value -> [{}]", key, value, e); + } + + @Override + public void handleCacheEvictError(RuntimeException e, Cache cache, Object key) { + log.error("Redis occur handleCacheEvictError:key -> [{}]", key, e); + } + + @Override + public void handleCacheClearError(RuntimeException e, Cache cache) { + log.error("Redis occur handleCacheClearError:", e); + } + }; + } + +} + +/** + * Value 序列化 + * + * @param + */ +class FastJsonRedisSerializer implements RedisSerializer { + + private Class clazz; + + FastJsonRedisSerializer(Class clazz) { + super(); + this.clazz = clazz; + } + + @Override + public byte[] serialize(T t) { + if (t == null) { + return new byte[0]; + } + return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(StandardCharsets.UTF_8); + } + + @Override + public T deserialize(byte[] bytes) { + if (bytes == null || bytes.length <= 0) { + return null; + } + String str = new String(bytes, StandardCharsets.UTF_8); + return JSON.parseObject(str, clazz); + } + +} + +/** + * 重写序列化器 + * + */ +class StringRedisSerializer implements RedisSerializer { + + private final Charset charset; + + StringRedisSerializer() { + this(StandardCharsets.UTF_8); + } + + private StringRedisSerializer(Charset charset) { + Assert.notNull(charset, "Charset must not be null!"); + this.charset = charset; + } + + @Override + public String deserialize(byte[] bytes) { + return (bytes == null ? null : new String(bytes, charset)); + } + + @Override + public byte[] serialize(Object object) { + String string = JSON.toJSONString(object); + if (StringUtils.isBlank(string)) { + return null; + } + string = string.replace("\"", ""); + return string.getBytes(charset); + } +} diff --git a/dubhe-server/common-biz/redis/src/main/java/org/dubhe/biz/redis/utils/RedisUtils.java b/dubhe-server/common-biz/redis/src/main/java/org/dubhe/biz/redis/utils/RedisUtils.java new file mode 100644 index 0000000..16e8d09 --- /dev/null +++ b/dubhe-server/common-biz/redis/src/main/java/org/dubhe/biz/redis/utils/RedisUtils.java @@ -0,0 +1,865 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.redis.utils; + +import org.dubhe.biz.base.constant.MagicNumConstant; +import org.dubhe.biz.base.utils.StringUtils; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.data.redis.connection.RedisConnection; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.core.Cursor; +import org.springframework.data.redis.core.RedisConnectionUtils; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.core.ScanOptions; +import org.springframework.data.redis.core.script.DefaultRedisScript; +import org.springframework.data.redis.core.script.RedisScript; +import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; +import org.springframework.stereotype.Component; +import org.springframework.util.CollectionUtils; + +import java.util.*; +import java.util.concurrent.TimeUnit; + +/** + * @description redis工具类 + * @date 2020-03-13 + */ +@Component +@SuppressWarnings({"unchecked", "all"}) +public class RedisUtils { + + private RedisTemplate redisTemplate; + @Value("${jwt.online-key}") + private String onlineKey; + + public RedisUtils(RedisTemplate redisTemplate) { + this.redisTemplate = redisTemplate; + } + + // =============================common============================ + + /** + * 指定缓存失效时间 + * + * @param key 键 + * @param time 时间(秒) + */ + public boolean expire(String key, long time) { + try { + if (time > 0) { + redisTemplate.expire(key, time, TimeUnit.SECONDS); + } + } catch (Exception e) { + LogUtil.error(LogEnum.REDIS, "RedisUtils expire key {} time {} error:{}", key, time, e); + return false; + } + return true; + } + + /** + * 根据 key 获取过期时间 + * + * @param key 键 不能为null + * @return 时间(秒) 返回0代表为永久有效 + */ + public long getExpire(Object key) { + return redisTemplate.getExpire(key, TimeUnit.SECONDS); + } + + /** + * 查找匹配key + * + * @param pattern key + * @return List 匹配的key集合 + */ + public List scan(String pattern) { + ScanOptions options = ScanOptions.scanOptions().match(pattern).build(); + RedisConnectionFactory factory = redisTemplate.getConnectionFactory(); + RedisConnection rc = Objects.requireNonNull(factory).getConnection(); + Cursor cursor = rc.scan(options); + List result = new ArrayList<>(); + while (cursor.hasNext()) { + result.add(new String(cursor.next())); + } + try { + RedisConnectionUtils.releaseConnection(rc, factory, true); + } catch (Exception e) { + LogUtil.error(LogEnum.REDIS, "RedisUtils scan pattern {} error:{}", pattern, e); + } + return result; + } + + /** + * 分页查询 key + * + * @param patternKey key + * @param page 页码 + * @param size 每页数目 + * @return 匹配到的key集合 + */ + public List findKeysForPage(String patternKey, int page, int size) { + ScanOptions options = ScanOptions.scanOptions().match(patternKey).build(); + RedisConnectionFactory factory = redisTemplate.getConnectionFactory(); + RedisConnection rc = Objects.requireNonNull(factory).getConnection(); + Cursor cursor = rc.scan(options); + List result = new ArrayList<>(size); + int tmpIndex = 0; + int fromIndex = page * size; + int toIndex = page * size + size; + while (cursor.hasNext()) { + if (tmpIndex >= fromIndex && tmpIndex < toIndex) { + result.add(new String(cursor.next())); + tmpIndex++; + continue; + } + // 获取到满足条件的数据后,就可以退出了 + if (tmpIndex >= toIndex) { + break; + } + tmpIndex++; + cursor.next(); + } + try { + RedisConnectionUtils.releaseConnection(rc, factory, true); + } catch (Exception e) { + LogUtil.error(LogEnum.REDIS, "RedisUtils findKeysForPage patternKey {} page {} size {} error:{}", patternKey, page, size, e); + } + return result; + } + + /** + * 判断key是否存在 + * + * @param key 键 + * @return true 存在 false不存在 + */ + public boolean hasKey(String key) { + try { + return redisTemplate.hasKey(key); + } catch (Exception e) { + LogUtil.error(LogEnum.REDIS, "RedisUtils hasKey key {} error:{}", key, e); + return false; + } + } + + /** + * 删除缓存 + * + * @param key 可以传一个值 或多个 + */ + public void del(String... key) { + if (key != null && key.length > 0) { + if (key.length == 1) { + redisTemplate.delete(key[0]); + } else { + redisTemplate.delete(CollectionUtils.arrayToList(key)); + } + } + } + + /** + * + * @param script 脚本字符串 + * @param key 键 + * @param args 脚本其他参数 + * @return + */ + public Object executeRedisScript(String script, String key, Object... args) { + try { + RedisScript redisScript = new DefaultRedisScript<>(script, Long.class); + redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<>(Object.class)); + return redisTemplate.execute(redisScript, Collections.singletonList(key), args); + } catch (Exception e) { + LogUtil.error(LogEnum.REDIS, "executeRedisScript script {} key {} args {} error:{}", script, key, args, e); + return MagicNumConstant.ZERO_LONG; + } + } + + /** + * + * @param script 脚本字符串 + * @param key 键 + * @param args 脚本其他参数 + * @return + */ + public Object executeRedisObjectScript(String script, String key, Object... args) { + try { + RedisScript redisScript = new DefaultRedisScript<>(script, Object.class); + redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<>(Object.class)); + return redisTemplate.execute(redisScript, Collections.singletonList(key), args); + } catch (Exception e) { + LogUtil.error(LogEnum.REDIS, "executeRedisObjectScript script {} key {} args {} error:{}", script, key, args, e); + return null; + } + } + + // ============================String============================= + + /** + * 普通缓存获取 + * + * @param key 键 + * @return key对应的value值 + */ + public Object get(String key) { + + return key == null ? null : redisTemplate.opsForValue().get(key); + } + + /** + * 批量获取 + * + * @param keys key集合 + * @return key集合对应的value集合 + */ + public List multiGet(List keys) { + Object obj = redisTemplate.opsForValue().multiGet(Collections.singleton(keys)); + return null; + } + + /** + * 普通缓存放入 + * + * @param key 键 + * @param value 值 + * @return true成功 false失败 + */ + public boolean set(String key, Object value) { + try { + redisTemplate.opsForValue().set(key, value); + return true; + } catch (Exception e) { + LogUtil.error(LogEnum.REDIS, "RedisUtils set key {} value {} error:{}", key, value, e); + return false; + } + } + + /** + * 普通缓存放入并设置时间 + * + * @param key 键 + * @param value 值 + * @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期 + * @return true成功 false 失败 + */ + public boolean set(String key, Object value, long time) { + try { + if (time > 0) { + redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS); + } else { + set(key, value); + } + return true; + } catch (Exception e) { + LogUtil.error(LogEnum.REDIS, "RedisUtils set key {} value {} time {} error:{}", key, value, time, e); + return false; + } + } + + /** + * 普通缓存放入并设置时间 + * + * @param key 键 + * @param value 值 + * @param time 时间 + * @param timeUnit 类型 + * @return true成功 false 失败 + */ + public boolean set(String key, Object value, long time, TimeUnit timeUnit) { + try { + if (time > 0) { + redisTemplate.opsForValue().set(key, value, time, timeUnit); + } else { + set(key, value); + } + return true; + } catch (Exception e) { + LogUtil.error(LogEnum.REDIS, "RedisUtils set key {} value {} time {} timeUnit {} error:{}", key, value, time, timeUnit, e); + return false; + } + } + + //===============================Lock================================= + + /** + * 加锁 + * @param key 键 + * @param requestId 请求id用以释放锁 + * @param expireTime 超时时间(秒) + * @return + */ + public boolean getDistributedLock(String key, String requestId, long expireTime) { + String script = "if redis.call('setNx',KEYS[1],ARGV[1]) == 1 then if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('expire',KEYS[1],ARGV[2]) else return 0 end else return 0 end"; + Object result = executeRedisScript(script, key, requestId, expireTime); + return result != null && result.equals(MagicNumConstant.ONE_LONG); + } + + /** + * 释放锁 + * @param key 键 + * @param requestId 请求id用以释放锁 + * @return + */ + public boolean releaseDistributedLock(String key, String requestId) { + String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end"; + Object result = executeRedisScript(script, key, requestId); + return result != null && result.equals(MagicNumConstant.ONE_LONG); + } + + // ================================Map================================= + + /** + * HashGet + * + * @param key 键 不能为null + * @param item 项 不能为null + * @return 值 + */ + public Object hget(String key, String item) { + return redisTemplate.opsForHash().get(key, item); + } + + /** + * 获取hashKey对应的所有键值 + * + * @param key 键 + * @return 对应的多个键值 + */ + public Map hmget(String key) { + return redisTemplate.opsForHash().entries(key); + + } + + /** + * HashSet + * + * @param key 键 + * @param map 对应多个键值 + * @return true 成功 false 失败 + */ + public boolean hmset(String key, Map map) { + try { + redisTemplate.opsForHash().putAll(key, map); + return true; + } catch (Exception e) { + LogUtil.error(LogEnum.REDIS, "RedisUtils hmset key {} map {} error:{}", key, map, e); + return false; + } + } + + /** + * HashSet 并设置时间 + * + * @param key 键 + * @param map 对应多个键值 + * @param time 时间(秒) + * @return true成功 false失败 + */ + public boolean hmset(String key, Map map, long time) { + try { + redisTemplate.opsForHash().putAll(key, map); + if (time > 0) { + expire(key, time); + } + return true; + } catch (Exception e) { + LogUtil.error(LogEnum.REDIS, "RedisUtils hmset key {} map {} time {} error:{}", key, map, time, e); + return false; + } + } + + /** + * 向一张hash表中放入数据,如果不存在将创建 + * + * @param key 键 + * @param item 项 + * @param value 值 + * @return true 成功 false失败 + */ + public boolean hset(String key, String item, Object value) { + try { + redisTemplate.opsForHash().put(key, item, value); + return true; + } catch (Exception e) { + LogUtil.error(LogEnum.REDIS, "RedisUtils hset key {} item {} value {} error:{}", key, item, value, e); + return false; + } + } + + /** + * 向一张hash表中放入数据,如果不存在将创建 + * + * @param key 键 + * @param item 项 + * @param value 值 + * @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间 + * @return true 成功 false失败 + */ + public boolean hset(String key, String item, Object value, long time) { + try { + redisTemplate.opsForHash().put(key, item, value); + if (time > 0) { + expire(key, time); + } + return true; + } catch (Exception e) { + LogUtil.error(LogEnum.REDIS, "RedisUtils hset key {} item {} value {} time {} error:{}", key, item, value, time, e); + return false; + } + } + + /** + * 删除hash表中的值 + * + * @param key 键 不能为null + * @param item 项 可以使多个 不能为null + */ + public void hdel(String key, Object... item) { + redisTemplate.opsForHash().delete(key, item); + } + + /** + * 判断hash表中是否有该项的值 + * + * @param key 键 不能为null + * @param item 项 不能为null + * @return true 存在 false不存在 + */ + public boolean hHasKey(String key, String item) { + return redisTemplate.opsForHash().hasKey(key, item); + } + + /** + * hash递增 如果不存在,就会创建一个 并把新增后的值返回 + * + * @param key 键 + * @param item 项 + * @param by 要增加几(大于0) + * @return + */ + public double hincr(String key, String item, double by) { + return redisTemplate.opsForHash().increment(key, item, by); + } + + /** + * hash递减 + * + * @param key 键 + * @param item 项 + * @param by 要减少记(小于0) + * @return + */ + public double hdecr(String key, String item, double by) { + return redisTemplate.opsForHash().increment(key, item, -by); + } + + // ============================set============================= + + /** + * 根据key获取Set中的所有值 + * + * @param key 键 + * @return + */ + public Set sGet(String key) { + try { + return redisTemplate.opsForSet().members(key); + } catch (Exception e) { + LogUtil.error(LogEnum.REDIS, "RedisUtils sGet key {} error:{}", key, e); + return null; + } + } + + /** + * 根据value从一个set中查询,是否存在 + * + * @param key 键 + * @param value 值 + * @return true 存在 false不存在 + */ + public boolean sHasKey(String key, Object value) { + try { + return redisTemplate.opsForSet().isMember(key, value); + } catch (Exception e) { + LogUtil.error(LogEnum.REDIS, "RedisUtils sHasKey key {} value {} error:{}", key, value, e); + return false; + } + } + + /** + * 将数据放入set缓存 + * + * @param key 键 + * @param values 值 可以是多个 + * @return 成功个数 + */ + public long sSet(String key, Object... values) { + try { + return redisTemplate.opsForSet().add(key, values); + } catch (Exception e) { + LogUtil.error(LogEnum.REDIS, "RedisUtils sSet key {} values {} error:{}", key, values, e); + return 0; + } + } + + /** + * 将set数据放入缓存 + * + * @param key 键 + * @param time 时间(秒) + * @param values 值 可以是多个 + * @return 成功个数 + */ + public long sSetAndTime(String key, long time, Object... values) { + try { + Long count = redisTemplate.opsForSet().add(key, values); + if (time > 0) { + expire(key, time); + } + return count; + } catch (Exception e) { + LogUtil.error(LogEnum.REDIS, "RedisUtils sSetAndTime key {} time {} values {} error:{}", key, time, values, e); + return 0; + } + } + + /** + * 获取set缓存的长度 + * + * @param key 键 + * @return + */ + public long sGetSetSize(String key) { + try { + return redisTemplate.opsForSet().size(key); + } catch (Exception e) { + LogUtil.error(LogEnum.REDIS, "RedisUtils sGetSetSize key {} error:{}", key, e); + return 0; + } + } + + /** + * 移除值为value的 + * + * @param key 键 + * @param values 值 可以是多个 + * @return 移除的个数 + */ + public long setRemove(String key, Object... values) { + try { + Long count = redisTemplate.opsForSet().remove(key, values); + return count; + } catch (Exception e) { + LogUtil.error(LogEnum.REDIS, "RedisUtils setRemove key {} values {} error:{}", key, values, e); + return 0; + } + } + + // ===============================sorted set================================= + + /** + * 将zSet数据放入缓存 + * + * @param key + * @param time + * @param values + * @return Boolean + */ + public Boolean zSet(String key, long time, Object value) { + try { + Boolean success = redisTemplate.opsForZSet().add(key, value, System.currentTimeMillis()); + if (success) { + expire(key, time); + } + return success; + } catch (Exception e) { + LogUtil.error(LogEnum.REDIS, "RedisUtils zSet key {} time {} value {} error:{}", key, time, value, e); + return false; + } + } + + /** + * 将zSet数据放入缓存 + * @param key 健 + * @param score 分数 + * @param value 值 + * @return + */ + public Boolean zAdd(String key,Long score,Object value){ + try{ + if (StringUtils.isEmpty(key) || score == null || value == null){ + return false; + } + return redisTemplate.opsForZSet().add(key, value, score); + }catch (Exception e){ + LogUtil.error(LogEnum.REDIS, "RedisUtils zAdd key {} score {} value {} error:{}", key, score, value, e); + return false; + } + } + + /** + * 返回有序集合所有成员,从大到小排序 + * + * @param key + * @return Set + */ + public Set zGet(String key) { + try { + return redisTemplate.opsForZSet().reverseRange(key, Long.MIN_VALUE, Long.MAX_VALUE); + } catch (Exception e) { + LogUtil.error(LogEnum.REDIS, "RedisUtils zGet key {} error:{}", key, e); + return null; + } + } + + /** + * 弹出有序集合 score 在 [min,max] 内由小到大从 offset 取 count 个 + * @param key 健 + * @param min score最小值 + * @param max score最大值 + * @param offset 起始下标 + * @param count 偏移量 + * @return + */ + public List zRangeByScorePop(String key,double min,double max,long offset,long count){ + try{ + String script = "local elementSet = redis.call('ZRANGEBYSCORE',KEYS[1],ARGV[1],ARGV[2],'LIMIT',ARGV[3],ARGV[4]) if elementSet ~= false and #elementSet ~= 0 then redis.call('ZREM' , KEYS[1] , elementSet[1]) end return elementSet"; + Object result = executeRedisObjectScript(script, key, min, max,offset,count); + return (List) result; + }catch (Exception e){ + LogUtil.error(LogEnum.REDIS, "RedisUtils zRangeByScorePop key {} min {} max {} offset {} count {} error:{}", key,min, max, offset, count, e); + return new ArrayList<>(); + } + } + + /** + * 弹出有序集合 score 在 [min,max] 内由小到大从 0 取 1 个 + * @param key 健 + * @param min score最小值 + * @param max score最大值 + * @return + */ + public List zRangeByScorePop(String key,double min, double max){ + return zRangeByScorePop( key,min, max,0,1); + } + + /** + * 弹出有序集合 score 在 [0,max] 内由小到大从 offset 取 count 个 + * @param key 健 + * @param max score最大值 + * @return + */ + public List zRangeByScorePop(String key,double max){ + return zRangeByScorePop( key,0, max,0,1); + } + + + // ===============================list================================= + + /** + * 获取list缓存的内容 + * + * @param key 键 + * @param start 开始 + * @param end 结束 0 到 -1代表所有值 + * @return + */ + public List lGet(String key, long start, long end) { + try { + return redisTemplate.opsForList().range(key, start, end); + } catch (Exception e) { + LogUtil.error(LogEnum.REDIS, "RedisUtils lGetIndex key {} start {} end {} error:{}", key, start, end, e); + return null; + } + } + + /** + * 获取list缓存的长度 + * + * @param key 键 + * @return + */ + public long lGetListSize(String key) { + try { + return redisTemplate.opsForList().size(key); + } catch (Exception e) { + LogUtil.error(LogEnum.REDIS, "RedisUtils lGetListSize key {} error:{}", key, e); + return 0; + } + } + + /** + * 通过索引 获取list中的值 + * + * @param key 键 + * @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推 + * @return + */ + public Object lGetIndex(String key, long index) { + try { + return redisTemplate.opsForList().index(key, index); + } catch (Exception e) { + LogUtil.error(LogEnum.REDIS, "RedisUtils lGetIndex key {} index {} error:{}", key, index, e); + return null; + } + } + + /** + * 将list放入缓存 + * + * @param key 键 + * @param value 值 + * @return + */ + public boolean lSet(String key, Object value) { + try { + redisTemplate.opsForList().rightPush(key, value); + return true; + } catch (Exception e) { + LogUtil.error(LogEnum.REDIS, "RedisUtils lSet key {} value {} error:{}", key, value, e); + return false; + } + } + + /** + * 将list放入缓存 + * + * @param key 键 + * @param value 值 + * @param time 时间(秒) + * @return 是否存储成功 + */ + public boolean lSet(String key, Object value, long time) { + try { + redisTemplate.opsForList().rightPush(key, value); + if (time > 0) { + expire(key, time); + } + return true; + } catch (Exception e) { + LogUtil.error(LogEnum.REDIS, "RedisUtils lSet key {} value {} time {} error:{}", key, value, time, e); + return false; + } + } + + /** + * 将list放入缓存 + * + * @param key 键 + * @param value 值 + * @return 是否存储成功 + */ + public boolean lSet(String key, List value) { + try { + redisTemplate.opsForList().rightPushAll(key, value); + return true; + } catch (Exception e) { + LogUtil.error(LogEnum.REDIS, "RedisUtils lSet key {} value {} error:{}", key, value, e); + return false; + } + } + + /** + * 将list放入缓存 + * + * @param key 键 + * @param value 值 + * @param time 时间(秒) + * @return 是否存储成功 + */ + public boolean lSet(String key, List value, long time) { + try { + redisTemplate.opsForList().rightPushAll(key, value); + if (time > 0) { + expire(key, time); + } + return true; + } catch (Exception e) { + LogUtil.error(LogEnum.REDIS, "RedisUtils lSet key {} value {} time {} error:{}", key, value, time, e); + return false; + } + } + + /** + * 根据索引修改list中的某条数据 + * + * @param key 键 + * @param index 索引 + * @param value 值 + * @return 更新数据标识 + */ + public boolean lUpdateIndex(String key, long index, Object value) { + try { + redisTemplate.opsForList().set(key, index, value); + return true; + } catch (Exception e) { + LogUtil.error(LogEnum.REDIS, "RedisUtils lUpdateIndex key {} index {} value {} error:{}", key, index, value, e); + return false; + } + } + + /** + * 移除N个值为value + * + * @param key 键 + * @param count 移除多少个 + * @param value 值 + * @return 移除的个数 + */ + public long lRemove(String key, long count, Object value) { + try { + return redisTemplate.opsForList().remove(key, count, value); + } catch (Exception e) { + LogUtil.error(LogEnum.REDIS, "RedisUtils lRemove key {} count {} value {} error:{}", key, count, value, e); + return 0; + } + } + + /** + * 队列从左弹出数据 + * + * @param key + * @return key对应的value值 + */ + public Object lpop(String key) { + try { + return redisTemplate.opsForList().leftPop(key); + } catch (Exception e) { + LogUtil.error(LogEnum.REDIS, "RedisUtils lRemove key {} error:{}", key, e); + return null; + } + } + + /** + * 队列从右压入数据 + * + * @param key + * @param value + * @return long + */ + public long rpush(String key, Object value) { + try { + return redisTemplate.opsForList().rightPush(key, value); + } catch (Exception e) { + LogUtil.error(LogEnum.SYS_ERR, "RedisUtils rpush key {} error:{}", key, e.getMessage()); + return 0L; + } + } +} diff --git a/dubhe-server/common-biz/state-machine/pom.xml b/dubhe-server/common-biz/state-machine/pom.xml new file mode 100644 index 0000000..5e3f2ff --- /dev/null +++ b/dubhe-server/common-biz/state-machine/pom.xml @@ -0,0 +1,48 @@ + + + 4.0.0 + + org.dubhe.biz + common-biz + 0.0.1-SNAPSHOT + + state-machine + 0.0.1-SNAPSHOT + 状态机 + state machine for Dubhe Server + + + + + + org.apache.poi + poi + + + org.apache.poi + poi-ooxml + + + + org.dubhe.biz + base + ${org.dubhe.biz.base.version} + + + org.dubhe.biz + log + ${org.dubhe.biz.log.version} + compile + + + + + + + + + + + \ No newline at end of file diff --git a/dubhe-server/common-biz/state-machine/src/main/java/org/dubhe/biz/statemachine/dto/StateChangeDTO.java b/dubhe-server/common-biz/state-machine/src/main/java/org/dubhe/biz/statemachine/dto/StateChangeDTO.java new file mode 100644 index 0000000..b6cbe93 --- /dev/null +++ b/dubhe-server/common-biz/state-machine/src/main/java/org/dubhe/biz/statemachine/dto/StateChangeDTO.java @@ -0,0 +1,49 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.statemachine.dto; + +import lombok.*; +import org.springframework.stereotype.Component; + +/** + * @description 执行状态机切换请求体 + * @date 2020-08-27 + */ +@Component +@Data +@Builder +@ToString +@NoArgsConstructor +@AllArgsConstructor +public class StateChangeDTO { + + /** + * 业务参数 eg: id + */ + private Object[] objectParam; + + /** + * 状态机类型 eg:dataStateMachine + */ + private String stateMachineType; + + /** + * 状态机执行事件 + */ + private String eventMethodName; + +} \ No newline at end of file diff --git a/dubhe-server/common-biz/state-machine/src/main/java/org/dubhe/biz/statemachine/exception/StateMachineException.java b/dubhe-server/common-biz/state-machine/src/main/java/org/dubhe/biz/statemachine/exception/StateMachineException.java new file mode 100644 index 0000000..aa3c0fa --- /dev/null +++ b/dubhe-server/common-biz/state-machine/src/main/java/org/dubhe/biz/statemachine/exception/StateMachineException.java @@ -0,0 +1,49 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.statemachine.exception; + +import lombok.Getter; +import org.dubhe.biz.base.exception.BusinessException; + +/** + * @description 状态机异常类 + * @date 2020-08-27 + */ +@Getter +public class StateMachineException extends BusinessException { + + private static final long serialVersionUID = 1L; + + /** + * 自定义状态机异常(抛出异常堆栈信息) + * + * @param cause + */ + public StateMachineException(Throwable cause){ + super(cause); + } + + /** + * 自定义状态机异常(抛出异常信息) + * + * @param msg + */ + public StateMachineException(String msg){ + super(msg); + } + +} \ No newline at end of file diff --git a/dubhe-server/common-biz/state-machine/src/main/java/org/dubhe/biz/statemachine/utils/StateMachineProxyUtil.java b/dubhe-server/common-biz/state-machine/src/main/java/org/dubhe/biz/statemachine/utils/StateMachineProxyUtil.java new file mode 100644 index 0000000..600b92d --- /dev/null +++ b/dubhe-server/common-biz/state-machine/src/main/java/org/dubhe/biz/statemachine/utils/StateMachineProxyUtil.java @@ -0,0 +1,124 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.biz.statemachine.utils; + +import org.apache.commons.lang3.StringUtils; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.dubhe.biz.statemachine.dto.StateChangeDTO; +import org.dubhe.biz.base.utils.SpringContextHolder; +import org.dubhe.biz.statemachine.exception.StateMachineException; +import org.springframework.stereotype.Component; +import org.springframework.util.CollectionUtils; +import org.springframework.util.ReflectionUtils; +import org.apache.poi.ss.formula.functions.T; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** + * @description 代理执行状态机 + * @date 2020-08-27 + */ +@Component +public class StateMachineProxyUtil { + + /** + * 代理执行单个状态机的状态切换 + * + * @param stateChangeDTO 数据集状态切换信息 + * @param objectService 服务类 + */ + public static void proxyExecutionSingleState(StateChangeDTO stateChangeDTO, Object objectService) { + checkSingleParam(stateChangeDTO); + //获取全局状态机中的指定状态机 + Field field = ReflectionUtils.findField(objectService.getClass(), stateChangeDTO.getStateMachineType()); + if (field == null) { + throw new StateMachineException("The specified state machine was not found in the global state machine"); + } + //获取需要执行的状态机对象 + Object stateMachineObject = SpringContextHolder.getBean(field.getName()); + try { + //获取目标执行方法的参数类型 + List> paramTypesList = getMethodParamTypes(stateMachineObject, stateChangeDTO.getEventMethodName()); + //构造目标执行方法 + Method method = ReflectionUtils.findMethod(stateMachineObject.getClass(), stateChangeDTO.getEventMethodName(), paramTypesList.toArray(new Class[paramTypesList.size()])); + if (stateChangeDTO.getObjectParam().length != paramTypesList.size()) { + LogUtil.error(LogEnum.STATE_MACHINE, "Target execution method parameters {} Inconsistent with the number of incoming {} ", paramTypesList.size(), stateChangeDTO.getObjectParam().length); + } else { + ReflectionUtils.invokeMethod(method, stateMachineObject, stateChangeDTO.getObjectParam()); + } + } catch (ClassNotFoundException e) { + LogUtil.error(LogEnum.STATE_MACHINE, "The specified class was not found {} ", e); + throw new StateMachineException("The specified class was not found"); + } + } + + /** + * 代理执行多个状态机的状态切换 + * + * @param stateChangeDTOList 多个状态机切换信息 + * @param objectService 服务类 + */ + public static void proxyExecutionRelationState(List stateChangeDTOList,Object objectService) { + if (!CollectionUtils.isEmpty(stateChangeDTOList)) { + for (StateChangeDTO stateChangeDTO : stateChangeDTOList) { + proxyExecutionSingleState(stateChangeDTO,objectService); + } + } + } + + /** + * 校验参数是否正常 + * + * @param stateChangeDTO 数据集状态切换信息 + */ + public static void checkSingleParam(StateChangeDTO stateChangeDTO) { + if (StringUtils.isEmpty(stateChangeDTO.getStateMachineType())) { + throw new StateMachineException("No state machine class specified"); + } + if (StringUtils.isEmpty(stateChangeDTO.getEventMethodName())) { + throw new StateMachineException("The state machine is not specified and events need to be executed"); + } + } + + /** + * 根据方法名获取所有参数的类型 + * + * @param classInstance 类实例 + * @param methodName 方法名 + * @return List> 对象集合 + * @throws ClassNotFoundException + */ + public static List> getMethodParamTypes(Object classInstance, String methodName) throws ClassNotFoundException { + List> paramTypes = new ArrayList<>(); + Method[] methods = classInstance.getClass().getMethods(); + for (Method method : methods) { + if (method.getName().equals(methodName)) { + Class[] params = method.getParameterTypes(); + for (Class classParamType : params) { + paramTypes.addAll(Collections.singleton((Class) Class.forName(classParamType.getName()))); + } + break; + } + } + return paramTypes; + } + +} diff --git a/dubhe-server/common-cloud/auth-config/pom.xml b/dubhe-server/common-cloud/auth-config/pom.xml new file mode 100644 index 0000000..29a7aa7 --- /dev/null +++ b/dubhe-server/common-cloud/auth-config/pom.xml @@ -0,0 +1,60 @@ + + + 4.0.0 + + org.dubhe.cloud + common-cloud + 0.0.1-SNAPSHOT + + auth-config + 0.0.1-SNAPSHOT + Cloud 统一权限配置 + Authorization config for Spring Cloud + + + + + org.dubhe.biz + data-response + ${org.dubhe.biz.data-response.version} + + + + + org.dubhe.biz + base + ${org.dubhe.biz.base.version} + + + + javax.servlet + javax.servlet-api + ${javax.servlet-api.version} + + + + org.springframework.cloud + spring-cloud-starter-security + + + org.springframework.cloud + spring-cloud-starter-oauth2 + + + + + org.dubhe.cloud + remote-call + ${org.dubhe.cloud.remote-call.version} + + + + + + + + + + + diff --git a/dubhe-server/common-cloud/auth-config/src/main/java/org/dubhe/cloud/authconfig/config/ResourceServerConfig.java b/dubhe-server/common-cloud/auth-config/src/main/java/org/dubhe/cloud/authconfig/config/ResourceServerConfig.java new file mode 100644 index 0000000..c513e63 --- /dev/null +++ b/dubhe-server/common-cloud/auth-config/src/main/java/org/dubhe/cloud/authconfig/config/ResourceServerConfig.java @@ -0,0 +1,126 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.cloud.authconfig.config; + +import org.dubhe.biz.base.constant.AuthConst; +import org.dubhe.cloud.authconfig.exception.handler.CustomerAccessDeniedHandler; +import org.dubhe.cloud.authconfig.exception.handler.CustomerTokenExceptionEntryPoint; +import org.dubhe.cloud.authconfig.factory.AccessTokenConverterFactory; +import org.dubhe.cloud.authconfig.factory.TokenServicesFactory; +import org.dubhe.cloud.authconfig.factory.TokenStoreFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; +import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; +import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer; +import org.springframework.security.oauth2.provider.token.RemoteTokenServices; +import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore; +import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; +import org.springframework.web.client.RestTemplate; + +import javax.sql.DataSource; + +/** + * @description 资源服务器鉴权配置 + * @date 2020-11-05 + */ +@Configuration +@EnableResourceServer +@EnableGlobalMethodSecurity(prePostEnabled = true,jsr250Enabled = true) +public class ResourceServerConfig extends ResourceServerConfigurerAdapter { + + @Autowired + private RestTemplate restTemplate; + + @Autowired + private DataSource dataSource; + + @Autowired + private UserDetailsService userDetailsService; + + @Autowired + private CustomerAccessDeniedHandler accessDeniedHandler; + + @Autowired + private CustomerTokenExceptionEntryPoint tokenExceptionEntryPoint; + + @Value("${security.permitAll.matchers:}") + private String[] permitAllMatchers; + + @Override + public void configure(ResourceServerSecurityConfigurer resources) { + + //配置异常处理 + resources.authenticationEntryPoint(tokenExceptionEntryPoint) + .accessDeniedHandler(accessDeniedHandler); + + resources + .tokenStore(tokenStore()) + .stateless(true); + // 配置RemoteTokenServices,用于向AuthorizationServer验证令牌 + RemoteTokenServices tokenServices = TokenServicesFactory.getTokenServices(accessTokenConverter(),restTemplate); + resources.tokenServices(tokenServices) + .stateless(true); + + + } + + @Bean + public JdbcTokenStore tokenStore(){ + return TokenStoreFactory.getJdbcTokenStore(dataSource); + } + + /** + * JWT转换器 + * @return + */ + @Bean + public JwtAccessTokenConverter accessTokenConverter(){ + return AccessTokenConverterFactory.getAccessTokenConverter(userDetailsService); + } + + + @Override + public void configure(HttpSecurity http) throws Exception { + // 配置资源服务器的拦截规则 + http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED) + .and() + .authorizeRequests() + // swagger + .antMatchers(getPermitAllMatchers()).permitAll() + .anyRequest().authenticated() + ; + } + + /** + * 获取匿名访问路径 + * @return + */ + private String[] getPermitAllMatchers(){ + String[] c= new String[permitAllMatchers.length + AuthConst.DEFAULT_PERMIT_PATHS.length]; + System.arraycopy(permitAllMatchers, 0, c, 0, permitAllMatchers.length); + System.arraycopy(AuthConst.DEFAULT_PERMIT_PATHS, 0, c, permitAllMatchers.length, AuthConst.DEFAULT_PERMIT_PATHS.length); + return c; + } + +} diff --git a/dubhe-server/common-cloud/auth-config/src/main/java/org/dubhe/cloud/authconfig/decorator/AuthenticationThreadLocalTaskDecorator.java b/dubhe-server/common-cloud/auth-config/src/main/java/org/dubhe/cloud/authconfig/decorator/AuthenticationThreadLocalTaskDecorator.java new file mode 100644 index 0000000..214b19c --- /dev/null +++ b/dubhe-server/common-cloud/auth-config/src/main/java/org/dubhe/cloud/authconfig/decorator/AuthenticationThreadLocalTaskDecorator.java @@ -0,0 +1,51 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.cloud.authconfig.decorator; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.core.task.TaskDecorator; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; + +/** + * @description 线程池设置ThreadLocal用户信息 + * @date 2021-06-10 + */ +@Slf4j +public class AuthenticationThreadLocalTaskDecorator implements TaskDecorator { + + @Override + public Runnable decorate(Runnable runnable) { + final Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + return () -> { + try { + SecurityContextHolder.getContext().setAuthentication(authentication); + runnable.run(); + } catch (Throwable e){ + log.error(e.getMessage(), e); + } finally { + try { + SecurityContextHolder.getContext().setAuthentication(null); + } catch (Exception e){ + log.error(e.getMessage(), e); + throw new IllegalStateException(e); + } + } + }; + } +} diff --git a/dubhe-server/common-cloud/auth-config/src/main/java/org/dubhe/cloud/authconfig/dto/JwtUserDTO.java b/dubhe-server/common-cloud/auth-config/src/main/java/org/dubhe/cloud/authconfig/dto/JwtUserDTO.java new file mode 100644 index 0000000..7f05b98 --- /dev/null +++ b/dubhe-server/common-cloud/auth-config/src/main/java/org/dubhe/cloud/authconfig/dto/JwtUserDTO.java @@ -0,0 +1,92 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.cloud.authconfig.dto; + +import org.dubhe.biz.base.context.UserContext; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; + +import java.util.Collection; + +/** + * @description 安全用户模型 + * @date 2020-10-29 + */ +public class JwtUserDTO implements UserDetails{ + + private static final long serialVersionUID = 1L; + + private U user; + + private Collection authorities; + + public JwtUserDTO(U user, Collection authorities) { + this.user = user; + this.authorities = authorities; + } + + /** + * 获取当前用户ID + * @return + */ + public Long getCurUserId(){ + return user.getId(); + } + + /** + * 获取当前用户信息(不建议全部暴露,建议根据业务需要暴露可暴露信息) + * @return + */ + public U getUser() { + return user; + } + + @Override + public Collection getAuthorities() { + return authorities; + } + + @Override + public String getPassword() { + return user.getPassword(); + } + + @Override + public String getUsername() { + return user.getUsername(); + } + + @Override + public boolean isAccountNonExpired() { + return true; + } + + @Override + public boolean isAccountNonLocked() { + return true; + } + + @Override + public boolean isCredentialsNonExpired() { + return true; + } + + @Override + public boolean isEnabled() { + return true; + } +} diff --git a/dubhe-server/common-cloud/auth-config/src/main/java/org/dubhe/cloud/authconfig/exception/handler/CustomerAccessDeniedHandler.java b/dubhe-server/common-cloud/auth-config/src/main/java/org/dubhe/cloud/authconfig/exception/handler/CustomerAccessDeniedHandler.java new file mode 100644 index 0000000..2f9e151 --- /dev/null +++ b/dubhe-server/common-cloud/auth-config/src/main/java/org/dubhe/cloud/authconfig/exception/handler/CustomerAccessDeniedHandler.java @@ -0,0 +1,49 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.cloud.authconfig.exception.handler; + + +import com.alibaba.fastjson.JSONObject; +import org.dubhe.biz.base.constant.ResponseCode; +import org.dubhe.biz.dataresponse.factory.DataResponseFactory; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.springframework.http.MediaType; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.web.access.AccessDeniedHandler; +import org.springframework.stereotype.Component; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.Objects; + +/** + * @description 权限不足处理类 + * @date 2020-12-21 + */ +@Component +public class CustomerAccessDeniedHandler implements AccessDeniedHandler { + @Override + public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException{ + if(!Objects.isNull(e)){ + LogUtil.error(LogEnum.SYS_ERR,"CustomerTokenExceptionEntryPoint accessDeniedException is : {}",e); + } + httpServletResponse.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE); + httpServletResponse.getWriter().write(JSONObject.toJSONString(DataResponseFactory.failed(ResponseCode.UNAUTHORIZED,"无权访问"))); + } +} \ No newline at end of file diff --git a/dubhe-server/common-cloud/auth-config/src/main/java/org/dubhe/cloud/authconfig/exception/handler/CustomerTokenExceptionEntryPoint.java b/dubhe-server/common-cloud/auth-config/src/main/java/org/dubhe/cloud/authconfig/exception/handler/CustomerTokenExceptionEntryPoint.java new file mode 100644 index 0000000..d6995f0 --- /dev/null +++ b/dubhe-server/common-cloud/auth-config/src/main/java/org/dubhe/cloud/authconfig/exception/handler/CustomerTokenExceptionEntryPoint.java @@ -0,0 +1,50 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.cloud.authconfig.exception.handler; + + +import com.alibaba.fastjson.JSONObject; +import org.dubhe.biz.base.constant.ResponseCode; +import org.dubhe.biz.dataresponse.factory.DataResponseFactory; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.springframework.http.MediaType; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint; +import org.springframework.stereotype.Component; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.Objects; + + +/** + * @description token无效处理类 + * @date 2020-12-21 + */ +@Component +public class CustomerTokenExceptionEntryPoint extends OAuth2AuthenticationEntryPoint { + @Override + public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException { + if(!Objects.isNull(e)){ + LogUtil.error(LogEnum.SYS_ERR,"CustomerTokenExceptionEntryPoint authenticationException is : {}",e); + } + httpServletResponse.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE); + httpServletResponse.getWriter().write(JSONObject.toJSONString(DataResponseFactory.failed(ResponseCode.TOKEN_ERROR,"token无效或已过期"))); + } +} diff --git a/dubhe-server/common-cloud/auth-config/src/main/java/org/dubhe/cloud/authconfig/factory/AccessTokenConverterFactory.java b/dubhe-server/common-cloud/auth-config/src/main/java/org/dubhe/cloud/authconfig/factory/AccessTokenConverterFactory.java new file mode 100644 index 0000000..b3ddb05 --- /dev/null +++ b/dubhe-server/common-cloud/auth-config/src/main/java/org/dubhe/cloud/authconfig/factory/AccessTokenConverterFactory.java @@ -0,0 +1,51 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.cloud.authconfig.factory; + +import org.dubhe.biz.base.constant.AuthConst; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter; +import org.springframework.security.oauth2.provider.token.DefaultUserAuthenticationConverter; +import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; + +/** + * @description AccessTokenConverter 工厂类 + * @date 2020-11-24 + */ +public class AccessTokenConverterFactory { + + private AccessTokenConverterFactory(){} + + + /** + * 获取JwtAccessTokenConverter + * @param userDetailsService 自定义实现的用户信息获取Service + * @return jwtAccessTokenConverter + */ + public static JwtAccessTokenConverter getAccessTokenConverter(UserDetailsService userDetailsService){ + DefaultUserAuthenticationConverter userAuthenticationConverter = new DefaultUserAuthenticationConverter(); + userAuthenticationConverter.setUserDetailsService(userDetailsService); + + DefaultAccessTokenConverter converter = new DefaultAccessTokenConverter(); + converter.setUserTokenConverter(userAuthenticationConverter); + + JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter(); + jwtAccessTokenConverter.setSigningKey(AuthConst.CLIENT_SECRET); + jwtAccessTokenConverter.setAccessTokenConverter(converter); + return jwtAccessTokenConverter; + } +} diff --git a/dubhe-server/common-cloud/auth-config/src/main/java/org/dubhe/cloud/authconfig/factory/PasswordEncoderFactory.java b/dubhe-server/common-cloud/auth-config/src/main/java/org/dubhe/cloud/authconfig/factory/PasswordEncoderFactory.java new file mode 100644 index 0000000..e67ca4e --- /dev/null +++ b/dubhe-server/common-cloud/auth-config/src/main/java/org/dubhe/cloud/authconfig/factory/PasswordEncoderFactory.java @@ -0,0 +1,44 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.cloud.authconfig.factory; + +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; + +/** + * @description 加密工具工厂类 + * @date 2020-11-06 + */ +public class PasswordEncoderFactory { + + private PasswordEncoderFactory(){ + + } + + + public static final PasswordEncoder PASSWORD_ENCODER = new BCryptPasswordEncoder(); + + /** + * 获取加密器 + * @return + */ + public static PasswordEncoder getPasswordEncoder(){ + return PASSWORD_ENCODER; + } + +} diff --git a/dubhe-server/common-cloud/auth-config/src/main/java/org/dubhe/cloud/authconfig/factory/TokenServicesFactory.java b/dubhe-server/common-cloud/auth-config/src/main/java/org/dubhe/cloud/authconfig/factory/TokenServicesFactory.java new file mode 100644 index 0000000..40aaa54 --- /dev/null +++ b/dubhe-server/common-cloud/auth-config/src/main/java/org/dubhe/cloud/authconfig/factory/TokenServicesFactory.java @@ -0,0 +1,54 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.cloud.authconfig.factory; + +import org.dubhe.biz.base.constant.AuthConst; +import org.springframework.security.oauth2.provider.token.RemoteTokenServices; +import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; +import org.springframework.web.client.RestTemplate; + +/** + * @description TokenServices 工厂类 + * @date 2020-11-25 + */ +public class TokenServicesFactory { + + private TokenServicesFactory(){ + + } + + /** + * 获取 RemoteTokenServices + * @param accessTokenConverter token转换器 + * @param restTemplate rest请求模板 + * @return RemoteTokenServices + */ + public static RemoteTokenServices getTokenServices(JwtAccessTokenConverter accessTokenConverter, RestTemplate restTemplate){ + RemoteTokenServices tokenServices = new RemoteTokenServices(); + if (accessTokenConverter != null){ + tokenServices.setAccessTokenConverter(accessTokenConverter); + } + // 配置异常处理器 +// restTemplate.setErrorHandler(new OAuth2ResponseErrorHandler()); + tokenServices.setRestTemplate(restTemplate); + tokenServices.setCheckTokenEndpointUrl(AuthConst.CHECK_TOKEN_ENDPOINT_URL); + tokenServices.setClientId(AuthConst.CLIENT_ID); + tokenServices.setClientSecret(AuthConst.CLIENT_SECRET); + return tokenServices; + } + +} diff --git a/dubhe-server/common-cloud/auth-config/src/main/java/org/dubhe/cloud/authconfig/factory/TokenStoreFactory.java b/dubhe-server/common-cloud/auth-config/src/main/java/org/dubhe/cloud/authconfig/factory/TokenStoreFactory.java new file mode 100644 index 0000000..99a4714 --- /dev/null +++ b/dubhe-server/common-cloud/auth-config/src/main/java/org/dubhe/cloud/authconfig/factory/TokenStoreFactory.java @@ -0,0 +1,41 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.cloud.authconfig.factory; + +import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore; + +import javax.sql.DataSource; + +/** + * @description TokenStore工厂类 + * @date 2020-11-24 + */ +public class TokenStoreFactory { + + private TokenStoreFactory(){ + + } + + /** + * 获取token存储 + * @param dataSource 数据库数据源 + * @return + */ + public static JdbcTokenStore getJdbcTokenStore(DataSource dataSource){ + return new JdbcTokenStore(dataSource); + } +} diff --git a/dubhe-server/common-cloud/auth-config/src/main/java/org/dubhe/cloud/authconfig/filter/OAuth2ResponseErrorFilter.java b/dubhe-server/common-cloud/auth-config/src/main/java/org/dubhe/cloud/authconfig/filter/OAuth2ResponseErrorFilter.java new file mode 100644 index 0000000..eb57fa5 --- /dev/null +++ b/dubhe-server/common-cloud/auth-config/src/main/java/org/dubhe/cloud/authconfig/filter/OAuth2ResponseErrorFilter.java @@ -0,0 +1,71 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.cloud.authconfig.filter; + +import com.alibaba.fastjson.JSON; +import lombok.extern.slf4j.Slf4j; +import org.dubhe.biz.base.exception.OAuthResponseError; +import org.dubhe.biz.dataresponse.factory.DataResponseFactory; +import org.springframework.http.HttpStatus; +import org.springframework.web.client.ResourceAccessException; + +import javax.servlet.*; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +/** + * @description OAuth2 授权异常 过滤器 + * @date 2020-11-18 + */ +@Slf4j +public class OAuth2ResponseErrorFilter implements Filter { + + /** + * 过滤并处理OAuth2异常抛出 + * + * @param servletRequest + * @param servletResponse + * @param filterChain + * @throws IOException + * @throws ServletException + */ + @Override + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { + HttpServletResponse response = ((HttpServletResponse) servletResponse); + try { + filterChain.doFilter(servletRequest,servletResponse); + }catch (OAuthResponseError e){ + log.error("鉴权失败!",e); + response.setStatus(e.getStatusCode().value()); + response.getOutputStream().write(JSON.toJSON(e.getResponseBody()).toString().getBytes()); + }catch (IllegalStateException | ResourceAccessException e){ + log.error("授权服务未发现!",e); + response.setStatus(HttpStatus.NOT_FOUND.value()); + response + .getOutputStream() + .write(JSON.toJSON(DataResponseFactory.failed(e.getMessage())).toString().getBytes()); + }catch (Exception e){ + log.error("授权异常!",e); + response.setStatus(HttpStatus.UNAUTHORIZED.value()); + response + .getOutputStream() + .write(JSON.toJSON(DataResponseFactory.failed("OAuth2 response error!")).toString().getBytes()); + } + } + + +} diff --git a/dubhe-server/common-cloud/auth-config/src/main/java/org/dubhe/cloud/authconfig/service/AdminClient.java b/dubhe-server/common-cloud/auth-config/src/main/java/org/dubhe/cloud/authconfig/service/AdminClient.java new file mode 100644 index 0000000..8b826df --- /dev/null +++ b/dubhe-server/common-cloud/auth-config/src/main/java/org/dubhe/cloud/authconfig/service/AdminClient.java @@ -0,0 +1,51 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.cloud.authconfig.service; + +import org.dubhe.biz.base.constant.ApplicationNameConst; +import org.dubhe.biz.base.context.UserContext; +import org.dubhe.biz.base.dto.UserDTO; +import org.dubhe.biz.base.vo.DataResponseBody; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestParam; + +import java.util.List; + +/** + * @description admin远程服务调用类 + * @date 2020-12-10 + */ +@FeignClient(value = ApplicationNameConst.SERVER_ADMIN,fallback = AdminClientFallback.class) +public interface AdminClient { + + /** + * 根据用户名称获取用户信息 + * + * @param username 用户名称 + * @return 用户信息 + */ + @GetMapping(value = "/users/findUserByUsername") + DataResponseBody findUserByUsername(@RequestParam(value = "username") String username); + + @GetMapping(value = "/users/findById") + DataResponseBody getUsers(@RequestParam(value = "userId") Long userId); + + @GetMapping(value = "/users/findByIds") + DataResponseBody> getUserList(@RequestParam(value = "ids") List ids); + +} diff --git a/dubhe-server/common-cloud/auth-config/src/main/java/org/dubhe/cloud/authconfig/service/AdminClientFallback.java b/dubhe-server/common-cloud/auth-config/src/main/java/org/dubhe/cloud/authconfig/service/AdminClientFallback.java new file mode 100644 index 0000000..8bb550e --- /dev/null +++ b/dubhe-server/common-cloud/auth-config/src/main/java/org/dubhe/cloud/authconfig/service/AdminClientFallback.java @@ -0,0 +1,47 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.cloud.authconfig.service; + +import org.dubhe.biz.base.dto.UserDTO; +import org.dubhe.biz.base.vo.DataResponseBody; +import org.dubhe.biz.dataresponse.factory.DataResponseFactory; +import org.springframework.stereotype.Component; + +import java.util.List; + +/** + * @description admin远程服务调用类熔断 + * @date 2020-12-10 + */ +@Component +public class AdminClientFallback implements AdminClient { + @Override + public DataResponseBody findUserByUsername(String username) { + return DataResponseFactory.failed("call admin server findUserByUsername error"); + } + + @Override + public DataResponseBody getUsers(Long userId) { + return DataResponseFactory.failed("call user controller to get user error"); + } + + @Override + public DataResponseBody> getUserList(List ids) { + return DataResponseFactory.failed("call user controller to get users error"); + } + +} \ No newline at end of file diff --git a/dubhe-server/common-cloud/auth-config/src/main/java/org/dubhe/cloud/authconfig/service/AdminUserService.java b/dubhe-server/common-cloud/auth-config/src/main/java/org/dubhe/cloud/authconfig/service/AdminUserService.java new file mode 100644 index 0000000..3827fe9 --- /dev/null +++ b/dubhe-server/common-cloud/auth-config/src/main/java/org/dubhe/cloud/authconfig/service/AdminUserService.java @@ -0,0 +1,39 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.cloud.authconfig.service; + + +import org.dubhe.biz.base.context.UserContext; +import org.dubhe.biz.base.vo.DataResponseBody; + +/** + * @description Demo服务接口 + * @date 2020-11-26 + */ +public interface AdminUserService { + + /** + * 根据用户名查询用户信息 + * + * @param username 用户名称 + * @return 用户信息 + */ + DataResponseBody findUserByUsername(String username); + + + +} diff --git a/dubhe-server/common-cloud/auth-config/src/main/java/org/dubhe/cloud/authconfig/service/impl/GrantedAuthorityImpl.java b/dubhe-server/common-cloud/auth-config/src/main/java/org/dubhe/cloud/authconfig/service/impl/GrantedAuthorityImpl.java new file mode 100644 index 0000000..f538d2e --- /dev/null +++ b/dubhe-server/common-cloud/auth-config/src/main/java/org/dubhe/cloud/authconfig/service/impl/GrantedAuthorityImpl.java @@ -0,0 +1,43 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.cloud.authconfig.service.impl; + +import org.springframework.security.core.GrantedAuthority; + +/** + * @description 权限封装 + * @date 2020-10-29 + */ +public class GrantedAuthorityImpl implements GrantedAuthority { + + private static final long serialVersionUID = 1L; + + private String authority; + + public GrantedAuthorityImpl(String authority) { + this.authority = authority; + } + + public void setAuthority(String authority) { + this.authority = authority; + } + + @Override + public String getAuthority() { + return this.authority; + } +} diff --git a/dubhe-server/common-cloud/auth-config/src/main/java/org/dubhe/cloud/authconfig/service/impl/OAuth2UserContextServiceImpl.java b/dubhe-server/common-cloud/auth-config/src/main/java/org/dubhe/cloud/authconfig/service/impl/OAuth2UserContextServiceImpl.java new file mode 100644 index 0000000..390f319 --- /dev/null +++ b/dubhe-server/common-cloud/auth-config/src/main/java/org/dubhe/cloud/authconfig/service/impl/OAuth2UserContextServiceImpl.java @@ -0,0 +1,43 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.cloud.authconfig.service.impl; + +import org.dubhe.biz.base.context.UserContext; +import org.dubhe.biz.base.service.UserContextService; +import org.dubhe.cloud.authconfig.dto.JwtUserDTO; +import org.dubhe.cloud.authconfig.utils.JwtUtils; +import org.springframework.stereotype.Service; + +/** + * @description OAuth2 当前信息获取实现类 + * @date 2020-12-07 + */ +@Service(value = "oAuth2UserContextServiceImpl") +public class OAuth2UserContextServiceImpl implements UserContextService { + + @Override + public UserContext getCurUser() { + JwtUserDTO jwtUserDTO = JwtUtils.getCurUser(); + return jwtUserDTO == null?null:jwtUserDTO.getUser(); + } + + @Override + public Long getCurUserId() { + UserContext userContext = getCurUser(); + return userContext == null?null:userContext.getId(); + } +} diff --git a/dubhe-server/common-cloud/auth-config/src/main/java/org/dubhe/cloud/authconfig/service/impl/UserDetailsServiceImpl.java b/dubhe-server/common-cloud/auth-config/src/main/java/org/dubhe/cloud/authconfig/service/impl/UserDetailsServiceImpl.java new file mode 100644 index 0000000..0b034cd --- /dev/null +++ b/dubhe-server/common-cloud/auth-config/src/main/java/org/dubhe/cloud/authconfig/service/impl/UserDetailsServiceImpl.java @@ -0,0 +1,99 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.cloud.authconfig.service.impl; + +import org.dubhe.biz.base.context.UserContext; +import org.dubhe.biz.base.dto.SysPermissionDTO; +import org.dubhe.biz.base.dto.SysRoleDTO; +import org.dubhe.biz.base.exception.BusinessException; +import org.dubhe.biz.base.vo.DataResponseBody; +import org.dubhe.cloud.authconfig.dto.JwtUserDTO; +import org.dubhe.cloud.authconfig.service.AdminUserService; +import org.dubhe.cloud.authconfig.service.AdminClient; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Service; +import org.springframework.util.CollectionUtils; + +import javax.annotation.Resource; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * @description 自定义用户实现类(未实现对应数据库持久化设置) + * @date 2020-10-29 + */ +@Service +public class UserDetailsServiceImpl implements UserDetailsService { + + @Value("${spring.application.name}") + private String curService; + + @Autowired(required = false) + private AdminUserService adminUserService; + + @Resource + private AdminClient adminClient; + + /** + * 捞取用户信息 + * @param username + * @return + * @throws UsernameNotFoundException + */ + @Override + public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { + //根据adminUserService 子类是否加载 采取不同的方式获取用户信息 + DataResponseBody responseBody = Objects.isNull(adminUserService) + ? adminClient.findUserByUsername(username) : adminUserService.findUserByUsername(username); + if (responseBody == null || Objects.isNull(responseBody.getData())){ + throw new BusinessException(responseBody.getMsg()); + } + UserContext data = responseBody.getData(); + // 用户权限列表,根据用户拥有的权限标识与如 @PreAuthorize("hasAuthority('user')") 标注的接口对比,决定是否可以调用接口 + Set permissions = findPermissions(data.getRoles()); + List grantedAuthorities = permissions.stream().map(GrantedAuthorityImpl::new).collect(Collectors.toList()); + return new JwtUserDTO(data, grantedAuthorities); + } + + /** + * 固定权限 + * @return + */ + private Set findPermissions(List roles) { + Set permissions = new HashSet<>(); + roles.forEach(a->{ + permissions.add("ROLE_"+a.getName()); + List permissionsNames = a.getPermissions(); + if(!CollectionUtils.isEmpty(permissionsNames)){ + permissionsNames.forEach(b->{ + permissions.add("ROLE_"+b.getPermission()); + }); + + } + }); + return permissions; + } + +} diff --git a/dubhe-server/common-cloud/auth-config/src/main/java/org/dubhe/cloud/authconfig/utils/JwtUtils.java b/dubhe-server/common-cloud/auth-config/src/main/java/org/dubhe/cloud/authconfig/utils/JwtUtils.java new file mode 100644 index 0000000..0768f42 --- /dev/null +++ b/dubhe-server/common-cloud/auth-config/src/main/java/org/dubhe/cloud/authconfig/utils/JwtUtils.java @@ -0,0 +1,63 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.cloud.authconfig.utils; + +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.dubhe.cloud.authconfig.dto.JwtUserDTO; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; + +/** + * @description JWT + * @date 2020-11-25 + */ +public class JwtUtils { + + private JwtUtils(){ + + } + + /** + * 获取当前用户信息 + * @return 当前用户信息 + */ + public static JwtUserDTO getCurUser(){ + try { + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + if(authentication == null){ + return null; + } + if (authentication.getPrincipal() instanceof JwtUserDTO){ + return (JwtUserDTO) authentication.getPrincipal(); + } + }catch (Exception e){ + LogUtil.error(LogEnum.SYS_ERR,"Jwt getCurUser error!{}",e); + } + return null; + } + + /** + * 获取当前用户ID + * 若用户不存在,则返回null(可根据业务统一修改) + * @return 当前用户ID + */ + public static Long getCurUserId(){ + JwtUserDTO jwtUserDTO = getCurUser(); + return jwtUserDTO == null?null:jwtUserDTO.getCurUserId(); + } +} diff --git a/dubhe-server/common-cloud/configuration/pom.xml b/dubhe-server/common-cloud/configuration/pom.xml new file mode 100644 index 0000000..939aa96 --- /dev/null +++ b/dubhe-server/common-cloud/configuration/pom.xml @@ -0,0 +1,30 @@ + + + 4.0.0 + + org.dubhe.cloud + common-cloud + 0.0.1-SNAPSHOT + + configuration + 0.0.1-SNAPSHOT + Cloud 配置中心 + Configuration for Spring Cloud + + + + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-config + ${nacos.version} + + + + + + + + + + + diff --git a/dubhe-server/common-cloud/configuration/src/main/resources/bootstrap-cloud-data.yml b/dubhe-server/common-cloud/configuration/src/main/resources/bootstrap-cloud-data.yml new file mode 100644 index 0000000..23e7d7e --- /dev/null +++ b/dubhe-server/common-cloud/configuration/src/main/resources/bootstrap-cloud-data.yml @@ -0,0 +1,7 @@ +spring: + cloud: + nacos: + config: + namespace: dubhe-server-cloud-test-data + discovery: + namespace: dubhe-server-cloud-test-data diff --git a/dubhe-server/common-cloud/configuration/src/main/resources/bootstrap-cloud-dev.yml b/dubhe-server/common-cloud/configuration/src/main/resources/bootstrap-cloud-dev.yml new file mode 100644 index 0000000..0b3a9d3 --- /dev/null +++ b/dubhe-server/common-cloud/configuration/src/main/resources/bootstrap-cloud-dev.yml @@ -0,0 +1,7 @@ +spring: + cloud: + nacos: + config: + namespace: dubhe-server-cloud-dev + discovery: + namespace: dubhe-server-cloud-dev diff --git a/dubhe-server/common-cloud/configuration/src/main/resources/bootstrap-cloud-test.yml b/dubhe-server/common-cloud/configuration/src/main/resources/bootstrap-cloud-test.yml new file mode 100644 index 0000000..405d24e --- /dev/null +++ b/dubhe-server/common-cloud/configuration/src/main/resources/bootstrap-cloud-test.yml @@ -0,0 +1,7 @@ +spring: + cloud: + nacos: + config: + namespace: dubhe-server-cloud-test + discovery: + namespace: dubhe-server-cloud-test diff --git a/dubhe-server/common-cloud/configuration/src/main/resources/bootstrap-dev.yml b/dubhe-server/common-cloud/configuration/src/main/resources/bootstrap-dev.yml new file mode 100644 index 0000000..429a30f --- /dev/null +++ b/dubhe-server/common-cloud/configuration/src/main/resources/bootstrap-dev.yml @@ -0,0 +1,7 @@ +spring: + cloud: + nacos: + config: + namespace: dubhe-server-cloud-prod + discovery: + namespace: dubhe-server-cloud-prod diff --git a/dubhe-server/common-cloud/configuration/src/main/resources/bootstrap-istio-dev.yml b/dubhe-server/common-cloud/configuration/src/main/resources/bootstrap-istio-dev.yml new file mode 100644 index 0000000..f3895a8 --- /dev/null +++ b/dubhe-server/common-cloud/configuration/src/main/resources/bootstrap-istio-dev.yml @@ -0,0 +1,7 @@ +spring: + cloud: + nacos: + config: + namespace: dubhe-server-istio-dev + discovery: + namespace: dubhe-server-istio-dev diff --git a/dubhe-server/common-cloud/configuration/src/main/resources/bootstrap-istio-test.yml b/dubhe-server/common-cloud/configuration/src/main/resources/bootstrap-istio-test.yml new file mode 100644 index 0000000..51c1cd8 --- /dev/null +++ b/dubhe-server/common-cloud/configuration/src/main/resources/bootstrap-istio-test.yml @@ -0,0 +1,7 @@ +spring: + cloud: + nacos: + config: + namespace: dubhe-server-istio-test + discovery: + namespace: dubhe-server-istio-test diff --git a/dubhe-server/common-cloud/configuration/src/main/resources/bootstrap-prod.yml b/dubhe-server/common-cloud/configuration/src/main/resources/bootstrap-prod.yml new file mode 100644 index 0000000..429a30f --- /dev/null +++ b/dubhe-server/common-cloud/configuration/src/main/resources/bootstrap-prod.yml @@ -0,0 +1,7 @@ +spring: + cloud: + nacos: + config: + namespace: dubhe-server-cloud-prod + discovery: + namespace: dubhe-server-cloud-prod diff --git a/dubhe-server/common-cloud/pom.xml b/dubhe-server/common-cloud/pom.xml new file mode 100644 index 0000000..7d9d1b4 --- /dev/null +++ b/dubhe-server/common-cloud/pom.xml @@ -0,0 +1,37 @@ + + + 4.0.0 + pom + + org.dubhe + server + 0.0.1-SNAPSHOT + + org.dubhe.cloud + common-cloud + 0.0.1-SNAPSHOT + 通用SpringCloud模块(Cloud) + Dubhe Common for Spring Cloud + + + auth-config + swagger + remote-call + registration + configuration + unit-test + + + + + + + + + + + + + + diff --git a/dubhe-server/common-cloud/registration/pom.xml b/dubhe-server/common-cloud/registration/pom.xml new file mode 100644 index 0000000..08cf43f --- /dev/null +++ b/dubhe-server/common-cloud/registration/pom.xml @@ -0,0 +1,29 @@ + + + 4.0.0 + + org.dubhe.cloud + common-cloud + 0.0.1-SNAPSHOT + + registration + 0.0.1-SNAPSHOT + Cloud 注册中心 + Registration for Spring Cloud + + + + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-discovery + ${nacos.version} + + + + + + + + + + diff --git a/dubhe-server/common-cloud/registration/src/main/java/org/dubhe/cloud/registration/RegistrationConfig.java b/dubhe-server/common-cloud/registration/src/main/java/org/dubhe/cloud/registration/RegistrationConfig.java new file mode 100644 index 0000000..ba13a2d --- /dev/null +++ b/dubhe-server/common-cloud/registration/src/main/java/org/dubhe/cloud/registration/RegistrationConfig.java @@ -0,0 +1,29 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.cloud.registration; + +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.context.annotation.Configuration; + +/** + * @description 注册中心默认配置 + * @date 2020-12-11 + */ +@Configuration +@EnableDiscoveryClient +public class RegistrationConfig { +} diff --git a/dubhe-server/common-cloud/remote-call/pom.xml b/dubhe-server/common-cloud/remote-call/pom.xml new file mode 100644 index 0000000..e382c34 --- /dev/null +++ b/dubhe-server/common-cloud/remote-call/pom.xml @@ -0,0 +1,71 @@ + + + 4.0.0 + + org.dubhe.cloud + common-cloud + 0.0.1-SNAPSHOT + + remote-call + 0.0.1-SNAPSHOT + Cloud 远程调用 + Remote call for Spring Cloud + + + + + + org.dubhe.biz + base + ${org.dubhe.biz.base.version} + + + + org.dubhe.biz + log + ${org.dubhe.biz.log.version} + + + + org.springframework.cloud + spring-cloud-starter-netflix-hystrix + + + + org.springframework.cloud + spring-cloud-openfeign-core + + + org.springframework.cloud + spring-cloud-starter-feign + ${feign.version} + + + io.github.openfeign + feign-httpclient + + + + javax.servlet + javax.servlet-api + ${javax.servlet-api.version} + + + com.squareup.okhttp3 + okhttp + ${okhttp.version} + + + io.github.openfeign + feign-httpclient + + + + + + + + + + diff --git a/dubhe-server/common-cloud/remote-call/src/main/java/org/dubhe/cloud/remotecall/config/FeignErrorDecoder.java b/dubhe-server/common-cloud/remote-call/src/main/java/org/dubhe/cloud/remotecall/config/FeignErrorDecoder.java new file mode 100644 index 0000000..9f15754 --- /dev/null +++ b/dubhe-server/common-cloud/remote-call/src/main/java/org/dubhe/cloud/remotecall/config/FeignErrorDecoder.java @@ -0,0 +1,54 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.cloud.remotecall.config; + + + + +import com.alibaba.fastjson.JSONObject; +import feign.Response; +import feign.Util; +import feign.codec.ErrorDecoder; +import org.dubhe.biz.base.exception.FeignException; +import org.dubhe.biz.base.vo.DataResponseBody; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.springframework.context.annotation.Configuration; + + +/** + * @description feign 异常处理类 + * @date 2020-12-21 + */ + +@Configuration +public class FeignErrorDecoder implements ErrorDecoder { + + @Override + public Exception decode(String s, Response response) { + FeignException baseException = null; + try { + String errorContent = Util.toString(response.body().asReader()); + DataResponseBody result = JSONObject.parseObject(errorContent, DataResponseBody.class); + baseException = new FeignException(result.getCode(), result.getMsg()); + } catch (Exception e) { + LogUtil.error(LogEnum.SYS_ERR,"FeignClient error :{}",e); + } + return baseException; + } +} diff --git a/dubhe-server/common-cloud/remote-call/src/main/java/org/dubhe/cloud/remotecall/config/HttpClientConfig.java b/dubhe-server/common-cloud/remote-call/src/main/java/org/dubhe/cloud/remotecall/config/HttpClientConfig.java new file mode 100644 index 0000000..58e60d8 --- /dev/null +++ b/dubhe-server/common-cloud/remote-call/src/main/java/org/dubhe/cloud/remotecall/config/HttpClientConfig.java @@ -0,0 +1,125 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.cloud.remotecall.config; + +import org.apache.commons.lang3.concurrent.BasicThreadFactory; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy; +import org.apache.http.impl.client.DefaultHttpRequestRetryHandler; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; +import org.dubhe.biz.base.constant.MagicNumConstant; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.springframework.boot.autoconfigure.AutoConfigureBefore; +import org.springframework.cloud.openfeign.FeignAutoConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +import static org.dubhe.biz.base.constant.MagicNumConstant.ONE_THOUSAND; + +/** + * @description HttpClient配置类 + * @date 2020-12-28 + */ +@Configuration +@AutoConfigureBefore(FeignAutoConfiguration.class) +public class HttpClientConfig { + + /** + * 超时时间(秒) + */ + private final static int TIMEOUT_SECOND = MagicNumConstant.FIVE; + + private final ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1, + new BasicThreadFactory.Builder().namingPattern("RemoteCall HTTP连接回收管理器-%d").daemon(true).build()); + + /** + * 构建HttpClient + * @return HttpClient + */ + @Bean + public CloseableHttpClient httpClient(){ + int processCount = Runtime.getRuntime().availableProcessors() * 2; + return httpClientBuilder(processCount).build(); + } + + /** + * 获取Http客户端生成器 + * @param processCount 当前硬件线程数*2 + * @return HttpClientBuilder + */ + private HttpClientBuilder httpClientBuilder(int processCount){ + HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); + // Keep Alive 默认策略 + httpClientBuilder.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy()); + // 连接管理器 + httpClientBuilder.setConnectionManager(poolingHttpClientConnectionManager(processCount)); + // Request请求配置 + httpClientBuilder.setDefaultRequestConfig(requestConfig()); + // 重试策略 + httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(2, true)); + return httpClientBuilder; + } + + /** + * 获取Request请求配置 + * @return RequestConfig + */ + private RequestConfig requestConfig(){ + RequestConfig.Builder requestConfigBuilder = RequestConfig.custom(); + // Socket超时时间(毫秒) + requestConfigBuilder.setSocketTimeout(TIMEOUT_SECOND * ONE_THOUSAND); + // 连接超时时间(毫秒) + requestConfigBuilder.setConnectTimeout(TIMEOUT_SECOND * ONE_THOUSAND); + // 从连接管理器中请求连接的超时时间(毫秒) + requestConfigBuilder.setConnectionRequestTimeout(1 * ONE_THOUSAND); + return requestConfigBuilder.build(); + } + + /** + * 获取http连接管理器 + * @param processCount 当前硬件线程数*2 + * @return PoolingHttpClientConnectionManager + */ + private PoolingHttpClientConnectionManager poolingHttpClientConnectionManager(int processCount){ + PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager(1, TimeUnit.MINUTES); + // 总连接数 + manager.setMaxTotal(processCount); + // 同一个路由并发数控制 + manager.setDefaultMaxPerRoute(processCount/2); + // 连接不活跃1秒后验证有效性 + manager.setValidateAfterInactivity(1 * ONE_THOUSAND); + executorService.scheduleAtFixedRate(new Runnable() { + @Override + public void run() { + LogUtil.debug(LogEnum.REMOTE_CALL,"PoolingHttpClientConnectionManager time to close connection.. "); + // 关闭过期连接 + manager.closeExpiredConnections(); + // 关闭空闲5秒连接 + manager.closeIdleConnections(TIMEOUT_SECOND,TimeUnit.SECONDS); + } + },10,5, TimeUnit.SECONDS); + return manager; + } + +} diff --git a/dubhe-server/common-cloud/remote-call/src/main/java/org/dubhe/cloud/remotecall/config/RemoteCallConfig.java b/dubhe-server/common-cloud/remote-call/src/main/java/org/dubhe/cloud/remotecall/config/RemoteCallConfig.java new file mode 100644 index 0000000..d0deac0 --- /dev/null +++ b/dubhe-server/common-cloud/remote-call/src/main/java/org/dubhe/cloud/remotecall/config/RemoteCallConfig.java @@ -0,0 +1,44 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.cloud.remotecall.config; + +import org.dubhe.biz.base.constant.AuthConst; +import org.springframework.cloud.openfeign.EnableFeignClients; +import org.springframework.context.annotation.Configuration; + +import java.util.LinkedList; +import java.util.List; + +/** + * @description 远程调用默认配置 + * @date 2020-12-11 + */ +@Configuration +@EnableFeignClients(basePackages = "org.dubhe") +public class RemoteCallConfig { + + /** + * 待处理token列表 + */ + public static final List TOKEN_LIST = new LinkedList<>(); + + static { + TOKEN_LIST.add(AuthConst.AUTHORIZATION); + TOKEN_LIST.add(AuthConst.K8S_CALLBACK_TOKEN); + TOKEN_LIST.add(AuthConst.COMMON_TOKEN); + } +} diff --git a/dubhe-server/common-cloud/remote-call/src/main/java/org/dubhe/cloud/remotecall/config/RestTemplateConfig.java b/dubhe-server/common-cloud/remote-call/src/main/java/org/dubhe/cloud/remotecall/config/RestTemplateConfig.java new file mode 100644 index 0000000..5b5c45f --- /dev/null +++ b/dubhe-server/common-cloud/remote-call/src/main/java/org/dubhe/cloud/remotecall/config/RestTemplateConfig.java @@ -0,0 +1,61 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.cloud.remotecall.config; + +import org.apache.http.impl.client.CloseableHttpClient; +import org.dubhe.cloud.remotecall.interceptor.RestTemplateTokenInterceptor; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.cloud.client.loadbalancer.LoadBalanced; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; +import org.springframework.web.client.RestTemplate; + +import java.util.Collections; + +/** + * @description RestTemplate配置类 + * @date 2020-11-26 + */ +@Configuration +@ConditionalOnMissingBean(RestTemplate.class) +public class RestTemplateConfig { + + @Autowired + private CloseableHttpClient httpClient; + + /** + * 负载均衡 + * @return RestTemplate + */ + @LoadBalanced + @Bean + public RestTemplate restTemplate() { + RestTemplate restTemplate = new RestTemplate( + new HttpComponentsClientHttpRequestFactory(httpClient) + ); + //拦截器统一添加token + restTemplate.setInterceptors( + Collections.singletonList( + new RestTemplateTokenInterceptor() + ) + ); + return restTemplate; + } + +} diff --git a/dubhe-server/common-cloud/remote-call/src/main/java/org/dubhe/cloud/remotecall/config/RestTemplateHolder.java b/dubhe-server/common-cloud/remote-call/src/main/java/org/dubhe/cloud/remotecall/config/RestTemplateHolder.java new file mode 100644 index 0000000..0fe7b4e --- /dev/null +++ b/dubhe-server/common-cloud/remote-call/src/main/java/org/dubhe/cloud/remotecall/config/RestTemplateHolder.java @@ -0,0 +1,95 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.cloud.remotecall.config; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.http.MediaType; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; +import org.springframework.stereotype.Component; +import org.springframework.web.client.RestTemplate; + +import javax.annotation.PostConstruct; +import java.lang.reflect.Field; +import java.util.Arrays; +import java.util.List; + + +/** + * @description RestTemplate持有器(调用非nacos中注册的服务) + * @date 2021-01-07 + */ +@Component +public class RestTemplateHolder { + + @Autowired + private ObjectMapper objectMapper; + + @Autowired + private RestTemplateBuilder restTemplateBuilder; + + private RestTemplate restTemplate; + + @PostConstruct + private void init() { + RestTemplate template = restTemplateBuilder.build(); + + MediaType[] mediaTypes = new MediaType[]{ + MediaType.APPLICATION_JSON, + MediaType.APPLICATION_OCTET_STREAM, + MediaType.TEXT_HTML, + MediaType.TEXT_PLAIN, + MediaType.TEXT_XML, + MediaType.APPLICATION_STREAM_JSON, + MediaType.APPLICATION_ATOM_XML, + MediaType.APPLICATION_FORM_URLENCODED, + MediaType.APPLICATION_JSON_UTF8, + MediaType.APPLICATION_PDF, + }; + + MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); + converter.setObjectMapper(objectMapper); + converter.setSupportedMediaTypes(Arrays.asList(mediaTypes)); + + try { + Field field = template.getClass().getDeclaredField("messageConverters"); + field.setAccessible(true); + List> orgConverterList = (List>) field.get(template); + + for (int i = 0; i < orgConverterList.size(); i++) { + if (MappingJackson2HttpMessageConverter.class.equals(orgConverterList.get(i).getClass())) { + orgConverterList.set(i, converter); + } + } + + } catch (Exception e) { + LogUtil.error(LogEnum.SYS_ERR, "restTemplate bean instance error, exception is :【{}】", e); + } + this.restTemplate = template; + } + + public RestTemplate getRestTemplate(){ + return this.restTemplate; + } + + +} diff --git a/dubhe-server/common-cloud/remote-call/src/main/java/org/dubhe/cloud/remotecall/interceptor/FeignInterceptor.java b/dubhe-server/common-cloud/remote-call/src/main/java/org/dubhe/cloud/remotecall/interceptor/FeignInterceptor.java new file mode 100644 index 0000000..07c7e74 --- /dev/null +++ b/dubhe-server/common-cloud/remote-call/src/main/java/org/dubhe/cloud/remotecall/interceptor/FeignInterceptor.java @@ -0,0 +1,50 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.cloud.remotecall.interceptor; + +import feign.RequestInterceptor; +import feign.RequestTemplate; +import org.dubhe.cloud.remotecall.config.RemoteCallConfig; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import javax.servlet.http.HttpServletRequest; + +/** + * @description Feign请求拦截器 + * @date 2020-11-19 + */ +@Configuration +public class FeignInterceptor implements RequestInterceptor { + + /** + * 拦截feign请求,传递token + * @param requestTemplate + */ + @Override + public void apply(RequestTemplate requestTemplate) { + if (RequestContextHolder.getRequestAttributes() == null){ + return; + } + ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); + HttpServletRequest request = attributes.getRequest(); + RemoteCallConfig.TOKEN_LIST.forEach(token -> { + requestTemplate.header(token, request.getHeader(token)); + }); + } +} diff --git a/dubhe-server/common-cloud/remote-call/src/main/java/org/dubhe/cloud/remotecall/interceptor/RestTemplateTokenInterceptor.java b/dubhe-server/common-cloud/remote-call/src/main/java/org/dubhe/cloud/remotecall/interceptor/RestTemplateTokenInterceptor.java new file mode 100644 index 0000000..dda819c --- /dev/null +++ b/dubhe-server/common-cloud/remote-call/src/main/java/org/dubhe/cloud/remotecall/interceptor/RestTemplateTokenInterceptor.java @@ -0,0 +1,97 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.cloud.remotecall.interceptor; + +import org.dubhe.biz.base.constant.AuthConst; +import org.dubhe.cloud.remotecall.config.RemoteCallConfig; +import org.springframework.http.HttpRequest; +import org.springframework.http.client.ClientHttpRequestExecution; +import org.springframework.http.client.ClientHttpRequestInterceptor; +import org.springframework.http.client.ClientHttpResponse; +import org.springframework.util.CollectionUtils; +import org.springframework.web.context.request.RequestAttributes; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; +import java.util.List; + +/** + * @description RestTemplate token拦截处理器 + * @date 2020-11-26 + */ +public class RestTemplateTokenInterceptor implements ClientHttpRequestInterceptor { + + /** + * 对 RestTemplate 的token进行拦截传递 + * @param httpRequest the request, containing method, URI, and headers + * @param body the body of the request + * @param execution the request execution + * @return the response + * @throws IOException in case of I/O errors + */ + @Override + public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] body, ClientHttpRequestExecution execution) throws IOException { + RemoteCallConfig.TOKEN_LIST.forEach(token -> { + if (AuthConst.AUTHORIZATION.equals(token)){ + do4Auth2Token(httpRequest); + }else { + do4DefinedToken(httpRequest,token); + } + }); + return execution.execute(httpRequest, body); + } + + /** + * 处理自定义token传递 + * @param httpRequest the request, containing method, URI, and headers + * @param token token名称 + */ + private void do4DefinedToken(HttpRequest httpRequest,String token) { + List authorizations = httpRequest.getHeaders().get(token); + if (CollectionUtils.isEmpty(authorizations)){ + return; + } + httpRequest.getHeaders().add(token, authorizations.get(0)); + } + + /** + * 处理Auth2授权token传递 + * @param httpRequest the request, containing method, URI, and headers + */ + private void do4Auth2Token(HttpRequest httpRequest) { + RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); + if (requestAttributes == null){ + return; + } + HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest(); + String authToken = request.getHeader(AuthConst.AUTHORIZATION); + String accessToken = request.getParameter(AuthConst.ACCESS_TOKEN); + List authorizations = httpRequest.getHeaders().get(AuthConst.AUTHORIZATION); + String authorization = null; + if (accessToken != null){ + authorization = AuthConst.ACCESS_TOKEN_PREFIX + accessToken; + }else if (authToken != null){ + authorization = authToken; + }else if (authorizations != null){ + authorization = AuthConst.ACCESS_TOKEN_PREFIX + authorizations.get(0); + } + httpRequest.getHeaders().add(AuthConst.AUTHORIZATION, authorization); + } + +} diff --git a/dubhe-server/common-cloud/remote-call/src/main/java/org/dubhe/cloud/remotecall/strategy/RequestAttributeHystrixConcurrencyStrategy.java b/dubhe-server/common-cloud/remote-call/src/main/java/org/dubhe/cloud/remotecall/strategy/RequestAttributeHystrixConcurrencyStrategy.java new file mode 100644 index 0000000..da23ba8 --- /dev/null +++ b/dubhe-server/common-cloud/remote-call/src/main/java/org/dubhe/cloud/remotecall/strategy/RequestAttributeHystrixConcurrencyStrategy.java @@ -0,0 +1,141 @@ +/* + * Copyright 2013-2019 the original author or authors. + * + * Licensed 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 + * + * https://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 org.dubhe.cloud.remotecall.strategy; + +import com.netflix.hystrix.HystrixThreadPoolKey; +import com.netflix.hystrix.HystrixThreadPoolProperties; +import com.netflix.hystrix.strategy.HystrixPlugins; +import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy; +import com.netflix.hystrix.strategy.concurrency.HystrixRequestVariable; +import com.netflix.hystrix.strategy.concurrency.HystrixRequestVariableLifecycle; +import com.netflix.hystrix.strategy.eventnotifier.HystrixEventNotifier; +import com.netflix.hystrix.strategy.executionhook.HystrixCommandExecutionHook; +import com.netflix.hystrix.strategy.metrics.HystrixMetricsPublisher; +import com.netflix.hystrix.strategy.properties.HystrixPropertiesStrategy; +import com.netflix.hystrix.strategy.properties.HystrixProperty; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; +import org.springframework.web.context.request.RequestAttributes; +import org.springframework.web.context.request.RequestContextHolder; + +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.Callable; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +/** + * @description 重写Hystrix参数传递并发处理战略,保证授权token传递 + * 参考 org.springframework.cloud.sleuth.instrument.hystrix.SleuthHystrixConcurrencyStrategy + * @date 2020-11-26 + */ +@Slf4j +@Component +public class RequestAttributeHystrixConcurrencyStrategy extends HystrixConcurrencyStrategy { + + private HystrixConcurrencyStrategy delegate; + + public RequestAttributeHystrixConcurrencyStrategy() { + this.delegate = HystrixPlugins.getInstance().getConcurrencyStrategy(); + if (this.delegate instanceof RequestAttributeHystrixConcurrencyStrategy) { + return; + } + HystrixCommandExecutionHook commandExecutionHook = HystrixPlugins + .getInstance().getCommandExecutionHook(); + HystrixEventNotifier eventNotifier = HystrixPlugins.getInstance() + .getEventNotifier(); + HystrixMetricsPublisher metricsPublisher = HystrixPlugins.getInstance() + .getMetricsPublisher(); + HystrixPropertiesStrategy propertiesStrategy = HystrixPlugins.getInstance() + .getPropertiesStrategy(); + this.logCurrentStateOfHystrixPlugins(eventNotifier, metricsPublisher, + propertiesStrategy); + HystrixPlugins.reset(); + HystrixPlugins.getInstance().registerConcurrencyStrategy(this); + HystrixPlugins.getInstance() + .registerCommandExecutionHook(commandExecutionHook); + HystrixPlugins.getInstance().registerEventNotifier(eventNotifier); + HystrixPlugins.getInstance().registerMetricsPublisher(metricsPublisher); + HystrixPlugins.getInstance().registerPropertiesStrategy(propertiesStrategy); + } + + private void logCurrentStateOfHystrixPlugins(HystrixEventNotifier eventNotifier, + HystrixMetricsPublisher metricsPublisher, + HystrixPropertiesStrategy propertiesStrategy) { + if (log.isDebugEnabled()) { + log.debug("Current Hystrix plugins configuration is [" + + "concurrencyStrategy [" + this.delegate + "]," + "eventNotifier [" + + eventNotifier + "]," + "metricPublisher [" + metricsPublisher + "]," + + "propertiesStrategy [" + propertiesStrategy + "]," + "]"); + log.debug("Registering Sleuth Hystrix Concurrency Strategy."); + } + } + + @Override + public Callable wrapCallable(Callable callable) { + RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); + return new WrappedCallable<>(callable, requestAttributes); + } + + static class WrappedCallable implements Callable { + + private final Callable target; + // 基于成员变量,手动传递RequestContextHolder.getRequestAttributes(); + private final RequestAttributes requestAttributes; + + public WrappedCallable(Callable target, RequestAttributes requestAttributes) { + this.target = target; + this.requestAttributes = requestAttributes; + } + + @Override + public T call() throws Exception { + try { + RequestContextHolder.setRequestAttributes(requestAttributes); + return target.call(); + }finally { + RequestContextHolder.resetRequestAttributes(); + } + } + } + + @Override + public ThreadPoolExecutor getThreadPool(HystrixThreadPoolKey threadPoolKey, + HystrixProperty corePoolSize, + HystrixProperty maximumPoolSize, + HystrixProperty keepAliveTime, TimeUnit unit, + BlockingQueue workQueue) { + return this.delegate.getThreadPool(threadPoolKey, corePoolSize, maximumPoolSize, + keepAliveTime, unit, workQueue); + } + + @Override + public ThreadPoolExecutor getThreadPool(HystrixThreadPoolKey threadPoolKey, + HystrixThreadPoolProperties threadPoolProperties) { + return this.delegate.getThreadPool(threadPoolKey, threadPoolProperties); + } + + @Override + public BlockingQueue getBlockingQueue(int maxQueueSize) { + return this.delegate.getBlockingQueue(maxQueueSize); + } + + @Override + public HystrixRequestVariable getRequestVariable( + HystrixRequestVariableLifecycle rv) { + return this.delegate.getRequestVariable(rv); + } +} diff --git a/dubhe-server/common-cloud/swagger/pom.xml b/dubhe-server/common-cloud/swagger/pom.xml new file mode 100644 index 0000000..667949a --- /dev/null +++ b/dubhe-server/common-cloud/swagger/pom.xml @@ -0,0 +1,48 @@ + + + 4.0.0 + + org.dubhe.cloud + common-cloud + 0.0.1-SNAPSHOT + + swagger + 0.0.1-SNAPSHOT + Cloud swagger + Swagger for Spring Cloud + + + + + org.dubhe.biz + base + ${org.dubhe.biz.base.version} + + + + io.springfox + springfox-swagger2 + ${swagger.version} + + + com.github.xiaoymin + swagger-bootstrap-ui + ${swagger-bootstrap-ui.version} + + + org.springframework.boot + spring-boot-starter-webflux + + + org.springframework + spring-webmvc + + + + + + + + + diff --git a/dubhe-server/common-cloud/swagger/src/main/java/org/dubhe/cloud/swagger/config/SwaggerConfig.java b/dubhe-server/common-cloud/swagger/src/main/java/org/dubhe/cloud/swagger/config/SwaggerConfig.java new file mode 100644 index 0000000..fda245b --- /dev/null +++ b/dubhe-server/common-cloud/swagger/src/main/java/org/dubhe/cloud/swagger/config/SwaggerConfig.java @@ -0,0 +1,134 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.cloud.swagger.config; + +import com.fasterxml.classmate.TypeResolver; +import com.google.common.base.Predicates; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import org.dubhe.biz.base.constant.AuthConst; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.Ordered; +import org.springframework.data.domain.Pageable; +import springfox.documentation.builders.ApiInfoBuilder; +import springfox.documentation.builders.ParameterBuilder; +import springfox.documentation.builders.PathSelectors; +import springfox.documentation.schema.AlternateTypeRule; +import springfox.documentation.schema.AlternateTypeRuleConvention; +import springfox.documentation.schema.ModelRef; +import springfox.documentation.service.ApiInfo; +import springfox.documentation.service.Parameter; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; +import springfox.documentation.swagger2.annotations.EnableSwagger2; + +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import static com.google.common.collect.Lists.newArrayList; +import static springfox.documentation.schema.AlternateTypeRules.newRule; + +/** + * @description api页面 /swagger-ui.html + * @date 2020-03-25 + */ +@Configuration +@EnableSwagger2 +public class SwaggerConfig { + + /** + * 默认开启,如需要关闭,再对应模块自行关闭 + */ + @Value("${swagger.enabled:true}") + private Boolean enabled; + + @Value("${spring.application.name}") + private String applicationName; + + + @Bean + @SuppressWarnings("all") + public Docket createRestApi() { + List pars = new ArrayList<>(); + pars.add(new ParameterBuilder() + .name(AuthConst.AUTHORIZATION) + .description("令牌") + .modelRef( + new ModelRef("string") + ) + .parameterType("header") + .required(false) + .build() + ); + return new Docket(DocumentationType.SWAGGER_2) + .enable(enabled) + .apiInfo(apiInfo()) + .select() + .paths(Predicates.not(PathSelectors.regex("/error.*"))) + .build().directModelSubstitute(Timestamp.class, Date.class) + .globalOperationParameters(pars); + } + + private ApiInfo apiInfo() { + return new ApiInfoBuilder() + .title(applicationName) + .version("1.0") + .build(); + } + +} + +/** + * 将Pageable转换展示在swagger中 + */ +@Configuration +class SwaggerDataConfig { + + @Bean + public AlternateTypeRuleConvention pageableConvention(final TypeResolver resolver) { + return new AlternateTypeRuleConvention() { + @Override + public int getOrder() { + return Ordered.HIGHEST_PRECEDENCE; + } + + @Override + public List rules() { + return newArrayList(newRule(resolver.resolve(Pageable.class), resolver.resolve(Page.class))); + } + }; + } + + @ApiModel + @Data + private static class Page { + @ApiModelProperty("页码 (0..N)") + private Integer page; + + @ApiModelProperty("每页显示的数目") + private Integer size; + + @ApiModelProperty("以下列格式排序标准:property[,asc | desc]。 默认排序顺序为升序。 支持多种排序条件:如:id,asc") + private List sort; + } +} diff --git a/dubhe-server/common-cloud/unit-test/pom.xml b/dubhe-server/common-cloud/unit-test/pom.xml new file mode 100644 index 0000000..d595b5a --- /dev/null +++ b/dubhe-server/common-cloud/unit-test/pom.xml @@ -0,0 +1,59 @@ + + + + org.dubhe.cloud + common-cloud + 0.0.1-SNAPSHOT + + 4.0.0 + + unit-test + 0.0.1-SNAPSHOT + unit-test 单元测试 + unit-test for Spring Cloud + + + org.springframework.boot + spring-boot-starter-test + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.cloud + spring-cloud-context + + + + org.dubhe.biz + base + ${org.dubhe.biz.base.version} + + + + org.dubhe.biz + data-response + ${org.dubhe.biz.data-response.version} + + + + org.dubhe.cloud + auth-config + ${org.dubhe.cloud.auth-config.version} + + + + org.dubhe.cloud + remote-call + ${org.dubhe.cloud.remote-call.version} + + + + + + + + \ No newline at end of file diff --git a/dubhe-server/common-cloud/unit-test/src/main/java/org/dubhe/cloud/unittest/base/BaseTest.java b/dubhe-server/common-cloud/unit-test/src/main/java/org/dubhe/cloud/unittest/base/BaseTest.java new file mode 100644 index 0000000..41786a9 --- /dev/null +++ b/dubhe-server/common-cloud/unit-test/src/main/java/org/dubhe/cloud/unittest/base/BaseTest.java @@ -0,0 +1,165 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.cloud.unittest.base; + +import cn.hutool.http.HttpStatus; +import org.dubhe.biz.base.constant.ApplicationNameConst; +import org.dubhe.biz.base.constant.AuthConst; +import org.dubhe.cloud.unittest.config.UnitTestConfig; +import org.dubhe.biz.base.vo.DataResponseBody; +import org.junit.Assert; +import org.junit.Before; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.security.web.FilterChainProxy; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.ResultMatcher; +import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.transaction.annotation.EnableTransactionManagement; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestTemplate; +import org.springframework.web.context.WebApplicationContext; + +import java.io.UnsupportedEncodingException; +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * @description 基础测试类 + * @date 2020-04-20 + */ +@ActiveProfiles(value = "dev") +@RunWith(SpringRunner.class) +@SpringBootTest +@EnableTransactionManagement +@WebAppConfiguration +public class BaseTest { + + @Autowired + private WebApplicationContext wac; + + @Autowired + private FilterChainProxy springSecurityFilterChain; + + protected MockMvc mockMvc; + + @Autowired + private RestTemplate restTemplate; + + @Autowired + private UnitTestConfig unitTestConfig; + + public BaseTest() { + } + + /** + * 初始化MockMvc对象,添加Security过滤器链 + */ + @Before + public void setup() { + this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).addFilter(springSecurityFilterChain).build(); + } + + /** + * mockMvcTest + * content 返回结果 + * status 返回状态码 + * + * @param mockHttpServletRequestBuilder 模拟HTTP请求 + * @param s 传入参数 + * @param ok 预期结果 + * @param i 预期状态码 + * @throws throws Exception + */ + public void mockMvcTest(MockHttpServletRequestBuilder mockHttpServletRequestBuilder, String s, ResultMatcher ok, int i) throws Exception { + String accessToken = obtainAccessToken(); + MockHttpServletResponse response = this.mockMvc.perform( + mockHttpServletRequestBuilder + .contentType(MediaType.APPLICATION_JSON) + .content(s).header(AuthConst.AUTHORIZATION, AuthConst.ACCESS_TOKEN_PREFIX + accessToken) + ).andExpect(ok) + .andReturn() + .getResponse(); + response.setCharacterEncoding("UTF-8"); + //得到返回状态码 + int status = response.getStatus(); + //得到返回结果 + String content = response.getContentAsString(); + //断言,判断返回代码是否正确 + Assert.assertEquals(i, status); + System.out.println(content); + } + + /** + * @param response 响应结果 + * @param i 响应码 + * @param @throws UnsupportedEncodingException 入参 + * @return void 返回类型 + * @throws @Title: mockMvcWithNoRequestBody + */ + public void mockMvcWithNoRequestBody(MockHttpServletResponse response, int i) throws UnsupportedEncodingException { + response.setCharacterEncoding("UTF-8"); + // 得到返回代码 + int status = response.getStatus(); + // 得到返回结果 + String content = response.getContentAsString(); + // 断言,判断返回代码是否正确 + Assert.assertEquals(i, status); + System.out.println("返回的参数" + content); + } + + /** + * 模拟登录获取token + * @return String token + */ + public String obtainAccessToken() { + MultiValueMap params = new LinkedMultiValueMap<>(); + params.add("grant_type", AuthConst.GRANT_TYPE); + params.add("client_id", AuthConst.CLIENT_ID); + params.add("client_secret", AuthConst.CLIENT_SECRET); + params.add("username", unitTestConfig.getUsername()); + params.add("password", unitTestConfig.getPassword()); + params.add("scope", "all"); + HttpHeaders headers = new HttpHeaders(); + // 需求需要传参为application/x-www-form-urlencoded格式 + headers.setContentType(MediaType.valueOf(MediaType.APPLICATION_FORM_URLENCODED_VALUE)); + HttpEntity> httpEntity = new HttpEntity<>(params, headers); + ResponseEntity responseEntity = restTemplate.postForEntity("http://" + ApplicationNameConst.SERVER_AUTHORIZATION + "/oauth/token", httpEntity, DataResponseBody.class); + if (HttpStatus.HTTP_OK != responseEntity.getStatusCodeValue()) { + return null; + } + DataResponseBody restResult = responseEntity.getBody(); + Map map = new LinkedHashMap(); + if (restResult.succeed()) { + map = (Map) restResult.getData(); + } + // 返回 token + return (String) map.get("token"); + } +} diff --git a/dubhe-server/common-cloud/unit-test/src/main/java/org/dubhe/cloud/unittest/config/UnitTestConfig.java b/dubhe-server/common-cloud/unit-test/src/main/java/org/dubhe/cloud/unittest/config/UnitTestConfig.java new file mode 100644 index 0000000..7702caa --- /dev/null +++ b/dubhe-server/common-cloud/unit-test/src/main/java/org/dubhe/cloud/unittest/config/UnitTestConfig.java @@ -0,0 +1,38 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.cloud.unittest.config; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.cloud.context.config.annotation.RefreshScope; +import org.springframework.stereotype.Component; + +/** + * @description 配置dev环境单元测试用户名与密码 + * @date 2021-01-11 + */ +@Data +@Component +@ConfigurationProperties(prefix = "unittest") +@RefreshScope +public class UnitTestConfig { + + private String username; + + private String password; + +} \ No newline at end of file diff --git a/dubhe-server/common-k8s/.gitignore b/dubhe-server/common-k8s/.gitignore new file mode 100644 index 0000000..3efc846 --- /dev/null +++ b/dubhe-server/common-k8s/.gitignore @@ -0,0 +1 @@ +!common-k8s/src/main/resources/kubeconfig diff --git a/dubhe-server/common-k8s/pom.xml b/dubhe-server/common-k8s/pom.xml new file mode 100644 index 0000000..5d49fe1 --- /dev/null +++ b/dubhe-server/common-k8s/pom.xml @@ -0,0 +1,92 @@ + + + 4.0.0 + + org.dubhe + server + 0.0.1-SNAPSHOT + + common-k8s + 0.0.1-SNAPSHOT + k8s 通用模块 + Dubhe K8s Common + + + + + org.dubhe.biz + file + ${org.dubhe.biz.file.version} + + + org.dubhe.biz + redis + ${org.dubhe.biz.redis.version} + + + org.dubhe.biz + db + ${org.dubhe.biz.db.version} + + + + org.dubhe.cloud + swagger + ${org.dubhe.cloud.swagger.version} + + + + org.springframework.boot + spring-boot-starter-web + + + + + io.fabric8 + kubernetes-client + ${fabric.io.version} + + + + + com.google.code.gson + gson + + + org.elasticsearch.client + elasticsearch-rest-high-level-client + + + org.elasticsearch + elasticsearch + + + + jakarta.validation + jakarta.validation-api + + + org.dubhe.biz + data-permission + 0.0.1-SNAPSHOT + compile + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + true + src/main/resources + + + + + diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/harbor/api/HarborApi.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/harbor/api/HarborApi.java new file mode 100644 index 0000000..2491c6b --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/harbor/api/HarborApi.java @@ -0,0 +1,70 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.harbor.api; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.dubhe.harbor.domain.vo.ImageVO; +import java.util.List; +import java.util.Map; + +/** + * @description HarborApi接口 + * @date 2020-07-01 + */ +public interface HarborApi { + /** + * 通过ProjectName名称查询镜像名称 + * + * @param projectNameList 项目名称集合 + * @return List 镜像名称集合 + */ + List searchImageNames(List projectNameList); + /** + * 通过projectM名称查询镜像名称 + * + * @param projectNameList 项目名称集合 + * @return List 镜像结果集 + */ + List searchImageByProjects(List projectNameList); + + /** + * 根据完整镜像路径查询判断是否具有镜像 + * + * @param imageUrl 镜像路径 + * @return Boolean true 存在 false 不存在 + */ + Boolean isExistImage(String imageUrl); + /** + * 查询所有镜像名称不用根据ProjectName进行查询 + * + * @return List 镜像结果集 + **/ + List findImageList(); + /** + * 分页查询(镜像) + * + * @param page 分页对象 + * @return ImageVO 镜像vo对象 + **/ + ImageVO findImagePage(Page page); + /** + * 删除镜像 + * + * @param imageUrl 镜像的完整路径 + */ + void deleteImageByTag(String imageUrl); + +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/harbor/api/impl/HarborApiImpl.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/harbor/api/impl/HarborApiImpl.java new file mode 100644 index 0000000..d3b6824 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/harbor/api/impl/HarborApiImpl.java @@ -0,0 +1,312 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.harbor.api.impl; + + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.dubhe.biz.base.constant.MagicNumConstant; +import org.dubhe.biz.base.constant.SymbolConstant; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.harbor.api.HarborApi; +import org.dubhe.harbor.domain.vo.ImagePageVO; +import org.dubhe.harbor.domain.vo.ImageVO; +import org.dubhe.harbor.utils.HttpClientUtils; +import org.dubhe.biz.log.utils.LogUtil; +import org.dubhe.biz.base.utils.StringUtils; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.util.CollectionUtils; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +import static org.dubhe.biz.base.constant.SymbolConstant.COLON; + +/** + * @description HarborApi接口实现类 + * @date 2020-05-21 + */ +public class HarborApiImpl implements HarborApi { + + @Value("https://${harbor.address}/api/repositories?project_id=") + private String imageSearchUrl; + @Value("${harbor.address}/") + private String imagePullUrl; + @Value("https://${harbor.address}/api/projects") + private String projectSearchUrl; + @Value("https://${harbor.address}/api/repositories/") + private String tagSearchUrl; + @Value("${harbor.username}") + private String harborName; + @Value("${harbor.password}") + private String harborPassword; + private static final String TAG_SEARCH_CONF = "/%2F"; + private static final String TAG_SEARCH_PARAMS = "/tags"; + private static final String RESOURCE_NAME_KEY = "name"; + private static final String PROJECT_ID_KEY = "project_id"; + private static final String CREATION_TIME = "creation_time"; + private static final String UPDATE_TIME = "update_time"; + private static final String CPL_IMAGE_NAMES = "cplImageName"; + + /** + * 通过ProjectName名称查询镜像名称 + * + * @param projectNameList 项目名称集合 + * @return List 镜像名称集合 + */ + @Override + public List searchImageNames(List projectNameList) { + List imageNames = new ArrayList<>(MagicNumConstant.TEN); + List imageInfoList = searchImageByProjects(projectNameList); + if (CollectionUtils.isEmpty(projectNameList) || CollectionUtils.isEmpty(imageInfoList)) { + return imageNames; + } + imageInfoList.forEach(imageInfo -> imageNames.add((String) imageInfo.get(CPL_IMAGE_NAMES))); + return imageNames; + } + + /** + * 通过projectM名称查询镜像名称 + * + * @param projectNameList 镜像名称 + * @return List 镜像结果集合 + */ + @Override + public List searchImageByProjects(List projectNameList) { + /**创建镜像名称List**/ + List imageInfoList = new ArrayList<>(MagicNumConstant.TEN); + /**处理数据非空判断**/ + if (CollectionUtils.isEmpty(projectNameList)) { + return imageInfoList; + } + /**获取projectName-projectId映射Map**/ + Map project = getProjectIdMap(); + projectNameList.parallelStream().forEach(projectName -> { + /**根据projectName获取projectId**/ + Integer projectId = project.get(projectName); + if (projectId != null) { + /**调用Harbor提供的http接口,传入projectId获取Json格式的repository 信息**/ + String repoJson = HttpClientUtils.sendHttps(imageSearchUrl + projectId); + /**解析repoJson**/ + JSONArray repoArray = JSON.parseArray(repoJson); + repoArray.stream().forEach(repo -> { + /**获取repoName**/ + Map repoDetailMap = (Map) repo; + String repoName = repoDetailMap.get(RESOURCE_NAME_KEY); + /**获取imageName**/ + String imageName = repoName.substring(projectName.length() + MagicNumConstant.ONE); + /**调用getImageTagNames方法获取镜像的tag**/ + List imageTagNames = getImageTagNameList(projectName, imageName); + /**获取creation_time**/ + String creationTime = repoDetailMap.get(CREATION_TIME); + /**获取update_time**/ + String updateTime = repoDetailMap.get(UPDATE_TIME); + imageTagNames.stream().forEach(imageTagName -> { + Map imageMap = new HashMap(MagicNumConstant.SIXTEEN); + imageMap.put("imageName", imageName); + imageMap.put("cplImageName", imagePullUrl + repoName + COLON + imageTagName); + imageMap.put("tag", imageTagName); + imageMap.put("creationTime", creationTime); + imageMap.put("updateTime", updateTime); + imageInfoList.add(imageMap); + }); + }); + } else { + LogUtil.error(LogEnum.BIZ_K8S, "The number information corresponding to the project name was not found {}", projectNameList); + } + }); + return imageInfoList; + } + + /** + * 获取projectName-projectId映射Map + * + * @return Map 项目名称和项目id映射map + */ + private Map getProjectIdMap() { + Map projectIdMap = new HashMap<>(MagicNumConstant.SIXTEEN); + /**调用Harbor提供的http接口,获取Json格式的project信息**/ + String projectJson = HttpClientUtils.sendHttps(projectSearchUrl); + /**解析projectArray**/ + JSONArray projectArray = JSON.parseArray(projectJson); + List jsonArrays = Arrays.asList(projectArray); + if (CollectionUtils.isEmpty(jsonArrays)) { + return projectIdMap; + } + JSONArray projects = jsonArrays.get(0); + /**将对象转换为Map集合**/ + projects.stream().forEach(project -> { + Map projectDetailMap = (Map) project; + /**得到projectName**/ + String projectName = (String) projectDetailMap.get(RESOURCE_NAME_KEY); + /**得到projectID**/ + Integer projectId = (Integer) projectDetailMap.get(PROJECT_ID_KEY); + projectIdMap.put(projectName, projectId); + }); + return projectIdMap; + } + + + /** + * 查询镜像Tag名称方法 + * + * @param projectName 项目名称 + * @param imageName 镜像名称 + * @return List 镜像标签集合名称 + */ + private List getImageTagNameList(String projectName, String imageName) { + List tagNames = new ArrayList<>(MagicNumConstant.TEN); + /***非空校验*/ + if (StringUtils.isBlank(projectName)) { + return tagNames; + } + if (StringUtils.isBlank(imageName)) { + return tagNames; + } + /**调用Harbor提供的http接口,获取Json格式的Tag信息**/ + String imageTagsJson = HttpClientUtils.sendHttps(tagSearchUrl + projectName + TAG_SEARCH_CONF + imageName + TAG_SEARCH_PARAMS); + if (StringUtils.isBlank(imageTagsJson)) { + return tagNames; + } + + /***解析imageTagsJson*/ + JSONArray tagsArray = JSON.parseArray(imageTagsJson); + /**遍历数据并且转换为map类型**/ + tagsArray.stream().forEach(tag -> { + /**获取tagName**/ + Map tagDetailMap = (Map) tag; + String tagName = tagDetailMap.get(RESOURCE_NAME_KEY); + tagNames.add(tagName); + }); + + return tagNames; + } + + + /** + * 根据完整镜像路径查询判断是否具有镜像 + * + * @param imageUrl 镜像路径 + * @return Boolean true 存在 false 不存在 + */ + @Override + public Boolean isExistImage(String imageUrl) { + if (StringUtils.isBlank(imageUrl)) { + LogUtil.info(LogEnum.BIZ_K8S, "The image path is empty", imageUrl); + return false; + } + /**将imageName(含版本号)分割出来**/ + String[] urlSplit = imageUrl.split(SymbolConstant.SLASH); + String imageName = urlSplit[MagicNumConstant.TWO]; + /**获取该项目下所有镜像名称**/ + List imageInfoList = searchImageByProjects(Arrays.asList(urlSplit[MagicNumConstant.ONE])); + /**创建集合存储该项目下面的所有的镜像**/ + List imageList = new ArrayList<>(MagicNumConstant.TEN); + /**根据ProjectName和image将版本号查询出来**/ + try { + if (!CollectionUtils.isEmpty(imageInfoList)) { + imageInfoList.stream().forEach(name -> { + /**将该项目下面的所有镜像存储进来**/ + imageList.add(((String) name.get(CPL_IMAGE_NAMES)).split(SymbolConstant.SLASH)[MagicNumConstant.TWO]); + }); + } + } catch (Exception e) { + LogUtil.error(LogEnum.BIZ_K8S, "error path:{}", imageUrl); + } + + return imageList.contains(imageName); + } + + /** + * 查询所有镜像名称不用根据ProjectName进行查询 + * + * @param + * @return List 镜像结果集 + **/ + @Override + public List findImageList() { + /**查询所有项目名称**/ + Map projectIdMap = getProjectIdMap(); + /**创建集合将项目名添加进去**/ + List projects = new ArrayList<>(projectIdMap.keySet()); + return searchImageByProjects(projects); + } + + /** + * 分页查询(镜像) + * + * @param page 分页对象 + * @return ImageVO 镜像vo对象 + **/ + @Override + public ImageVO findImagePage(Page page) { + /**查询所有项目名称**/ + Map projectIdMap = getProjectIdMap(); + /**创建集合将项目名添加进去**/ + List projects = new ArrayList<>(projectIdMap.keySet()); + List imageList = searchImageByProjects(projects); + ImageVO imageVO = new ImageVO(); + if (CollectionUtils.isEmpty(imageList)) { + List imagesData = imageList.stream().skip((page.getCurrent() - MagicNumConstant.ONE) * page.getSize()).limit(page.getSize()).collect(Collectors.toList()); + imageVO.setResult(imagesData); + ImagePageVO imagePageVO = new ImagePageVO(); + /**获取当前页**/ + imagePageVO.setCurrent(page.getCurrent()); + /**获取每页显示都数据**/ + imagePageVO.setSize(page.getSize()); + /**获取总记录数**/ + imagePageVO.setTotal(imageList.size()); + imageVO.setPage(imagePageVO); + } + return imageVO; + } + + /** + * 根据镜像标签删除镜像 + * + * @param imageUrl + */ + @Override + public void deleteImageByTag(String imageUrl) { + if(StringUtils.isNotEmpty(imageUrl)){ + LogUtil.info(LogEnum.BIZ_K8S,"image path{}",imageUrl); + String[] urlSplits = imageUrl.split(SymbolConstant.SLASH); + String[] tagUrls = urlSplits[MagicNumConstant.TWO].split(SymbolConstant.COLON); + String dataRep=urlSplits[MagicNumConstant.ONE]+SymbolConstant.SLASH+tagUrls[MagicNumConstant.ZERO]; + LogUtil.info(LogEnum.BIZ_K8S,"data warehouse{}",dataRep); + Map projectIdMap = getProjectIdMap(); + //获取harbor中所有项目的名称 + Set names = projectIdMap.keySet(); + //判断harbor中是否具有改项目 + names.forEach(name->{ + if(urlSplits[MagicNumConstant.ONE].equals(name)){ + //发送删除请求 + HttpClientUtils.sendHttpsDelete(tagSearchUrl+dataRep+TAG_SEARCH_PARAMS+SymbolConstant.SLASH+tagUrls[MagicNumConstant.ONE],harborName,harborPassword); + LogUtil.error(LogEnum.BIZ_K8S,"fail to delete{}",imageUrl); + return; + } + }); + } + } + +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/harbor/config/HarborConfig.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/harbor/config/HarborConfig.java new file mode 100644 index 0000000..28c33af --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/harbor/config/HarborConfig.java @@ -0,0 +1,35 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.harbor.config; +import org.dubhe.harbor.api.impl.HarborApiImpl; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * @description Harbor spring bean 配置类 + * @date 2020-05-02 + */ + +@Configuration +public class HarborConfig { + @Bean + public HarborApiImpl harborApi(){ + return new HarborApiImpl(); + } + +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/harbor/domain/vo/ImagePageVO.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/harbor/domain/vo/ImagePageVO.java new file mode 100644 index 0000000..18cf895 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/harbor/domain/vo/ImagePageVO.java @@ -0,0 +1,35 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.harbor.domain.vo; + +import lombok.Data; + +import java.io.Serializable; + +/** + * @description 镜像结果集 + * @date 2020-06-04 + */ +@Data +public class ImagePageVO implements Serializable { + private static final long serialVersionUID = 1L; + private Integer total; + private Long size; + private Long current; + +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/harbor/domain/vo/ImageVO.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/harbor/domain/vo/ImageVO.java new file mode 100644 index 0000000..d31565c --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/harbor/domain/vo/ImageVO.java @@ -0,0 +1,37 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.harbor.domain.vo; + +import lombok.Data; + + +import java.io.Serializable; +import java.util.List; + +/** + * @description 转换对象 + * @date 2020-06-04 + */ +@Data +public class ImageVO implements Serializable { + private static final long serialVersionUID = 1L; + private List result; + private ImagePageVO page; + + +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/harbor/utils/HttpClientUtils.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/harbor/utils/HttpClientUtils.java new file mode 100644 index 0000000..22ddfe3 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/harbor/utils/HttpClientUtils.java @@ -0,0 +1,169 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.harbor.utils; +import org.apache.commons.io.IOUtils; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; + + +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSocketFactory; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; +import java.io.BufferedReader; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URL; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import org.apache.commons.codec.binary.Base64; +import static org.dubhe.biz.base.constant.StringConstant.UTF8; +import static org.dubhe.biz.base.constant.SymbolConstant.BLANK; + +/** + * @description httpClient工具类,不校验SSL证书 + * @date 2020-05-21 + */ +public class HttpClientUtils { + + public static String sendHttps(String path) { + InputStream inputStream = null; + BufferedReader bufferedReader = null; + InputStreamReader inputStreamReader = null; + StringBuilder stringBuilder = new StringBuilder(); + String result = BLANK; + HttpsURLConnection con = null; + try { + con = getConnection(path); + con.connect(); + + /**将返回的输入流转换成字符串**/ + inputStream = con.getInputStream(); + inputStreamReader = new InputStreamReader(inputStream, UTF8); + bufferedReader = new BufferedReader(inputStreamReader); + + String str = null; + while ((str = bufferedReader.readLine()) != null) { + stringBuilder.append(str); + } + + result = stringBuilder.toString(); + LogUtil.info(LogEnum.BIZ_SYS,"Request path:{}, SUCCESS, result:{}", path, result); + + } catch (Exception e) { + LogUtil.error(LogEnum.BIZ_SYS,"Request path:{}, ERROR, exception:{}", path, e); + return result; + } finally { + closeResource(bufferedReader,inputStreamReader,inputStream,con); + } + + return result; + } + public static String sendHttpsDelete(String path,String username,String password) { + InputStream inputStream = null; + BufferedReader bufferedReader = null; + InputStreamReader inputStreamReader = null; + StringBuilder stringBuilder = new StringBuilder(); + String result = BLANK; + HttpsURLConnection con = null; + try { + con = getConnection(path); + String input =username+ ":" +password; + String encoding=Base64.encodeBase64String(input.getBytes()); + con.setRequestProperty("Authorization", "Basic " + encoding); + con.setRequestMethod("DELETE"); + con.connect(); + /**将返回的输入流转换成字符串**/ + inputStream = con.getInputStream(); + inputStreamReader = new InputStreamReader(inputStream, UTF8); + bufferedReader = new BufferedReader(inputStreamReader); + + String str = null; + while ((str = bufferedReader.readLine()) != null) { + stringBuilder.append(str); + } + + result = stringBuilder.toString(); + LogUtil.info(LogEnum.BIZ_SYS,"Request path:{}, SUCCESS, result:{}", path, result); + + } catch (Exception e) { + LogUtil.error(LogEnum.BIZ_SYS,"Request path:{}, ERROR, exception:{}", path, e); + return result; + } finally { + closeResource(bufferedReader,inputStreamReader,inputStream,con); + } + + return result; + } + + private static void closeResource(BufferedReader bufferedReader,InputStreamReader inputStreamReader,InputStream inputStream,HttpsURLConnection con) { + if (inputStream != null) { + IOUtils.closeQuietly(inputStream); + } + + if (inputStreamReader != null) { + IOUtils.closeQuietly(inputStreamReader); + } + if (bufferedReader != null) { + IOUtils.closeQuietly(bufferedReader); + } + if (con != null) { + con.disconnect(); + } + } + + + private static HttpsURLConnection getConnection(String path){ + HttpsURLConnection con = null; + try { + /**创建并初始化SSLContext对象**/ + TrustManager[] trustManagers = {new X509TrustManager() { + @Override + public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { + } + + @Override + public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { + } + + @Override + public X509Certificate[] getAcceptedIssuers() { + return null; + } + }}; + SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); + sslContext.init(null, trustManagers, new java.security.SecureRandom()); + + /**得到SSLSocketFactory对象**/ + SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); + + URL url = new URL(path); + con = (HttpsURLConnection) url.openConnection(); + con.setSSLSocketFactory(sslSocketFactory); + con.setUseCaches(false); + }catch (Exception e){ + LogUtil.error(LogEnum.BIZ_SYS,"Request path:{}, error, exception:{}", path, e); + } + return con; + + } + +} + + diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/abstracts/AbstractDeploymentCallback.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/abstracts/AbstractDeploymentCallback.java new file mode 100644 index 0000000..2dd32fe --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/abstracts/AbstractDeploymentCallback.java @@ -0,0 +1,85 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.abstracts; + +import org.dubhe.biz.base.constant.NumberConstant; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.dubhe.k8s.domain.dto.BaseK8sDeploymentCallbackCreateDTO; +import org.dubhe.k8s.service.DeploymentCallbackAsyncService; +import org.dubhe.k8s.utils.K8sCallBackTool; + +import javax.annotation.Resource; + +/** + * @description 公共 deployment回调 + * @date 2020-11-27 + */ +public abstract class AbstractDeploymentCallback implements DeploymentCallbackAsyncService { + + @Resource + private K8sCallBackTool k8sCallBackTool; + + /** + * 公共 失败重试策略 + * + * @param k8sDeploymentCallbackCreateDTO + * @param + */ + @Override + public void deploymentCallBack(R k8sDeploymentCallbackCreateDTO) { + int tryTime = 1; + while (!doCallback(tryTime, k8sDeploymentCallbackCreateDTO)) { + if (k8sCallBackTool.continueRetry(++tryTime)) { + // 继续重试 tryTime重试次数+1 + try { + Thread.sleep(tryTime * NumberConstant.NUMBER_1000); + } catch (InterruptedException e) { + LogUtil.error(LogEnum.NOTE_BOOK, "AbstractDeploymentCallback deploymentCallBack InterruptedException : {}", e); + // Restore interrupted state...       + Thread.currentThread().interrupt(); + } + } else { + // 重试超限 tryTime重试次数+1未尝试,因此需要tryTime重试次数-1 + callbackFailed(--tryTime, k8sDeploymentCallbackCreateDTO); + break; + } + } + } + + + /** + * deployment 异步回调具体实现处理类 + * + * @param times 第n次处理 + * @param k8sDeploymentCallbackCreateDTO k8s回调实体类 + * @param BaseK8sDeploymentCallbackReq k8s回调基类 + * @return true:处理成功 false:处理失败 + */ + public abstract boolean doCallback(int times, R k8sDeploymentCallbackCreateDTO); + + + /** + * deployment 异步回调具体实现处理类 + * + * @param retryTimes 总处理次数 + * @param k8sDeploymentCallbackCreateDTO k8s回调实体类 + * @param BaseK8sDeploymentCallbackReq k8s回调基类 + */ + public abstract void callbackFailed(int retryTimes, R k8sDeploymentCallbackCreateDTO); +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/abstracts/AbstractPodCallback.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/abstracts/AbstractPodCallback.java new file mode 100644 index 0000000..2f022f7 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/abstracts/AbstractPodCallback.java @@ -0,0 +1,83 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.abstracts; + + +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.dubhe.k8s.domain.dto.BaseK8sPodCallbackCreateDTO; +import org.dubhe.k8s.service.PodCallbackAsyncService; +import org.dubhe.k8s.utils.K8sCallBackTool; +import org.springframework.beans.factory.annotation.Autowired; + +/** + * @description pod 异步回调抽象处理类 + * @date 2020-05-29 + */ +public abstract class AbstractPodCallback implements PodCallbackAsyncService { + + @Autowired + private K8sCallBackTool k8sCallBackTool; + + /** + * 公共 失败重试策略 + * + * @param k8sPodCallbackCreateDTO + * @param + */ + @Override + public void podCallBack(R k8sPodCallbackCreateDTO) { + int tryTime = 1; + while (!doCallback(tryTime, k8sPodCallbackCreateDTO)) { + if (k8sCallBackTool.continueRetry(++tryTime)) { + // 继续重试 tryTime重试次数+1 + try { + Thread.sleep(tryTime * 1000); + continue; + } catch (InterruptedException e) { + LogUtil.error(LogEnum.NOTE_BOOK, "AbstractPodCallback podCallBack InterruptedException : {}", e); + // Restore interrupted state...       + Thread.currentThread().interrupt(); + } + } else { + // 重试超限 tryTime重试次数+1未尝试,因此需要tryTime重试次数-1 + callbackFailed(--tryTime, k8sPodCallbackCreateDTO); + break; + } + } + } + + /** + * pod 异步回调具体实现处理类 + * @param times 第n次处理 + * @param k8sPodCallbackCreateDTO k8s回调实体类 + * @param BaseK8sPodCallbackReq k8s回调基类 + * @return true:处理成功 false:处理失败 + */ + public abstract boolean doCallback(int times, R k8sPodCallbackCreateDTO); + + + /** + * pod 异步回调具体实现处理类 + * @param retryTimes 总处理次数 + * @param k8sPodCallbackCreateDTO k8s回调实体类 + * @param BaseK8sPodCallbackReq k8s回调基类 + */ + public abstract void callbackFailed(int retryTimes, R k8sPodCallbackCreateDTO); + +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/annotation/K8sField.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/annotation/K8sField.java new file mode 100644 index 0000000..cfa2615 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/annotation/K8sField.java @@ -0,0 +1,39 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.annotation; + + +import org.dubhe.biz.base.constant.SymbolConstant; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * @description 用于转换fabric pojo的自定义注解 + * @date 2020-04-14 + */ + +@Target(ElementType.FIELD) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface K8sField { + String value() default SymbolConstant.BLANK; +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/annotation/K8sValidation.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/annotation/K8sValidation.java new file mode 100644 index 0000000..c7017f4 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/annotation/K8sValidation.java @@ -0,0 +1,35 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.annotation; + +import org.dubhe.k8s.enums.ValidationTypeEnum; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * @description 用于标记需要校验的字段 + * @date 2020-06-04 + */ +@Target({ElementType.FIELD, ElementType.PARAMETER}) +@Retention(RetentionPolicy.RUNTIME) +public @interface K8sValidation { + ValidationTypeEnum value(); +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/DistributeTrainApi.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/DistributeTrainApi.java new file mode 100644 index 0000000..c4ce7c0 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/DistributeTrainApi.java @@ -0,0 +1,68 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.api; + +import org.dubhe.k8s.domain.PtBaseResult; +import org.dubhe.k8s.domain.bo.DistributeTrainBO; +import org.dubhe.k8s.domain.resource.BizDistributeTrain; + +/** + * @description k8s中资源为DistributeTrain的操作接口 + * @date 2020-07-07 + */ +public interface DistributeTrainApi { + BizDistributeTrain create(DistributeTrainBO bo); + + /** + * 删除 + * + * @param namespace 命名空间 + * @param resourceName 资源名称 + * @return PtBaseResult + */ + PtBaseResult deleteByResourceName(String namespace, String resourceName); + + /** + * 根据namespace和resourceName查询cr信息 + * + * @param namespce 命令空间 + * @param resourceName 资源名称 + * @return BizDistributeTrain 自定义资源转换类集合 + */ + BizDistributeTrain get(String namespce,String resourceName); + /** + * 根据名称查cr + * + * @param crName 自定义资源名称 + * @return BizDistributeTrain 自定义资源类 + */ + BizDistributeTrain findDisByName(String crName); + + /** + * 通过 yaml创建 + * @param crYaml cr定义yaml脚本 + * @return BizDistributeTrain 自定义资源类 + */ + BizDistributeTrain create(String crYaml); + + /** + * 通过 yaml删除 + * @param crYaml cr定义yaml脚本 + * @return boolean true 删除成功 false删除失败 + */ + boolean delete(String crYaml); +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/DubheDeploymentApi.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/DubheDeploymentApi.java new file mode 100644 index 0000000..4f4a0db --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/DubheDeploymentApi.java @@ -0,0 +1,70 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.api; + +import org.dubhe.k8s.domain.PtBaseResult; +import org.dubhe.k8s.domain.bo.PtModelOptimizationDeploymentBO; +import org.dubhe.k8s.domain.resource.BizDeployment; + +import java.util.List; + +/** + * @description k8s中资源为Deployment的操作接口 + * @date 2020-07-03 + */ +public interface DubheDeploymentApi { + /** + * 创建模型压缩Deployment + * + * @param bo 模型压缩 Deployment BO + * @return BizDeployment Deployment 业务类 + */ + BizDeployment create(PtModelOptimizationDeploymentBO bo); + + /** + * 通过命名空间和资源名称查找Deployment资源 + * + * @param namespace 命名空间 + * @param resourceName 资源名称 + * @return BizDeployment Deployment 业务类 + */ + BizDeployment getWithResourceName(String namespace,String resourceName); + + /** + * 通过命名空间查找Deployment资源集合 + * + * @param namespace 命名空间 + * @return List Deployment 业务类集合 + */ + List getWithNamespace(String namespace); + + /** + * 查询集群所有Deployment资源 + * + * @return List Deployment 业务类集合 + */ + List listAll(); + + /** + * 通过资源名进行删除 + * + * @param namespace 命名空间 + * @param resourceName 资源名称 + * @return PtBaseResult 基础结果类 + */ + PtBaseResult deleteByResourceName(String namespace, String resourceName); +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/JupyterResourceApi.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/JupyterResourceApi.java new file mode 100644 index 0000000..230fa43 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/JupyterResourceApi.java @@ -0,0 +1,73 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.api; + +import org.dubhe.k8s.domain.PtBaseResult; +import org.dubhe.k8s.domain.bo.PtJupyterResourceBO; +import org.dubhe.k8s.domain.vo.PtJupyterDeployVO; + +import java.util.List; + +/** + * @description Jupyter Notebook 操作接口 + * @date 2020-07-03 + */ +public interface JupyterResourceApi { + + /** + * 创建Notebook Deployment + * + * @param bo 模型管理 Notebook BO + * @return PtJupyterDeployVO Notebook 结果类 + */ + PtJupyterDeployVO create(PtJupyterResourceBO bo); + + /** + * 创建Notebook Deployment并使用pvc存储 + * + * @param bo 模型管理 Notebook BO + * @return PtJupyterDeployVO Notebook 结果类 + */ + PtJupyterDeployVO createWithPvc(PtJupyterResourceBO bo); + + /** + * 删除Notebook Deployment + * + * @param namespace 命名空间 + * @param resourceName 资源名称 + * @return PtBaseResult 基础结果类 + */ + PtBaseResult delete(String namespace, String resourceName); + + /** + * 查询命名空间下所有Notebook + * + * @param namespace 命名空间 + * @return List Notebook 结果类集合 + */ + List list(String namespace); + + /** + * 查询Notebook + * + * @param namespace 命名空间 + * @param resourceName 资源名称 + * @return PtJupyterDeployVO Notebook 结果类 + */ + PtJupyterDeployVO get(String namespace, String resourceName); +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/LimitRangeApi.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/LimitRangeApi.java new file mode 100644 index 0000000..c62f5f3 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/LimitRangeApi.java @@ -0,0 +1,56 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.api; + +import org.dubhe.k8s.domain.PtBaseResult; +import org.dubhe.k8s.domain.bo.PtLimitRangeBO; +import org.dubhe.k8s.domain.resource.BizLimitRange; + +import java.util.List; + +/** + * @description 限制命名空间下Pod的资源配额 + * @date 2020-07-03 + */ +public interface LimitRangeApi { + /** + * 创建LimitRange + * + * @param bo LimitRange BO + * @return BizLimitRange LimitRange 业务类 + */ + BizLimitRange create(PtLimitRangeBO bo); + + /** + * 查询命名空间下所有LimitRange + * + * @param namespace 命名空间 + * @return List LimitRange 业务类集合 + */ + List list(String namespace); + + /** + * 删除LimitRange + * + * @param namespace 命名空间 + * @param name LimitRange 名称 + * @return PtBaseResult 基本结果类 + */ + PtBaseResult delete(String namespace, String name); + +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/LogMonitoringApi.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/LogMonitoringApi.java new file mode 100644 index 0000000..20d9bd0 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/LogMonitoringApi.java @@ -0,0 +1,78 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.api; +import org.dubhe.k8s.domain.bo.LogMonitoringBO; +import org.dubhe.k8s.domain.vo.LogMonitoringVO; + +import java.util.List; + + +/** + * @description 日志监控接口 + * @date 2020-07-03 + */ +public interface LogMonitoringApi { + + /** + * 添加Pod日志到ES,无日志参数,默认从k8s集群查询日志添加到ES + * + * @param podName Pod名称 + * @param namespace 命名空间 + * @return boolean 日志添加是否成功 + */ + boolean addLogsToEs(String podName,String namespace); + + /** + * 添加Pod自定义日志到ES + * + * @param podName Pod名称 + * @param namespace 命名空间 + * @param logList 日志信息 + * @return boolean 日志添加是否成功 + */ + boolean addLogsToEs(String podName, String namespace, List logList); + + /** + * 日志查询方法 + * + * @param from 日志查询起始值,初始值为1,表示从第一条日志记录开始查询 + * @param size 日志查询记录数 + * @param logMonitoringBo 日志查询bo + * @return LogMonitoringVO 日志查询结果类 + */ + LogMonitoringVO searchLogByResName(int from, int size, LogMonitoringBO logMonitoringBo); + + /** + * 日志查询方法 + * + * @param from 日志查询起始值,初始值为1,表示从第一条日志记录开始查询 + * @param size 日志查询记录数 + * @param logMonitoringBo 日志查询bo + * @return LogMonitoringVO 日志查询结果类 + */ + LogMonitoringVO searchLogByPodName(int from, int size, LogMonitoringBO logMonitoringBo); + + /** + * Pod 日志总量查询方法 + * + * @param logMonitoringBo 日志查询bo + * @return long Pod 产生的日志总量 + */ + long searchLogCountByPodName(LogMonitoringBO logMonitoringBo); + +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/MetricsApi.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/MetricsApi.java new file mode 100644 index 0000000..d16c272 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/MetricsApi.java @@ -0,0 +1,107 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.api; + +import org.dubhe.k8s.domain.dto.PodQueryDTO; +import org.dubhe.k8s.domain.vo.PodRangeMetricsVO; +import org.dubhe.k8s.domain.vo.PtContainerMetricsVO; +import org.dubhe.k8s.domain.vo.PtNodeMetricsVO; +import org.dubhe.k8s.domain.vo.PtPodsVO; + +import java.util.List; + +/** + * @description 监控信息查询接口 + * @date 2020-07-03 + */ +public interface MetricsApi { + /** + * 获取k8s所有节点当前cpu、内存用量 + * + * @return List NodeMetrics 结果类集合 + */ + List getNodeMetrics(); + + /** + * 获取k8s所有Pod资源用量的实时信息 + * + * @return List Pod资源用量结果类集合 + */ + List getPodsMetricsRealTime(); + + /** + * 获取k8s所有pod当前cpu、内存用量的实时使用情况 + * + * @return List Pod资源用量结果类集合 + */ + List getPodMetricsRealTime(); + + /** + * 获取k8s resourceName 下pod当前cpu、内存用量的实时使用情况 + * @param namespace 命名空间 + * @param resourceName 资源名称 + * @return List Pod资源用量结果类集合 + */ + List getPodMetricsRealTime(String namespace,String resourceName); + + /** + * 获取k8s pod当前cpu、内存用量的实时使用情况 + * @param namespace 命名空间 + * @param podName pod名称 + * @return List Pod资源用量结果类集合 + */ + List getPodMetricsRealTimeByPodName(String namespace,String podName); + + /** + * 获取k8s pod当前cpu、内存用量的实时使用情况 + * @param namespace 命名空间 + * @param podNames pod名称列表 + * @return List Pod资源用量结果类集合 + */ + List getPodMetricsRealTimeByPodName(String namespace,List podNames); + + /** + * 获取k8s resourceName 下pod 时间范围内cpu、内存用量的实时使用情况 + * @param podQueryDTO Pod基础信息查询入参 + * @return List Pod监控指标 列表 + */ + List getPodRangeMetrics(PodQueryDTO podQueryDTO); + + /** + * 根据namespace、podName获取k8s pod 时间范围内cpu、内存用量的实时使用情况 + * @param podQueryDTO Pod基础信息查询入参 + * @return List Pod监控指标 列表 + */ + List getPodRangeMetricsByPodName(PodQueryDTO podQueryDTO); + + /** + * 查询命名空间下所有Pod的cpu和内存使用 + * + * @param namespace 命名空间 + * @return List Pod资源用量结果类集合 + */ + List getContainerMetrics(String namespace); + + /** + * 查询所有命名空间下所有pod的cpu和内存使用 + * + * @return List Pod资源用量结果类集合 + */ + List getContainerMetrics(); + +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/ModelOptJobApi.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/ModelOptJobApi.java new file mode 100644 index 0000000..0e500ef --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/ModelOptJobApi.java @@ -0,0 +1,71 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.api; + +import org.dubhe.k8s.domain.PtBaseResult; +import org.dubhe.k8s.domain.bo.PtModelOptimizationJobBO; +import org.dubhe.k8s.domain.resource.BizJob; + +import java.util.List; + +/** + * @description 模型压缩操作接口 + * @date 2020-07-03 + */ +public interface ModelOptJobApi { + /** + * 创建模型优化 Job + * + * @param bo 模型优化 Job BO + * @return BizJob Job业务类 + */ + BizJob create(PtModelOptimizationJobBO bo); + + /** + * 通过命名空间和资源名称查找Job资源 + * + * @param namespace 命名空间 + * @param resourceName 资源名称 + * @return BizJob Job 业务类 + */ + BizJob getWithResourceName(String namespace,String resourceName); + + /** + * 通过命名空间查找Job资源 + * + * @param namespace 命名空间 + * @return List Job 业务类集合 + */ + List getWithNamespace(String namespace); + + /** + * 查询所有Job资源 + * + * @return List Job 业务类集合 + */ + List listAll(); + + /** + * 通过命名空间和资源名删除Job + * + * @param namespace 命名空间 + * @param resourceName 资源名称 + * @return PtBaseResult 基础结果类 + */ + PtBaseResult deleteByResourceName(String namespace, String resourceName); +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/ModelServingApi.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/ModelServingApi.java new file mode 100644 index 0000000..a12ee64 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/ModelServingApi.java @@ -0,0 +1,52 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.api; + +import org.dubhe.k8s.domain.PtBaseResult; +import org.dubhe.k8s.domain.bo.ModelServingBO; +import org.dubhe.k8s.domain.vo.ModelServingVO; + +/** + * @description 模型部署接口 + * @date 2020-09-09 + */ +public interface ModelServingApi { + + /** + * 创建 + * @param bo + * @return + */ + ModelServingVO create(ModelServingBO bo); + + /** + * 删除 + * @param namespace 命名空间 + * @param resourceName 资源名称 + * @return PtBaseResult 基础结果类 + */ + PtBaseResult delete(String namespace, String resourceName); + + /** + * 查询 + * @param namespace + * @param resourceName + * @return + */ + ModelServingVO get(String namespace, String resourceName); +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/NamespaceApi.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/NamespaceApi.java new file mode 100644 index 0000000..11e60a1 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/NamespaceApi.java @@ -0,0 +1,145 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.api; + +import io.fabric8.kubernetes.api.model.ResourceQuota; +import org.dubhe.k8s.annotation.K8sValidation; +import org.dubhe.k8s.domain.PtBaseResult; +import org.dubhe.k8s.domain.resource.BizNamespace; +import org.dubhe.k8s.enums.ValidationTypeEnum; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * @description k8s中资源为命名空间操作接口 + * @date 2020-07-03 + */ +public interface NamespaceApi { + /** + * 创建NamespaceLabels,为null则不添加标签 + * + * @param namespace 命名空间 + * @param labels 标签Map + * @return BizNamespace Namespace 业务类 + */ + BizNamespace create(@K8sValidation(ValidationTypeEnum.K8S_RESOURCE_NAME) String namespace, Map labels); + + /** + * 根据namespace查询BizNamespace + * + * @param namespace 命名空间 + * @return BizNamespace Namespace 业务类 + */ + BizNamespace get(String namespace); + + /** + * 查询所有的BizNamespace + * + * @return List Namespace 业务类集合 + */ + List listAll(); + + /** + * 根据label标签查询所有的BizNamespace + * + * @param labelKey 标签的键 + * @return List Namespace 业务类集合 + */ + List list(String labelKey); + + /** + * 根据label标签集合查询所有的BizNamespace数据 + * + * @param labels 标签键的集合 + * @return List Namespace业务类集合 + */ + List list(Set labels); + + /** + * 删除命名空间 + * + * @param namespace 命名空间 + * @return PtBaseResult 基础结果类 + */ + PtBaseResult delete(String namespace); + + /** + * 删除命名空间的标签 + * + * @param namespace 命名空间 + * @param labelKey 标签的键 + * @return PtBaseResult 基础结果类 + */ + PtBaseResult removeLabel(String namespace, String labelKey); + + /** + * 删除命名空间下的多个标签 + * + * @param namespace 命名空间 + * @param labels 标签键的集合 + * @return PtBaseResult 基础结果类 + */ + PtBaseResult removeLabels(String namespace, Set labels); + + /** + * 将labelKey和labelValue添加到指定的命名空间 + * + * @param namespace 命名空间 + * @param labelKey 标签的键 + * @param labelValue 标签的值 + * @return PtBaseResult 基础结果类 + */ + PtBaseResult addLabel(String namespace, String labelKey, String labelValue); + + /** + * 将多个label标签添加到指定的命名空间 + * + * @param namespace 命名空间 + * @param labels 标签 + * @return PtBaseResult 基础结果类 + */ + PtBaseResult addLabels(String namespace, Map labels); + + /** + * 命名空间的资源限制 + * + * @param namespace 命名空间 + * @param quota 资源限制参数类 + * @return ResourceQuota 资源限制参数类 + */ + ResourceQuota addResourceQuota(String namespace, ResourceQuota quota); + + /** + * 获得命名空间下的所有的资源限制 + * + * @param namespace 命名空间 + * @return List 资源限制参数类 + */ + List listResourceQuotas(String namespace); + + /** + * 解除对命名空间的资源限制 + * + * @param namespace 命名空间 + * @param quota 资源限制参数类 + * @return boolean true删除成功 false删除失败 + */ + boolean removeResourceQuota(String namespace, ResourceQuota quota); +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/NativeResourceApi.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/NativeResourceApi.java new file mode 100644 index 0000000..2e68224 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/NativeResourceApi.java @@ -0,0 +1,41 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.api; + +import io.fabric8.kubernetes.api.model.HasMetadata; + +import java.util.List; + +/** + * @description Kubernetes 原生资源对象操作 + * @date 2020-08-28 + */ +public interface NativeResourceApi { + /** + * 通过 yaml创建 + * @param crYaml cr定义yaml脚本 + * @return List + */ + List create(String crYaml); + + /** + * 通过 yaml删除 + * @param crYaml cr定义yaml脚本 + * @return boolean true删除成功 false删除失败 + */ + boolean delete(String crYaml); +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/NodeApi.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/NodeApi.java new file mode 100644 index 0000000..d2b531a --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/NodeApi.java @@ -0,0 +1,210 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.api; + +import io.fabric8.kubernetes.api.model.Toleration; +import org.dubhe.k8s.domain.PtBaseResult; +import org.dubhe.k8s.domain.resource.BizNode; +import org.dubhe.k8s.domain.resource.BizTaint; +import org.dubhe.k8s.enums.LackOfResourcesEnum; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * @description Node(k8s节点)操作接口 + * @date 2020-07-03 + */ +public interface NodeApi { + /** + * 根据节点名称查询节点信息 + * + * @param nodeName 节点名称 + * @return BizNode Node 业务类 + */ + BizNode get(String nodeName); + + /** + * 查询所有节点信息 + * + * @return List Node 业务类集合 + */ + List listAll(); + + /** + * 给节点添加单个标签 + * + * @param nodeName 节点名称 + * @param labelKey 标签的键 + * @param labelValue 标签的值 + * @return PtBaseResult 基础结果类 + */ + PtBaseResult addLabel(String nodeName, String labelKey, String labelValue); + + /** + * 给节点添加多个标签 + * + * @param nodeName 节点名称 + * @param labels 标签Map + * @return PtBaseResult 基础结果类 + */ + PtBaseResult addLabels(String nodeName, Map labels); + + /** + * 删除节点单个标签 + * + * @param nodeName 节点名称 + * @param labelKey 标签的键 + * @return PtBaseResult 基础结果类 + */ + PtBaseResult deleteLabel(String nodeName, String labelKey); + + /** + * 删除节点的多个标签 + * + * @param nodeName 节点名称 + * @param labels 标签键集合 + * @return PtBaseResult 基础结果类 + */ + PtBaseResult deleteLabels(String nodeName, Set labels); + + /** + * 根据标签查询节点 + * + * @param key 标签key + * @param value 标签value + * @return List + */ + List getWithLabel(String key,String value); + + /** + * 根据标签查询节点 + * + * @param labels 标签 + * @return List + */ + List getWithLabels(Map labels); + + /** + * 设置节点是否可调度 + * + * @param nodeName 节点名称 + * @param schedulable 参数true或false + * @return PtBaseResult 基础结果类 + */ + PtBaseResult schedulable(String nodeName, boolean schedulable); + + /** + * 查询集群资源是否充足 + * + * @param nodeSelector 节点选择标签 + * @param taints 该资源所能容忍的污点 + * @param cpuNum 单位为m 1核等于1000m + * @param memNum 单位为Mi 1Mi等于1024Ki + * @param gpuNum 单位为显卡,即"1"表示1张显卡 + * @return LackOfResourcesEnum 资源缺乏枚举类 + */ + LackOfResourcesEnum isAllocatable(Map nodeSelector, List taints, Integer cpuNum, Integer memNum, Integer gpuNum); + + /** + * 查询集群资源是否充足 + * + * @param cpuNum 单位为m 1核等于1000m + * @param memNum 单位为Mi 1Mi等于1024Ki + * @param gpuNum 单位为显卡,即"1"表示1张显卡 + * @return LackOfResourcesEnum 资源缺乏枚举类 + */ + LackOfResourcesEnum isAllocatable(Integer cpuNum, Integer memNum, Integer gpuNum); + + /** + * 判断是否超出总可分配gpu数 + * @param gpuNum + * @return LackOfResourcesEnum 资源缺乏枚举类 + */ + LackOfResourcesEnum isOutOfTotalAllocatableGpu(Integer gpuNum); + + /** + * 添加污点 + * + * @param nodeName 节点名称 + * @param bizTaintList 污点 + * @return BizNode + */ + BizNode taint(String nodeName, List bizTaintList); + + /** + * 删除污点 + * + * @param nodeName 节点名称 + * @param bizTaintList 污点 + * @return BizNode + */ + BizNode delTaint(String nodeName, List bizTaintList); + + /** + * 删除污点 + * + * @param nodeName 节点名称 + * @return BizNode + */ + BizNode delTaint(String nodeName); + + /** + * 根据id获取 node资源隔离 标志 + * + * @param isolationId + * @return node资源隔离 标志 + */ + String getNodeIsolationValue(Long isolationId); + + /** + * 获取当前用户 + * + * @return node资源隔离 标志 + */ + String getNodeIsolationValue(); + + /** + * 获取当前用户资源隔离 Toleration + * + * @return Toleration + */ + Toleration getNodeIsolationToleration(); + + /** + * 获取当前用户 资源隔离 NodeSelector + * @return Map + */ + Map getNodeIsolationNodeSelector(); + + /** + * 根据userid 生成 BizTaint 列表 + * + * @param userId + * @return + */ + List geBizTaintListByUserId(Long userId); + + /** + * 根据当前用户 生成 BizTaint 列表 + * + * @return + */ + List geBizTaintListByUserId(); +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/PersistentVolumeClaimApi.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/PersistentVolumeClaimApi.java new file mode 100644 index 0000000..cbcdf0a --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/PersistentVolumeClaimApi.java @@ -0,0 +1,113 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.api; + +import io.fabric8.kubernetes.api.model.PersistentVolume; +import org.dubhe.k8s.domain.PtBaseResult; +import org.dubhe.k8s.domain.bo.PtPersistentVolumeClaimBO; +import org.dubhe.k8s.domain.resource.BizPersistentVolumeClaim; + +import java.util.List; + +/** + * @description k8s中资源为持久卷声明操作接口 + * @date 2020-07-03 + */ +public interface PersistentVolumeClaimApi { + /** + * 创建PVC + * + * @param bo PVC BO + * @return BizPersistentVolumeClaim PVC业务类 + */ + BizPersistentVolumeClaim create(PtPersistentVolumeClaimBO bo); + + /** + * 创建挂载文件存储服务 PV + * + * @param bo PVC bo + * @return BizPersistentVolumeClaim PVC业务类 + */ + BizPersistentVolumeClaim createWithFsPv(PtPersistentVolumeClaimBO bo); + + /** + * 创建挂载直接存储 PV + * + * @param bo PVC BO + * @return BizPersistentVolumeClaim PVC业务类 + */ + BizPersistentVolumeClaim createWithDirectPv(PtPersistentVolumeClaimBO bo); + + /** + * 创建创建自动挂载nfs动态存储的 PVC + * + * @param bo PVC bo + * @return BizPersistentVolumeClaim PVC 业务类 + */ + BizPersistentVolumeClaim createDynamicNfs(PtPersistentVolumeClaimBO bo); + + /** + * 查询命名空间下所有PVC + * + * @param namespace 命名空间 + * @return List PVC 业务类集合 + */ + List list(String namespace); + + /** + * 回收存储(recycle 的pv才能回收) + * + * @param namespace 命名空间 + * @param resourceName 资源名称 + * @return PtBaseResult 基础结果类 + */ + PtBaseResult recycle(String namespace, String resourceName); + + /** + * 删除具体的PVC + * + * @param namespace 命名空间 + * @param pvcName PVC名称 + * @return PtBaseResult 基础结果类 + */ + PtBaseResult delete(String namespace, String pvcName); + + /** + * 拼接storageClassName + * + * @param pvcName PVC 名称 + * @return String storageClassName + */ + String getStorageClassName(String pvcName); + + /** + * 删除PV + * + * @param pvName PV 名称 + * @return boolean true删除成功 false删除失败 + */ + boolean deletePv(String pvName); + + /** + * 查询PV + * + * @param pvName PV 名称 + * @return PersistentVolume PV 实体类 + */ + PersistentVolume getPv(String pvName); +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/PodApi.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/PodApi.java new file mode 100644 index 0000000..86b589a --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/PodApi.java @@ -0,0 +1,173 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.api; + +import io.fabric8.kubernetes.api.model.Pod; +import org.dubhe.k8s.domain.bo.LabelBO; +import org.dubhe.k8s.domain.resource.BizPod; +import org.dubhe.k8s.domain.vo.PtPodsVO; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * @description k8s中资源为Pod的操作接口 + * @date 2020-07-03 + */ +public interface PodApi { + + /** + * 根据Pod名称和命名空间查询Pod + * + * @param namespace 命名空间 + * @param podName Pod名称 + * @return BizPod Pod业务类 + */ + BizPod get(String namespace, String podName); + + /** + * 根据Pod名称列表和命名空间查询Pod列表 + * + * @param namespace 命名空间 + * @param podNames Pod名称 + * @return List Pod业务类列表 + */ + List get(String namespace, List podNames); + /** + * 根据命名空间和资源名查询Pod + * + * @param namespace 命名空间 + * @param resourceName 资源名称 + * @return BizPod Pod业务类 + */ + + BizPod getWithResourceName(String namespace, String resourceName); + /** + * 根据命名空间和资源名查询Pod集合 + * + * @param namespace 命名空间 + * @param resourceName 资源名称 + * @return List Pod业务类集合 + */ + List getListByResourceName(String namespace, String resourceName); + + /** + * 查询命名空间下所有Pod + * + * @param namespace 命名空间 + * @return List Pod业务类集合 + */ + List getWithNamespace(String namespace); + + /** + * 查询集群所有Pod + * + * @return List Pod业务类集合 + */ + List listAll(); + + List findByDtName(String dtName); + /** + * 根据Node分组获得所有运行中的Pod + * + * @return Map> 键为Node名称,值为Pod业务类集合 + */ + Map> listAllRuningPodGroupByNodeName(); + + /** + * 根据Node分组获取Pod信息 + * + * @return Map> 键为Node名称,值为Pod结果类集合 + */ + Map> getPods(); + + /** + * 根据label查询Pod集合 + * + * @param labelBO k8s label资源 bo + * @return List Pod 实体类集合 + */ + List list(LabelBO labelBO); + + /** + * 根据多个label查询Pod集合 + * + * @param labelBos label资源 bo 的集合 + * @return List Pod 实体类集合 + */ + List list(Set labelBos); + + /** + * 根据命名空间查询Pod集合 + * + * @param namespace 命名空间 + * @return List Pod 实体类集合 + */ + List list(String namespace); + + /** + * 根据命名空间和label查询Pod集合 + * + * @param namespace 命名空间 + * @param labelBO label资源 bo + * @return List Pod 实体类集合 + */ + List list(String namespace, LabelBO labelBO); + + /** + * 根据命名空间和多个label查询Pod集合 + * + * @param namespace 命名空间 + * @param labelBos label资源 bo 的集合 + * @return List Pod 实体类集合 + */ + List list(String namespace, Set labelBos); + + + /** + * 根据命名空间和Pod名称查询Token信息 + * + * @param namespace 命名空间 + * @param podName Pod名称 + * @return String token + */ + String getToken(String namespace, String podName); + + /** + * 根据命名空间和资源名获得Token信息 + * + * @param namespace 命名空间 + * @param resourceName 资源名称 + * @return String token + */ + String getTokenByResourceName(String namespace, String resourceName); + + /** + * 根据命名空间和资源名查询Notebook url + * + * @param namespace 命名空间 + * @param resourceName 资源名称 + * @return String validateJupyterUrl 验证Jupyte的url值 + */ + String getUrlByResourceName(String namespace, String resourceName); + + + + +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/ResourceIisolationApi.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/ResourceIisolationApi.java new file mode 100644 index 0000000..1740e0f --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/ResourceIisolationApi.java @@ -0,0 +1,57 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.api; + +import io.fabric8.kubernetes.api.model.apps.Deployment; +import io.fabric8.kubernetes.api.model.apps.StatefulSet; +import io.fabric8.kubernetes.api.model.batch.Job; +import org.dubhe.k8s.domain.cr.DistributeTrain; + +/** + * @description 资源隔离接口 + * @date 2021-05-20 + */ +public interface ResourceIisolationApi { + /** + * 添加 node资源隔离信息 Toleration 和 node Selector + * + * @param job + */ + void addIisolationInfo(Job job); + + /** + * 添加 node资源隔离信息 Toleration 和 node Selector + * + * @param deployment + */ + void addIisolationInfo(Deployment deployment); + + /** + * 添加 node资源隔离信息 Toleration 和 node Selector + * + * @param statefulSet + */ + void addIisolationInfo(StatefulSet statefulSet); + + /** + * 添加 node资源隔离信息 Toleration 和 node Selector + * + * @param distributeTrain + */ + void addIisolationInfo(DistributeTrain distributeTrain); +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/ResourceQuotaApi.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/ResourceQuotaApi.java new file mode 100644 index 0000000..278903d --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/ResourceQuotaApi.java @@ -0,0 +1,77 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.api; + +import org.dubhe.k8s.domain.PtBaseResult; +import org.dubhe.k8s.domain.bo.PtResourceQuotaBO; +import org.dubhe.k8s.domain.resource.BizResourceQuota; +import org.dubhe.k8s.enums.LimitsOfResourcesEnum; + +import java.util.List; + +/** + * @description 限制命名空间整体的资源配额 + * @date 2020-07-03 + */ +public interface ResourceQuotaApi { + /** + * 创建 ResourceQuota + * + * @param bo ResourceQuota BO + * @return BizResourceQuota ResourceQuota 业务类 + */ + BizResourceQuota create(PtResourceQuotaBO bo); + + /** + * 创建 ResourceQuota + * @param namespace 命名空间 + * @param name ResourceQuota 名称 + * @param cpu cpu限制 单位核 0表示不限制 + * @param memory 内存限制 单位G 0表示不限制 + * @param gpu gpu限制 单位张 0表示不限制 + * @return + */ + BizResourceQuota create(String namespace,String name,Integer cpu,Integer memory,Integer gpu); + + /** + * 根据命名空间查询ResourceQuota集合 + * + * @param namespace 命名空间 + * @return List ResourceQuota 业务类集合 + */ + List list(String namespace); + + /** + * 删除ResourceQuota + * + * @param namespace 命名空间 + * @param name ResourceQuota 名称 + * @return PtBaseResult 基础结果类 + */ + PtBaseResult delete(String namespace, String name); + + /** + * 判断资源是否达到限制 + * + * @param cpuNum 单位为m 1核等于1000m + * @param memNum 单位为Mi 1Mi等于1024Ki + * @param gpuNum 单位为显卡,即"1"表示1张显卡 + * @return LimitsOfResourcesEnum 资源超限枚举类 + */ + LimitsOfResourcesEnum reachLimitsOfResources(String namespace,Integer cpuNum, Integer memNum, Integer gpuNum); +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/TrainJobApi.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/TrainJobApi.java new file mode 100644 index 0000000..c0e81d1 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/TrainJobApi.java @@ -0,0 +1,64 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.api; + +import org.dubhe.k8s.domain.bo.PtJupyterJobBO; +import org.dubhe.k8s.domain.resource.BizJob; +import org.dubhe.k8s.domain.vo.PtJupyterJobVO; + +import java.util.List; + +/** + * @description 训练任务操作接口 + * @date 2020-07-03 + */ +public interface TrainJobApi { + /** + * 创建训练任务 Job + * + * @param bo 训练任务 Job BO + * @return PtJupyterJobVO 训练任务 Job 结果类 + */ + PtJupyterJobVO create(PtJupyterJobBO bo); + + /** + * 根据命名空间和资源名删除Job + * + * @param namespace 命名空间 + * @param resourceName 资源名称 + * @return Boolean true删除成功 false删除失败 + */ + Boolean delete(String namespace, String resourceName); + + /** + * 根据命名空间查询Job + * + * @param namespace 命名空间 + * @return List Job业务类集合 + */ + List list(String namespace); + + /** + * 根据命名空间和资源名查询Job + * + * @param namespace 命名空间 + * @param resourceName 资源名称 + * @return BizJob Job业务类 + */ + BizJob get(String namespace, String resourceName); +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/VolumeApi.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/VolumeApi.java new file mode 100644 index 0000000..9df86c4 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/VolumeApi.java @@ -0,0 +1,29 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.api; + +import org.dubhe.k8s.domain.bo.BuildFsVolumeBO; +import org.dubhe.k8s.domain.vo.VolumeVO; + +/** + * @description Kubernetes Volume api + * @date 2020-09-10 + */ +public interface VolumeApi { + VolumeVO buildFsVolumes(BuildFsVolumeBO bo); +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/impl/DistributeTrainApiImpl.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/impl/DistributeTrainApiImpl.java new file mode 100644 index 0000000..1b5c9e5 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/impl/DistributeTrainApiImpl.java @@ -0,0 +1,516 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.api.impl; + +import cn.hutool.core.collection.CollectionUtil; +import cn.hutool.core.util.RandomUtil; +import cn.hutool.core.util.StrUtil; +import com.alibaba.fastjson.JSON; +import com.baomidou.mybatisplus.core.toolkit.CollectionUtils; +import io.fabric8.kubernetes.api.model.EnvVar; +import io.fabric8.kubernetes.api.model.EnvVarBuilder; +import io.fabric8.kubernetes.api.model.ObjectMeta; +import io.fabric8.kubernetes.api.model.Quantity; +import io.fabric8.kubernetes.api.model.ResourceRequirements; +import io.fabric8.kubernetes.api.model.apiextensions.CustomResourceDefinition; +import io.fabric8.kubernetes.api.model.apiextensions.CustomResourceDefinitionList; +import io.fabric8.kubernetes.client.CustomResourceList; +import io.fabric8.kubernetes.client.KubernetesClient; +import io.fabric8.kubernetes.client.KubernetesClientException; +import io.fabric8.kubernetes.client.dsl.MixedOperation; +import io.fabric8.kubernetes.client.dsl.Resource; +import io.fabric8.kubernetes.client.dsl.base.CustomResourceDefinitionContext; +import org.dubhe.biz.base.constant.MagicNumConstant; +import org.dubhe.biz.base.constant.SymbolConstant; +import org.dubhe.biz.base.utils.StringUtils; +import org.dubhe.biz.file.api.FileStoreApi; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.dubhe.k8s.api.DistributeTrainApi; +import org.dubhe.k8s.api.NodeApi; +import org.dubhe.k8s.api.ResourceIisolationApi; +import org.dubhe.k8s.api.ResourceQuotaApi; +import org.dubhe.k8s.api.VolumeApi; +import org.dubhe.k8s.cache.ResourceCache; +import org.dubhe.k8s.constant.K8sParamConstants; +import org.dubhe.k8s.domain.PtBaseResult; +import org.dubhe.k8s.domain.bo.BuildFsVolumeBO; +import org.dubhe.k8s.domain.bo.DistributeTrainBO; +import org.dubhe.k8s.domain.bo.TaskYamlBO; +import org.dubhe.k8s.domain.cr.DistributeTrain; +import org.dubhe.k8s.domain.cr.DistributeTrainDoneable; +import org.dubhe.k8s.domain.cr.DistributeTrainList; +import org.dubhe.k8s.domain.cr.DistributeTrainSpec; +import org.dubhe.k8s.domain.entity.K8sTask; +import org.dubhe.k8s.domain.resource.BizDistributeTrain; +import org.dubhe.k8s.domain.vo.VolumeVO; +import org.dubhe.k8s.enums.ImagePullPolicyEnum; +import org.dubhe.k8s.enums.K8sKindEnum; +import org.dubhe.k8s.enums.K8sResponseEnum; +import org.dubhe.k8s.enums.LackOfResourcesEnum; +import org.dubhe.k8s.enums.LimitsOfResourcesEnum; +import org.dubhe.k8s.service.K8sTaskService; +import org.dubhe.k8s.utils.BizConvertUtils; +import org.dubhe.k8s.utils.K8sUtils; +import org.dubhe.k8s.utils.LabelUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; + +import java.io.ByteArrayInputStream; +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +import static org.dubhe.biz.base.constant.MagicNumConstant.ONE; +import static org.dubhe.biz.base.constant.MagicNumConstant.SIXTY_LONG; +import static org.dubhe.biz.base.constant.MagicNumConstant.THOUSAND_LONG; +import static org.dubhe.biz.base.constant.MagicNumConstant.ZERO; +import static org.dubhe.biz.base.constant.SymbolConstant.BLANK; +import static org.dubhe.k8s.constant.K8sParamConstants.GPU_RESOURCE_KEY; +import static org.dubhe.k8s.constant.K8sParamConstants.NODE_READY_TRUE; +import static org.dubhe.k8s.constant.K8sParamConstants.PYTHONUNBUFFERED; +import static org.dubhe.k8s.constant.K8sParamConstants.QUANTITY_CPU_KEY; +import static org.dubhe.k8s.constant.K8sParamConstants.QUANTITY_MEMORY_KEY; + +/** + * @description DistributeTrain 实现类 + * @date 2020-07-07 + */ +public class DistributeTrainApiImpl implements DistributeTrainApi { + private static final String CRD_NAME = "distributetrains.onebrain.oneflow.org"; + private static final String CRD_GROUP = "onebrain.oneflow.org"; + private static final String VERSION = "v1alpha1"; + private static final String PLURAL = "distributetrains"; + private static final String SCOPE = "Namespaced"; + private static final String ENABLE_USER_OP = "ENABLE_USER_OP"; + private static final String DATA_ROOT = "DATA_ROOT"; + private static final String NODE_NUM = "NODE_NUM"; + private static final String GPU_NUM_PER_NODE = "GPU_NUM_PER_NODE"; + private static final String ONEFLOW_DEBUG_MODE = "ONEFLOW_DEBUG_MODE"; + private static final String NCCL_DEBUG = "NCCL_DEBUG"; + private static final String INFO = "INFO"; + private static final String DATA_ROOT_VALUE = "/dataset"; + + @javax.annotation.Resource(name = "hostFileStoreApiImpl") + private FileStoreApi fileStoreApi; + + @Autowired + private K8sTaskService k8sTaskService; + + @Autowired + private ResourceCache resourceCache; + + @Autowired + private VolumeApi volumeApi; + + @Autowired + private NodeApi nodeApi; + + @Autowired + private ResourceQuotaApi resourceQuotaApi; + + @Autowired + private ResourceIisolationApi resourceIisolationApi; + + private KubernetesClient client; + private MixedOperation> dtClient; + + public DistributeTrainApiImpl(K8sUtils k8sUtils) { + this.client = k8sUtils.getClient(); + initDtClient(); + } + + /** + * 创建cr + * + * @param bo 自定义资源入参 + * @return BizDistributeTrain 自定义资源dt + */ + @Override + public BizDistributeTrain create(DistributeTrainBO bo) { + LogUtil.info(LogEnum.BIZ_K8S, "Params of creating DistributeTrain--create:{}", bo); + LimitsOfResourcesEnum limitsOfResources = resourceQuotaApi.reachLimitsOfResources(bo.getNamespace(), bo.getCpuNum() * bo.getSize(), bo.getMemNum() * bo.getSize(), bo.getGpuNum() * bo.getSize()); + if (!LimitsOfResourcesEnum.ADEQUATE.equals(limitsOfResources)) { + return new BizDistributeTrain().error(K8sResponseEnum.LACK_OF_RESOURCES.getCode(), limitsOfResources.getMessage()); + } + if (bo.getGpuNum() != null && bo.getGpuNum() > 0) { + LackOfResourcesEnum lack = nodeApi.isOutOfTotalAllocatableGpu(bo.getGpuNum() * bo.getSize()); + if (!LackOfResourcesEnum.ADEQUATE.equals(lack)) { + return new BizDistributeTrain().error(K8sResponseEnum.LACK_OF_RESOURCES.getCode(), lack.getMessage()); + } + } + if (!fileStoreApi.createDirs(bo.getDirList().toArray(new String[MagicNumConstant.ZERO]))) { + return new BizDistributeTrain().error(K8sResponseEnum.INTERNAL_SERVER_ERROR.getCode(), K8sResponseEnum.INTERNAL_SERVER_ERROR.getMessage()); + } + VolumeVO volumeVO = volumeApi.buildFsVolumes(new BuildFsVolumeBO(bo.getNamespace(), bo.getName(), bo.getFsMounts())); + if (!K8sResponseEnum.SUCCESS.getCode().equals(volumeVO.getCode())) { + return new BizDistributeTrain().error(volumeVO.getCode(), volumeVO.getMessage()); + } + //删除pod名称缓存 + resourceCache.deletePodCacheByResourceName(bo.getNamespace(), bo.getName()); + return new DistributeTrainDeployer(bo, volumeVO).deploy(); + } + + public class DistributeTrainDeployer { + private String baseName; + private String distributeTrainName; + private String namespace; + private int size; + private String image; + private String masterCmd; + private Integer memNum; + private Integer cpuNum; + private Integer gpuNum; + private String slaveCmd; + private Map env; + private Map baseLabels; + private String businessLabel; + private Integer delayCreate; + private Integer delayDelete; + private TaskYamlBO taskYamlBO; + private VolumeVO volumeVO; + + public DistributeTrainDeployer(DistributeTrainBO bo, VolumeVO volumeVO) { + this.baseName = bo.getName(); + this.distributeTrainName = StrUtil.format(K8sParamConstants.RESOURCE_NAME_TEMPLATE, baseName, RandomUtil.randomString(K8sParamConstants.RESOURCE_NAME_SUFFIX_LENGTH)); + this.namespace = bo.getNamespace(); + this.size = bo.getSize(); + this.image = bo.getImage(); + this.masterCmd = bo.getMasterCmd(); + this.memNum = bo.getMemNum(); + this.cpuNum = bo.getCpuNum(); + this.gpuNum = bo.getGpuNum(); + this.slaveCmd = bo.getSlaveCmd(); + this.env = bo.getEnv(); + this.businessLabel = bo.getBusinessLabel(); + this.baseLabels = LabelUtils.getChildLabels(baseName, distributeTrainName, K8sKindEnum.DISTRIBUTETRAIN.getKind(), businessLabel); + this.delayCreate = bo.getDelayCreateTime(); + this.delayDelete = bo.getDelayDeleteTime(); + this.taskYamlBO = new TaskYamlBO(); + this.volumeVO = volumeVO; + } + + /** + * 判断分布式训练资源定义在集群是否存在 + */ + private boolean isCrdExist() { + CustomResourceDefinitionList crds = client.customResourceDefinitions().list(); + //获取所有自定义资源的定义 + List crdsItems = crds.getItems(); + LogUtil.info(LogEnum.BIZ_K8S, "Found {} CRD(s)", crdsItems.size()); + CustomResourceDefinition crd = null; + //循环判断是否存在分布式训练资源定义 + for (CustomResourceDefinition obj : crdsItems) { + ObjectMeta metadata = obj.getMetadata(); + + if (metadata != null) { + String name = metadata.getName(); + if (CRD_NAME.equals(name)) { + crd = obj; + break; + } + } + } + + if (crd != null) { + LogUtil.info(LogEnum.BIZ_K8S, "Found CRD: {}", crd.getMetadata().getSelfLink()); + return true; + } else { + LogUtil.info(LogEnum.BIZ_K8S, "Not found crd {}", CRD_NAME); + return false; + } + } + + /** + * 构建Spec + */ + private DistributeTrainSpec buildSpec() { + DistributeTrainSpec distributeTrainSpec = new DistributeTrainSpec(); + //配置节点数 + distributeTrainSpec.setSize(size); + //配置镜像和拉取策略 + distributeTrainSpec.setImage(image); + distributeTrainSpec.setImagePullPolicy(ImagePullPolicyEnum.IFNOTPRESENT.getPolicy()); + //配置主从节点运行命令 + distributeTrainSpec.setMasterCmd(masterCmd); + distributeTrainSpec.setSlaveCmd(slaveCmd); + + //master节点申请资源 + ResourceRequirements masterResources = new ResourceRequirements(); + masterResources.setLimits(new HashMap() {{ + Optional.ofNullable(memNum).ifPresent(v -> put(QUANTITY_MEMORY_KEY, new Quantity(v.toString(), K8sParamConstants.MEM_UNIT))); + Optional.ofNullable(cpuNum).ifPresent(v -> put(QUANTITY_CPU_KEY, new Quantity(v.toString(), K8sParamConstants.CPU_UNIT))); + Optional.ofNullable(gpuNum).ifPresent(v -> put(GPU_RESOURCE_KEY, new Quantity(v.toString()))); + }}); + distributeTrainSpec.setMasterResources(masterResources); + //slave节点申请资源 + ResourceRequirements slaveResources = new ResourceRequirements(); + slaveResources.setLimits(new HashMap() {{ + Optional.ofNullable(memNum).ifPresent(v -> put(QUANTITY_MEMORY_KEY, new Quantity(v.toString(), K8sParamConstants.MEM_UNIT))); + Optional.ofNullable(cpuNum).ifPresent(v -> put(QUANTITY_CPU_KEY, new Quantity(v.toString(), K8sParamConstants.CPU_UNIT))); + Optional.ofNullable(gpuNum).ifPresent(v -> put(GPU_RESOURCE_KEY, new Quantity(v.toString()))); + }}); + distributeTrainSpec.setSlaveResources(slaveResources); + //配置环境变量 + List envVarList = new ArrayList() {{ + add(new EnvVarBuilder().withName(PYTHONUNBUFFERED).withValue(SymbolConstant.ZERO).build()); + add(new EnvVarBuilder().withName(ENABLE_USER_OP).withValue(NODE_READY_TRUE).build()); + add(new EnvVarBuilder().withName(DATA_ROOT).withValue(DATA_ROOT_VALUE).build()); + add(new EnvVarBuilder().withName(NODE_NUM).withValue(String.valueOf(size)).build()); + add(new EnvVarBuilder().withName(ONEFLOW_DEBUG_MODE).withValue(BLANK).build()); + add(new EnvVarBuilder().withName(NCCL_DEBUG).withValue(INFO).build()); + }}; + + if (gpuNum != null && gpuNum != 0) { + envVarList.add(new EnvVarBuilder().withName(GPU_NUM_PER_NODE).withValue(String.valueOf(gpuNum)).build()); + } + if (CollectionUtils.isNotEmpty(env)) { + Set envNames = env.keySet(); + for (String envName : envNames) { + envVarList.add(new EnvVarBuilder().withName(envName).withValue(env.get(envName)).build()); + } + } + + distributeTrainSpec.setEnv(envVarList); + distributeTrainSpec.setVolumeMounts(volumeVO.getVolumeMounts()); + distributeTrainSpec.setVolumes(volumeVO.getVolumes()); + + return distributeTrainSpec; + } + + /** + * 判断分布式训练资源在集群是否存在 + */ + private BizDistributeTrain alreadyHaveDistributeTrain() { + CustomResourceList dummyList = dtClient.inNamespace(namespace).withLabels(LabelUtils.withEnvResourceName(baseName)).list(); + List dummyItems = dummyList.getItems(); + if (CollectionUtil.isNotEmpty(dummyItems)) { + DistributeTrain distributeTrain = dummyItems.get(0); + LogUtil.warn(LogEnum.BIZ_K8S, "Skip creating DistributeTrain, {} already exists", baseName); + return BizConvertUtils.toBizDistributeTrain(distributeTrain); + } + return null; + } + + /** + * 部署分布式训练资源 + */ + private BizDistributeTrain deploy() { + try { + if (!isCrdExist()) { + return null; + } + + BizDistributeTrain bizdistributeTrain = alreadyHaveDistributeTrain(); + if (bizdistributeTrain != null) { + return bizdistributeTrain; + } + + DistributeTrain distributeTrain = new DistributeTrain(); + ObjectMeta metadata = new ObjectMeta(); + metadata.setName(distributeTrainName); + metadata.setNamespace(namespace); + metadata.setLabels(baseLabels); + distributeTrain.setMetadata(metadata); + + distributeTrain.setSpec(buildSpec()); + + delayCreate = delayCreate == null || delayCreate <= 0 ? ZERO : delayCreate; + delayDelete = delayDelete == null || delayDelete <= 0 ? ZERO : delayDelete; + + if (delayCreate > ZERO || delayDelete > ZERO) { + taskYamlBO.append(distributeTrain); + long applyUnixTime = System.currentTimeMillis() / THOUSAND_LONG + delayCreate * SIXTY_LONG; + Timestamp applyDisplayTime = new Timestamp(applyUnixTime * THOUSAND_LONG); + long stopUnixTime = applyUnixTime + delayDelete * SIXTY_LONG; + Timestamp stopDisplayTime = new Timestamp(stopUnixTime * THOUSAND_LONG); + K8sTask k8sTask = new K8sTask() {{ + setNamespace(namespace); + setResourceName(baseName); + setTaskYaml(JSON.toJSONString(taskYamlBO)); + setBusiness(businessLabel); + setApplyUnixTime(applyUnixTime); + setApplyDisplayTime(applyDisplayTime); + setApplyStatus(delayCreate == ZERO ? ZERO : ONE); + }}; + if (delayDelete > ZERO) { + k8sTask.setStopUnixTime(stopUnixTime); + k8sTask.setStopDisplayTime(stopDisplayTime); + k8sTask.setStopStatus(ONE); + } + k8sTaskService.createOrUpdateTask(k8sTask); + } + if (delayCreate == null || delayCreate == 0) { + LogUtil.info(LogEnum.BIZ_K8S, "Ready to deploy {}", distributeTrainName); + resourceIisolationApi.addIisolationInfo(distributeTrain); + distributeTrain = dtClient.inNamespace(namespace).create(distributeTrain); + LogUtil.info(LogEnum.BIZ_K8S, "{} deployed successfully", distributeTrainName); + } + + return BizConvertUtils.toBizDistributeTrain(distributeTrain); + } catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "DistributeTrainApi.deploy过程错误, 错误信息为{}", e.toString()); + return new BizDistributeTrain().error(String.valueOf(e.getCode()), e.getMessage()); + } + } + } + + /** + * 删除 + * + * @param namespace 命名空间 + * @param resourceName 资源名称 + * @return PtBaseResult 基础结果类 + */ + @Override + public PtBaseResult deleteByResourceName(String namespace, String resourceName) { + LogUtil.info(LogEnum.BIZ_K8S, "deleteByResourceName namespace {} resourceName {}", namespace,resourceName); + if (dtClient == null) { + LogUtil.error(LogEnum.BIZ_K8S, "dtClient初始化失败"); + } + if (StringUtils.isBlank(namespace) || StringUtils.isBlank(resourceName)) { + return new BizDistributeTrain().baseErrorBadRequest(); + } + try { + k8sTaskService.deleteByNamespaceAndResourceName(namespace,resourceName); + //根据条件获得对应的分布式训练资源集合 + DistributeTrainList list = dtClient.inNamespace(namespace).withLabels(LabelUtils.withEnvResourceName(resourceName)).list(); + List items = list.getItems(); + //判断该分布式训练资源是否存在 + if (items.size() == 0) { + return new PtBaseResult(K8sResponseEnum.SUCCESS.getCode(), "k8s任务不存在,无需删除"); + } + //判断是否存在多个分布式训练资源 + if (items.size() > 1) { + LogUtil.error(LogEnum.BIZ_K8S, "DistributeTrainApiImpl.deleteByResourceName过程错误, 存在多个dt"); + return new PtBaseResult(K8sResponseEnum.INTERNAL_SERVER_ERROR.getCode(), K8sResponseEnum.INTERNAL_SERVER_ERROR.getMessage()); + } + + if (dtClient.delete(items.get(0))) { + LogUtil.info(LogEnum.BIZ_K8S, "input namespace={};resourceName={}; 删除成功"); + return new PtBaseResult(); + } else { + return new PtBaseResult(K8sResponseEnum.INTERNAL_SERVER_ERROR.getCode(), K8sResponseEnum.INTERNAL_SERVER_ERROR.getMessage()); + } + } catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "DistributeTrainApiImpl.deleteByResourceName过程错误, 错误信息为{}", e); + return new BizDistributeTrain().error(String.valueOf(e.getCode()), e.getMessage()); + } + } + + /** + * 根据namespace和resourceName查询cr信息 + * + * @param namespce 命令空间 + * @param resourceName 资源名称 + * @return BizDistributeTrain 自定义资源转换类集合 + */ + @Override + public BizDistributeTrain get(String namespce, String resourceName) { + try { + DistributeTrain distributeTrain = dtClient.inNamespace(namespce).withName(resourceName).get(); + if (distributeTrain != null) { + return BizConvertUtils.toBizDistributeTrain(distributeTrain); + } + } catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "DistributeTrainApiImpl.get查询错误,错误信息为{}", e.toString()); + return new BizDistributeTrain().error(String.valueOf(e.getCode()), e.getMessage()); + } + return null; + } + + /** + * 根据名称查cr + * + * @param crName 自定义资源名称 + * @return BizDistributeTrain 自定义资源类 + */ + @Override + public BizDistributeTrain findDisByName(String crName) { + //获取所有DistributeTrain资源 + List distributeTrains = dtClient.inAnyNamespace().list().getItems(); + if (!CollectionUtil.isEmpty(distributeTrains)) { + for (DistributeTrain distributeTrain : distributeTrains) { + ObjectMeta metadata = distributeTrain.getMetadata(); + if (metadata != null) { + if (crName != null && crName.equals(metadata.getName())) { + return BizConvertUtils.toBizDistributeTrain(distributeTrain); + } + } + } + } + return null; + } + + /** + * 通过 yaml创建 + * @param crYaml cr定义yaml脚本 + * @return BizDistributeTrain 自定义资源类 + */ + @Override + public BizDistributeTrain create(String crYaml) { + try { + DistributeTrain distributeTrain = dtClient.load(new ByteArrayInputStream(crYaml.getBytes())).createOrReplace(); + return BizConvertUtils.toBizDistributeTrain(distributeTrain); + } catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "Create DistributeTrain error:{} ,yml:{}", e.getMessage(), crYaml); + return null; + } + } + + /** + * 通过 yaml删除 + * @param crYaml cr定义yaml脚本 + * @return boolean true 删除成功 false删除失败 + */ + @Override + public boolean delete(String crYaml) { + try { + LogUtil.info(LogEnum.BIZ_K8S, "delete crYaml {}",crYaml); + return dtClient.load(new ByteArrayInputStream(crYaml.getBytes())).delete(); + } catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "Delete DistributeTrain error:{} ,yml:{}", e.getMessage(), crYaml); + return false; + } + } + + /** + * 初始化dtClient + */ + void initDtClient() { + LogUtil.info(LogEnum.BIZ_K8S, "dtClient初始化开始"); + try { + //构建CustomResourceDefinitionContext + CustomResourceDefinitionContext crdContext = new CustomResourceDefinitionContext.Builder() + .withGroup(CRD_GROUP) + .withName(CRD_NAME) + .withPlural(PLURAL) + .withScope(SCOPE) + .withVersion(VERSION) + .build(); + + dtClient = client.customResources(crdContext, DistributeTrain.class, DistributeTrainList.class, DistributeTrainDoneable.class); + } catch (Exception e) { + LogUtil.error(LogEnum.BIZ_K8S, "dtClient初始化失败, 错误信息为{}", e); + } + LogUtil.info(LogEnum.BIZ_K8S, "dtClient初始化完成"); + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/impl/DubheDeploymentApiImpl.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/impl/DubheDeploymentApiImpl.java new file mode 100644 index 0000000..f688dd1 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/impl/DubheDeploymentApiImpl.java @@ -0,0 +1,439 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.api.impl; + +import cn.hutool.core.collection.CollectionUtil; +import cn.hutool.core.util.RandomUtil; +import cn.hutool.core.util.StrUtil; +import com.google.common.collect.Maps; +import io.fabric8.kubernetes.api.model.Container; +import io.fabric8.kubernetes.api.model.ContainerBuilder; +import io.fabric8.kubernetes.api.model.LabelSelector; +import io.fabric8.kubernetes.api.model.Quantity; +import io.fabric8.kubernetes.api.model.Volume; +import io.fabric8.kubernetes.api.model.VolumeBuilder; +import io.fabric8.kubernetes.api.model.VolumeMount; +import io.fabric8.kubernetes.api.model.VolumeMountBuilder; +import io.fabric8.kubernetes.api.model.apps.Deployment; +import io.fabric8.kubernetes.api.model.apps.DeploymentBuilder; +import io.fabric8.kubernetes.api.model.apps.DeploymentList; +import io.fabric8.kubernetes.client.KubernetesClient; +import io.fabric8.kubernetes.client.KubernetesClientException; +import org.dubhe.biz.base.constant.MagicNumConstant; +import org.dubhe.biz.base.utils.StringUtils; +import org.dubhe.biz.file.api.FileStoreApi; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.dubhe.k8s.api.DubheDeploymentApi; +import org.dubhe.k8s.api.NodeApi; +import org.dubhe.k8s.api.ResourceIisolationApi; +import org.dubhe.k8s.api.ResourceQuotaApi; +import org.dubhe.k8s.cache.ResourceCache; +import org.dubhe.k8s.constant.K8sLabelConstants; +import org.dubhe.k8s.constant.K8sParamConstants; +import org.dubhe.k8s.domain.PtBaseResult; +import org.dubhe.k8s.domain.bo.PtModelOptimizationDeploymentBO; +import org.dubhe.k8s.domain.resource.BizDeployment; +import org.dubhe.k8s.enums.ImagePullPolicyEnum; +import org.dubhe.k8s.enums.K8sKindEnum; +import org.dubhe.k8s.enums.K8sResponseEnum; +import org.dubhe.k8s.enums.LackOfResourcesEnum; +import org.dubhe.k8s.enums.LimitsOfResourcesEnum; +import org.dubhe.k8s.enums.RestartPolicyEnum; +import org.dubhe.k8s.enums.ShellCommandEnum; +import org.dubhe.k8s.utils.BizConvertUtils; +import org.dubhe.k8s.utils.K8sUtils; +import org.dubhe.k8s.utils.LabelUtils; +import org.dubhe.k8s.utils.YamlUtils; +import org.springframework.beans.factory.annotation.Autowired; + +import javax.annotation.Resource; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; + +/** + * @description DubheDeploymentApi 实现类 + * @date 2020-05-26 + */ +public class DubheDeploymentApiImpl implements DubheDeploymentApi { + private K8sUtils k8sUtils; + private KubernetesClient client; + + @Autowired + private NodeApi nodeApi; + @Autowired + private ResourceCache resourceCache; + @Autowired + private ResourceQuotaApi resourceQuotaApi; + @Resource(name = "hostFileStoreApiImpl") + private FileStoreApi fileStoreApi; + @Autowired + private ResourceIisolationApi resourceIisolationApi; + + private static final String DATASET = "/dataset"; + private static final String WORKSPACE = "/workspace"; + private static final String OUTPUT = "/output"; + + private static final String PVC_DATASET = "pvc-dataset"; + private static final String PVC_WORKSPACE = "pvc-workspace"; + private static final String PVC_OUTPUT = "pvc-output"; + + public DubheDeploymentApiImpl(K8sUtils k8sUtils) { + this.k8sUtils = k8sUtils; + this.client = k8sUtils.getClient(); + } + + /** + * 创建模型压缩Deployment + * + * @param bo 模型压缩 Deployment BO + * @return BizDeployment Deployment 业务类 + */ + @Override + public BizDeployment create(PtModelOptimizationDeploymentBO bo) { + try { + LogUtil.info(LogEnum.BIZ_K8S, "Param of create:{}", bo); + LimitsOfResourcesEnum limitsOfResources = resourceQuotaApi.reachLimitsOfResources(bo.getNamespace(), bo.getCpuNum(), bo.getMemNum(), bo.getGpuNum()); + if (!LimitsOfResourcesEnum.ADEQUATE.equals(limitsOfResources)) { + return new BizDeployment().error(K8sResponseEnum.LACK_OF_RESOURCES.getCode(), limitsOfResources.getMessage()); + } + LackOfResourcesEnum lack = nodeApi.isAllocatable(bo.getCpuNum(), bo.getMemNum(), bo.getGpuNum()); + if (!LackOfResourcesEnum.ADEQUATE.equals(lack)) { + return new BizDeployment().error(K8sResponseEnum.LACK_OF_RESOURCES.getCode(), lack.getMessage()); + } + if (!fileStoreApi.createDirs(bo.getWorkspaceDir(), bo.getDatasetDir(), bo.getOutputDir())) { + return new BizDeployment().error(K8sResponseEnum.INTERNAL_SERVER_ERROR.getCode(), K8sResponseEnum.INTERNAL_SERVER_ERROR.getMessage()); + } + resourceCache.deletePodCacheByResourceName(bo.getNamespace(), bo.getName()); + return new DeploymentDeployer(bo).deploy(); + } catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "DeploymentApiImpl.create error, param:{} error:{}", bo, e); + return new BizDeployment().error(String.valueOf(e.getCode()), e.getMessage()); + } + + } + + /** + * 通过命名空间和资源名称查找Deployment资源 + * + * @param namespace 命名空间 + * @param resourceName 资源名称 + * @return BizDeployment Deployment 业务类 + */ + @Override + public BizDeployment getWithResourceName(String namespace, String resourceName) { + try { + if (StringUtils.isEmpty(namespace)) { + return new BizDeployment().baseErrorBadRequest(); + } + DeploymentList bizDeploymentList = client.apps().deployments().inNamespace(namespace).withLabels(LabelUtils.withEnvResourceName(resourceName)).list(); + if (CollectionUtil.isEmpty(bizDeploymentList.getItems())) { + return new BizDeployment().error(K8sResponseEnum.NOT_FOUND.getCode(), K8sResponseEnum.NOT_FOUND.getMessage()); + } + Deployment deployment = bizDeploymentList.getItems().get(0); + return BizConvertUtils.toBizDeployment(deployment); + } catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "DeploymentApiImpl.getWithResourceName error, param:[namespace]={}, [resourceName]={}, error:{}", namespace, resourceName, e); + return new BizDeployment().error(String.valueOf(e.getCode()), e.getMessage()); + } + } + + /** + * 通过命名空间查找Deployment资源集合 + * + * @param namespace 命名空间 + * @return List Deployment 业务类集合 + */ + @Override + public List getWithNamespace(String namespace) { + List bizDeploymentList = new ArrayList<>(); + DeploymentList deploymentList = client.apps().deployments().inNamespace(namespace).withLabels(LabelUtils.withEnvResourceName()).list(); + if (CollectionUtil.isEmpty(deploymentList.getItems())) { + return bizDeploymentList; + } + return BizConvertUtils.toBizDeploymentList(deploymentList.getItems()); + } + + /** + * 查询集群所有Deployment资源 + * + * @return List Deployment 业务类集合 + */ + @Override + public List listAll() { + return client.apps().deployments().inAnyNamespace().withLabels(LabelUtils.withEnvResourceName()).list().getItems().parallelStream().map(obj -> BizConvertUtils.toBizDeployment(obj)).collect(Collectors.toList()); + } + + /** + * 通过资源名进行删除 + * + * @param namespace 命名空间 + * @param resourceName 资源名称 + * @return PtBaseResult 基础结果类 + */ + @Override + public PtBaseResult deleteByResourceName(String namespace, String resourceName) { + LogUtil.info(LogEnum.BIZ_K8S, "Param of deleteByResourceName:namespace {} resourceName {}", namespace,resourceName); + if (StringUtils.isEmpty(namespace) || StringUtils.isEmpty(resourceName)) { + return new PtBaseResult().baseErrorBadRequest(); + } + try { + client.apps().deployments().inNamespace(namespace).withLabels(LabelUtils.withEnvResourceName(resourceName)).delete(); + return new PtBaseResult(); + } catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "DeploymentApiImpl.deleteByResourceName error, param:[namespace]={}, [resourceName]={}, error:{}", namespace, resourceName, e); + return new PtBaseResult(String.valueOf(e.getCode()), e.getMessage()); + } + } + + private class DeploymentDeployer { + private String baseName; + private String deploymentName; + + private String namespace; + private String image; + private String datasetDir; + private String datasetMountPath; + private String workspaceDir; + private String workspaceMountPath; + private String outputDir; + private String outputMountPath; + + private List cmdLines; + //数据集默认只读 + private boolean datasetReadOnly; + + private Map resourcesLimitsMap; + private Map baseLabels; + private String businessLabel; + private Integer gpuNum; + + + private DeploymentDeployer(PtModelOptimizationDeploymentBO bo) { + this.baseName = bo.getName(); + this.deploymentName = StrUtil.format(K8sParamConstants.RESOURCE_NAME_TEMPLATE, baseName, RandomUtil.randomString(MagicNumConstant.EIGHT)); + this.namespace = bo.getNamespace(); + this.image = bo.getImage(); + this.datasetDir = bo.getDatasetDir(); + this.datasetMountPath = StringUtils.isEmpty(bo.getDatasetMountPath()) ? DATASET : bo.getDatasetMountPath(); + this.workspaceDir = bo.getWorkspaceDir(); + this.workspaceMountPath = StringUtils.isEmpty(bo.getWorkspaceMountPath()) ? WORKSPACE : bo.getWorkspaceMountPath(); + this.outputDir = bo.getOutputDir(); + this.outputMountPath = StringUtils.isEmpty(bo.getOutputMountPath()) ? OUTPUT : bo.getOutputMountPath(); + this.cmdLines = new ArrayList(); + this.gpuNum = bo.getGpuNum(); + Optional.ofNullable(bo.getDatasetReadOnly()).ifPresent(v -> datasetReadOnly = v); + Optional.ofNullable(bo.getCmdLines()).ifPresent(v -> cmdLines = v); + + this.resourcesLimitsMap = Maps.newHashMap(); + Optional.ofNullable(bo.getCpuNum()).ifPresent(v -> resourcesLimitsMap.put(K8sParamConstants.QUANTITY_CPU_KEY, new Quantity(v.toString(), K8sParamConstants.CPU_UNIT))); + Optional.ofNullable(bo.getGpuNum()).ifPresent(v -> resourcesLimitsMap.put(K8sParamConstants.GPU_RESOURCE_KEY, new Quantity(v.toString()))); + Optional.ofNullable(bo.getMemNum()).ifPresent(v -> resourcesLimitsMap.put(K8sParamConstants.QUANTITY_MEMORY_KEY, new Quantity(v.toString(), K8sParamConstants.MEM_UNIT))); + this.businessLabel = bo.getBusinessLabel(); + this.baseLabels = LabelUtils.getBaseLabels(baseName, businessLabel); + + this.datasetReadOnly = true; + } + + /** + * 部署Deployment + * + * @return BizDeployment Deployment 业务类 + */ + public BizDeployment deploy() { + //部署deployment + try { + Deployment deployment = deployDeployment(); + return BizConvertUtils.toBizDeployment(deployment); + } catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "DeploymentApiImpl.deploy error:{}", e); + return (BizDeployment) new PtBaseResult().error(String.valueOf(e.getCode()), e.getMessage()); + } + + } + + /** + * 检查资源是否已经存在 + * + * @return Deployment Deployment 业务类 + */ + private Deployment alreadyHaveDeployment() { + DeploymentList list = client.apps().deployments().inNamespace(namespace).withLabels(LabelUtils.withEnvResourceName(baseName)).list(); + if (CollectionUtil.isNotEmpty(list.getItems())) { + Deployment deployment = list.getItems().get(0); + LogUtil.info(LogEnum.BIZ_K8S, "Skip creating job, {} already exists", deployment.getMetadata().getName()); + return deployment; + } + return null; + } + + /** + * 部署Deployment + * + * @return Deployment Deployment 业务类 + */ + private Deployment deployDeployment() { + //已经存在直接返回 + Deployment deployment = alreadyHaveDeployment(); + if (deployment != null) { + return deployment; + } + deployment = buildDeployment(); + LogUtil.info(LogEnum.BIZ_K8S, YamlUtils.dumpAsYaml(deployment)); + resourceIisolationApi.addIisolationInfo(deployment); + deployment = client.apps().deployments().inNamespace(namespace).create(deployment); + return deployment; + } + + /** + * 构建Deployment + * + * @return Deployment Deployment 业务类 + */ + private Deployment buildDeployment() { + Map childLabels = LabelUtils.getChildLabels(baseName, deploymentName, K8sKindEnum.DEPLOYMENT.getKind(), businessLabel); + LabelSelector labelSelector = new LabelSelector(); + labelSelector.setMatchLabels(childLabels); + return new DeploymentBuilder() + .withNewMetadata() + .withName(deploymentName) + .addToLabels(baseLabels) + .withNamespace(namespace) + .endMetadata() + .withNewSpec() + .withSelector(labelSelector) + .withNewTemplate() + .withNewMetadata() + .withName(deploymentName) + .addToLabels(childLabels) + .withNamespace(namespace) + .endMetadata() + .withNewSpec() + .addToNodeSelector(gpuSelector()) + .addToContainers(buildContainer()) + .addToVolumes(buildVolume().toArray(new Volume[0])) + .withRestartPolicy(RestartPolicyEnum.ALWAYS.getRestartPolicy()) + .endSpec() + .endTemplate() + .endSpec() + .build(); + } + + /** + * 添加Gpu label + * + * @return Map Gpu label 键值 + */ + private Map gpuSelector() { + Map gpuSelector = new HashMap<>(2); + if (gpuNum != null && gpuNum > 0) { + gpuSelector.put(K8sLabelConstants.NODE_GPU_LABEL_KEY, K8sLabelConstants.NODE_GPU_LABEL_VALUE); + } + return gpuSelector; + } + + /** + * 构建Container + * + * @return Container 容器 + */ + private Container buildContainer() { + return new ContainerBuilder() + .withNewName(deploymentName) + .withNewImage(image) + .withNewImagePullPolicy(ImagePullPolicyEnum.IFNOTPRESENT.getPolicy()) + .withVolumeMounts(buildVolumeMount()) + .addNewCommand(ShellCommandEnum.BIN_BANSH.getShell()) + .addAllToArgs(cmdLines) + .withNewResources().addToLimits(resourcesLimitsMap).endResources() + .build(); + } + + /** + * 构建VolumeMount + * + * @return List VolumeMount集合类 + */ + private List buildVolumeMount() { + List volumeMounts = new ArrayList<>(); + if (StrUtil.isNotBlank(datasetDir)) { + volumeMounts.add(new VolumeMountBuilder() + .withName(PVC_DATASET) + .withMountPath(datasetMountPath) + .withReadOnly(datasetReadOnly) + .build()); + } + if (StrUtil.isNotBlank(workspaceDir)) { + volumeMounts.add(new VolumeMountBuilder() + .withName(PVC_WORKSPACE) + .withMountPath(workspaceMountPath) + .withReadOnly(false) + .build()); + } + if (StrUtil.isNotBlank(outputDir)) { + volumeMounts.add(new VolumeMountBuilder() + .withName(PVC_OUTPUT) + .withMountPath(outputMountPath) + .withReadOnly(false) + .build()); + } + return volumeMounts; + } + + /** + * 构建Volume + * + * @return List Volume集合类 + */ + private List buildVolume() { + List volumes = new ArrayList<>(); + if (StrUtil.isNotBlank(datasetDir)) { + volumes.add(new VolumeBuilder() + .withName(PVC_DATASET) + .withNewHostPath() + .withPath(datasetDir) + .withType(K8sParamConstants.HOST_PATH_TYPE) + .endHostPath() + .build()); + } + if (StrUtil.isNotBlank(workspaceDir)) { + volumes.add(new VolumeBuilder() + .withName(PVC_WORKSPACE) + .withNewHostPath() + .withPath(workspaceDir) + .withType(K8sParamConstants.HOST_PATH_TYPE) + .endHostPath() + .build()); + } + if (StrUtil.isNotBlank(outputDir)) { + volumes.add(new VolumeBuilder() + .withName(PVC_OUTPUT) + .withNewHostPath() + .withPath(outputDir) + .withType(K8sParamConstants.HOST_PATH_TYPE) + .endHostPath() + .build()); + } + return volumes; + } + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/impl/JupyterResourceApiImpl.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/impl/JupyterResourceApiImpl.java new file mode 100644 index 0000000..e74b306 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/impl/JupyterResourceApiImpl.java @@ -0,0 +1,692 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.api.impl; + +import cn.hutool.core.codec.Base64; +import cn.hutool.core.collection.CollectionUtil; +import cn.hutool.core.util.RandomUtil; +import cn.hutool.core.util.StrUtil; +import com.alibaba.fastjson.JSON; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Maps; +import io.fabric8.kubernetes.api.model.Container; +import io.fabric8.kubernetes.api.model.ContainerPortBuilder; +import io.fabric8.kubernetes.api.model.EnvVar; +import io.fabric8.kubernetes.api.model.EnvVarBuilder; +import io.fabric8.kubernetes.api.model.IntOrString; +import io.fabric8.kubernetes.api.model.LabelSelector; +import io.fabric8.kubernetes.api.model.Quantity; +import io.fabric8.kubernetes.api.model.ResourceRequirementsBuilder; +import io.fabric8.kubernetes.api.model.Secret; +import io.fabric8.kubernetes.api.model.SecretBuilder; +import io.fabric8.kubernetes.api.model.SecretList; +import io.fabric8.kubernetes.api.model.Service; +import io.fabric8.kubernetes.api.model.ServiceBuilder; +import io.fabric8.kubernetes.api.model.ServiceList; +import io.fabric8.kubernetes.api.model.Volume; +import io.fabric8.kubernetes.api.model.VolumeBuilder; +import io.fabric8.kubernetes.api.model.VolumeMount; +import io.fabric8.kubernetes.api.model.VolumeMountBuilder; +import io.fabric8.kubernetes.api.model.apps.StatefulSet; +import io.fabric8.kubernetes.api.model.apps.StatefulSetBuilder; +import io.fabric8.kubernetes.api.model.apps.StatefulSetList; +import io.fabric8.kubernetes.api.model.extensions.Ingress; +import io.fabric8.kubernetes.api.model.extensions.IngressBuilder; +import io.fabric8.kubernetes.api.model.extensions.IngressList; +import io.fabric8.kubernetes.client.KubernetesClient; +import io.fabric8.kubernetes.client.KubernetesClientException; +import org.dubhe.biz.base.constant.MagicNumConstant; +import org.dubhe.biz.base.constant.SymbolConstant; +import org.dubhe.biz.base.utils.StringUtils; +import org.dubhe.biz.file.api.FileStoreApi; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.dubhe.k8s.api.JupyterResourceApi; +import org.dubhe.k8s.api.NodeApi; +import org.dubhe.k8s.api.PersistentVolumeClaimApi; +import org.dubhe.k8s.api.ResourceIisolationApi; +import org.dubhe.k8s.api.ResourceQuotaApi; +import org.dubhe.k8s.cache.ResourceCache; +import org.dubhe.k8s.constant.K8sLabelConstants; +import org.dubhe.k8s.constant.K8sParamConstants; +import org.dubhe.k8s.domain.PtBaseResult; +import org.dubhe.k8s.domain.bo.PtJupyterResourceBO; +import org.dubhe.k8s.domain.bo.PtPersistentVolumeClaimBO; +import org.dubhe.k8s.domain.bo.TaskYamlBO; +import org.dubhe.k8s.domain.entity.K8sTask; +import org.dubhe.k8s.domain.resource.BizPersistentVolumeClaim; +import org.dubhe.k8s.domain.vo.PtJupyterDeployVO; +import org.dubhe.k8s.enums.ImagePullPolicyEnum; +import org.dubhe.k8s.enums.K8sKindEnum; +import org.dubhe.k8s.enums.K8sResponseEnum; +import org.dubhe.k8s.enums.LackOfResourcesEnum; +import org.dubhe.k8s.enums.LimitsOfResourcesEnum; +import org.dubhe.k8s.service.K8sTaskService; +import org.dubhe.k8s.utils.K8sUtils; +import org.dubhe.k8s.utils.LabelUtils; +import org.dubhe.k8s.utils.YamlUtils; +import org.springframework.beans.factory.annotation.Autowired; + +import javax.annotation.Resource; +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import static java.util.stream.Collectors.toList; +import static org.dubhe.biz.base.constant.MagicNumConstant.SIXTY_LONG; +import static org.dubhe.biz.base.constant.MagicNumConstant.THOUSAND_LONG; +import static org.dubhe.biz.base.constant.MagicNumConstant.ZERO; +import static org.dubhe.biz.base.constant.MagicNumConstant.ZERO_LONG; + +/** + * @description JupyterResourceApi 实现类 + * @date 2020-04-17 + */ +public class JupyterResourceApiImpl implements JupyterResourceApi { + + private K8sUtils k8sUtils; + private KubernetesClient client; + @Autowired + private PersistentVolumeClaimApi persistentVolumeClaimApi; + @Resource(name = "hostFileStoreApiImpl") + private FileStoreApi fileStoreApi; + @Autowired + private NodeApi nodeApi; + @Autowired + private K8sTaskService k8sTaskService; + @Autowired + private ResourceCache resourceCache; + @Autowired + private ResourceQuotaApi resourceQuotaApi; + @Autowired + private ResourceIisolationApi resourceIisolationApi; + + + private static final String DATASET = "/dataset"; + private static final String WORKSPACE = "/workspace"; + + private static final String PVC_DATASET = "pvc-dataset"; + private static final String PVC_WORKSPACE = "pvc-workspace"; + + private static final String CONTAINER_NAME = "web"; + private static final Integer CONTAINER_PORT = 8888; + private static final Integer SVC_PORT = 32680; + private static final String NOTEBOOK_MAX_UPLOAD_SIZE = "100m"; + + public JupyterResourceApiImpl(K8sUtils k8sUtils) { + this.k8sUtils = k8sUtils; + this.client = k8sUtils.getClient(); + } + + /** + * 创建Notebook + * + * @param bo 模型管理 Notebook BO + * @return PtJupyterDeployVO Notebook 结果类 + */ + @Override + public PtJupyterDeployVO create(PtJupyterResourceBO bo) { + try { + LogUtil.info(LogEnum.BIZ_K8S, "Param of creating Notebook--create:{}", bo); + if (null == bo) { + return new PtJupyterDeployVO().error(K8sResponseEnum.BAD_REQUEST.getCode(), K8sResponseEnum.BAD_REQUEST.getMessage()); + } + + LimitsOfResourcesEnum limitsOfResources = resourceQuotaApi.reachLimitsOfResources(bo.getNamespace(), bo.getCpuNum(), bo.getMemNum(), bo.getGpuNum()); + if (!LimitsOfResourcesEnum.ADEQUATE.equals(limitsOfResources)) { + return new PtJupyterDeployVO().error(K8sResponseEnum.LACK_OF_RESOURCES.getCode(), limitsOfResources.getMessage()); + } + LackOfResourcesEnum lack = nodeApi.isAllocatable(bo.getCpuNum(), bo.getMemNum(), bo.getGpuNum()); + if (!LackOfResourcesEnum.ADEQUATE.equals(lack)) { + return new PtJupyterDeployVO().error(K8sResponseEnum.LACK_OF_RESOURCES.getCode(), lack.getMessage()); + } + + if (!fileStoreApi.createDirs(bo.getWorkspaceDir(), bo.getDatasetDir())) { + return new PtJupyterDeployVO().error(K8sResponseEnum.INTERNAL_SERVER_ERROR.getCode(), K8sResponseEnum.INTERNAL_SERVER_ERROR.getMessage()); + } + resourceCache.deletePodCacheByResourceName(bo.getNamespace(), bo.getName()); + PtJupyterDeployVO result = new JupyterDeployer(bo).buildFsVolumes().deploy(); + LogUtil.info(LogEnum.BIZ_K8S, "Return value of creating Notebook create:{}", result); + return result; + } catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "JupyterResourceApiImpl.create error, param:{} error:{}", bo, e); + return new PtJupyterDeployVO().error(String.valueOf(e.getCode()), e.getMessage()); + } + } + + /** + * 挂载存储创建 Notebook + * + * @param bo 模型管理 Notebook BO + * @return PtJupyterDeployVO Notebook 结果类 + */ + @Override + public PtJupyterDeployVO createWithPvc(PtJupyterResourceBO bo) { + try { + LimitsOfResourcesEnum limitsOfResources = resourceQuotaApi.reachLimitsOfResources(bo.getNamespace(), bo.getCpuNum(), bo.getMemNum(), bo.getGpuNum()); + if (!LimitsOfResourcesEnum.ADEQUATE.equals(limitsOfResources)) { + return new PtJupyterDeployVO().error(K8sResponseEnum.LACK_OF_RESOURCES.getCode(), limitsOfResources.getMessage()); + } + LackOfResourcesEnum lack = nodeApi.isAllocatable(bo.getCpuNum(), bo.getMemNum(), bo.getGpuNum()); + if (!LackOfResourcesEnum.ADEQUATE.equals(lack)) { + return new PtJupyterDeployVO().error(K8sResponseEnum.LACK_OF_RESOURCES.getCode(), lack.getMessage()); + } + LogUtil.info(LogEnum.BIZ_K8S, "Param of creating Notebook--createWithPvc:{}", bo); + if (null == bo) { + return new PtJupyterDeployVO().error(K8sResponseEnum.BAD_REQUEST.getCode(), K8sResponseEnum.BAD_REQUEST.getMessage()); + } + if (!fileStoreApi.createDirs(bo.getWorkspaceDir(), bo.getDatasetDir())) { + return new PtJupyterDeployVO().error(K8sResponseEnum.INTERNAL_SERVER_ERROR.getCode(), K8sResponseEnum.INTERNAL_SERVER_ERROR.getMessage()); + } + BizPersistentVolumeClaim bizPersistentVolumeClaim = (StringUtils.isEmpty(bo.getWorkspaceDir())) ? persistentVolumeClaimApi.createDynamicNfs(new PtPersistentVolumeClaimBO(bo)) : persistentVolumeClaimApi.createWithFsPv(new PtPersistentVolumeClaimBO(bo)); + if (K8sResponseEnum.SUCCESS.getCode().equals(bizPersistentVolumeClaim.getCode())) { + bo.setWorkspacePvcName(bizPersistentVolumeClaim.getName()); + resourceCache.deletePodCacheByResourceName(bo.getNamespace(), bo.getName()); + PtJupyterDeployVO result = new JupyterDeployer(bo).buildFsPvcVolumes().deploy(); + LogUtil.info(LogEnum.BIZ_K8S, "Return value of creating Notebook--createWithPvc:{}", result); + return result; + } else { + LogUtil.info(LogEnum.BIZ_K8S, "Notebook--createWithPvc error:{}", bizPersistentVolumeClaim.getMessage()); + return new PtJupyterDeployVO().error(bizPersistentVolumeClaim.getCode(), bizPersistentVolumeClaim.getMessage()); + } + } catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "JupyterResourceApiImpl.createWithPvc error, param:{} error:{}", bo, e); + return new PtJupyterDeployVO().error(String.valueOf(e.getCode()), e.getMessage()); + } + } + + /** + * 删除 Notebook + * + * @param namespace 命名空间 + * @param resourceName 资源名称 + * @return PtBaseResult 基础结果类 + */ + @Override + public PtBaseResult delete(String namespace, String resourceName) { + LogUtil.info(LogEnum.BIZ_K8S, "Param of delete namespace {} resourceName {}", namespace,resourceName); + try { + Boolean res = client.extensions().ingresses().inNamespace(namespace).withLabels(LabelUtils.withEnvResourceName(resourceName)).delete() + && client.services().inNamespace(namespace).withLabels(LabelUtils.withEnvResourceName(resourceName)).delete() + && client.apps().statefulSets().inNamespace(namespace).withLabels(LabelUtils.withEnvResourceName(resourceName)).delete() + && client.secrets().inNamespace(namespace).withLabels(LabelUtils.withEnvResourceName(resourceName)).delete(); + k8sTaskService.deleteByNamespaceAndResourceName(namespace,resourceName); + if (res) { + return new PtBaseResult(); + } else { + return K8sResponseEnum.REPEAT.toPtBaseResult(); + } + } catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "JupyterResourceApiImpl.delete error:{}", e); + return new PtBaseResult(String.valueOf(e.getCode()), e.getMessage()); + } + } + + /** + * 查询命名空间下所有Notebook + * + * @param namespace 命名空间 + * @return List Notebook 结果类集合 + */ + @Override + public List list(String namespace) { + StatefulSetList list = client.apps().statefulSets().inNamespace(namespace).withLabels(LabelUtils.withEnvResourceName()).list(); + if (CollectionUtil.isEmpty(list.getItems())) { + return Collections.EMPTY_LIST; + } + return list.getItems().stream().map(ss -> { + Map labels = ss.getMetadata().getLabels(); + String resourceName = labels.get(K8sLabelConstants.BASE_TAG_SOURCE); + return get(namespace, resourceName); + }).collect(toList()); + } + + /** + * 查询Notebook + * + * @param namespace 命名空间 + * @param resourceName 资源名称 + * @return PtJupyterDeployVO Notebook 结果类 + */ + @Override + public PtJupyterDeployVO get(String namespace, String resourceName) { + try { + IngressList ingressList = client.extensions().ingresses().inNamespace(namespace).withLabels(LabelUtils.withEnvResourceName(resourceName)).list(); + Ingress ingress = CollectionUtil.isEmpty(ingressList.getItems()) ? null : ingressList.getItems().get(0); + ServiceList svcList = client.services().inNamespace(namespace).withLabels(LabelUtils.withEnvResourceName(resourceName)).list(); + Service svc = CollectionUtil.isEmpty(svcList.getItems()) ? null : svcList.getItems().get(0); + StatefulSetList ssList = client.apps().statefulSets().inNamespace(namespace).withLabels(LabelUtils.withEnvResourceName(resourceName)).list(); + StatefulSet statefulSet = CollectionUtil.isEmpty(ssList.getItems()) ? null : ssList.getItems().get(0); + SecretList secretList = client.secrets().inNamespace(namespace).withLabels(LabelUtils.withEnvResourceName(resourceName)).list(); + Secret secret = CollectionUtil.isEmpty(secretList.getItems()) ? null : secretList.getItems().get(0); + return new PtJupyterDeployVO(secret, statefulSet, svc, ingress); + } catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "JupyterResourceApiImpl.get error:{}", e); + return new PtJupyterDeployVO().error(String.valueOf(e.getCode()), e.getMessage()); + } + } + + private class JupyterDeployer { + private static final String SUB_RESOURCE_NAME_TEMPLATE = "{}-{}-{}"; + + private String baseName; + private String statefulSetName; + private String secretName; + private String svcName; + private String ingressName; + + private String namespace; + private String image; + private String datasetDir; + private String datasetMountPath; + private String workspaceMountPath; + private String workspaceDir; + private Boolean useGpu; + + //数据集默认只读 + private boolean datasetReadOnly; + private String workSpacePvcName; + private String host; + + private Map resourcesLimitsMap; + private Map baseLabels; + private Map podLabels; + + private String defaultJupyterPwd; + private String baseUrl; + private String secondaryDomain; + private String businessLabel; + private Integer delayDelete; + + private List volumeMounts; + private List volumes; + private TaskYamlBO taskYamlBO; + + private JupyterDeployer(PtJupyterResourceBO bo) { + this.baseName = bo.getName(); + this.statefulSetName = StrUtil.format(K8sParamConstants.RESOURCE_NAME_TEMPLATE, baseName, RandomUtil.randomString(MagicNumConstant.FIVE)); + this.namespace = bo.getNamespace(); + this.image = bo.getImage(); + this.datasetDir = bo.getDatasetDir(); + this.datasetMountPath = StringUtils.isEmpty(bo.getDatasetMountPath()) ? DATASET : bo.getDatasetMountPath(); + this.workspaceDir = bo.getWorkspaceDir(); + this.workspaceMountPath = StringUtils.isEmpty(bo.getWorkspaceMountPath()) ? WORKSPACE : bo.getWorkspaceMountPath(); + Optional.ofNullable(bo.getDatasetReadOnly()).ifPresent(v -> datasetReadOnly = v); + this.workSpacePvcName = bo.getWorkspacePvcName(); + this.useGpu = bo.getUseGpu() == null ? false : bo.getUseGpu(); + if (bo.getUseGpu() != null && bo.getUseGpu() && null == bo.getGpuNum()) { + bo.setGpuNum(0); + } + + this.resourcesLimitsMap = Maps.newHashMap(); + Optional.ofNullable(bo.getCpuNum()).ifPresent(v -> resourcesLimitsMap.put(K8sParamConstants.QUANTITY_CPU_KEY, new Quantity(v.toString(), K8sParamConstants.CPU_UNIT))); + Optional.ofNullable(bo.getGpuNum()).ifPresent(v -> resourcesLimitsMap.put(K8sParamConstants.GPU_RESOURCE_KEY, new Quantity(v.toString()))); + Optional.ofNullable(bo.getMemNum()).ifPresent(v -> resourcesLimitsMap.put(K8sParamConstants.QUANTITY_MEMORY_KEY, new Quantity(v.toString(), K8sParamConstants.MEM_UNIT))); + + this.host = k8sUtils.getHost(); + this.businessLabel = bo.getBusinessLabel(); + this.delayDelete = bo.getDelayDeleteTime(); + this.baseLabels = LabelUtils.getBaseLabels(baseName, businessLabel); + this.podLabels = LabelUtils.getChildLabels(baseName, statefulSetName, K8sKindEnum.STATEFULSET.getKind(), businessLabel); + //生成附属资源的名称 + generateResourceName(); + + this.defaultJupyterPwd = RandomUtil.randomNumbers(MagicNumConstant.SIX); + this.baseUrl = SymbolConstant.SLASH + RandomUtil.randomString(MagicNumConstant.SIX); + this.secondaryDomain = RandomUtil.randomString(MagicNumConstant.SIX) + SymbolConstant.DOT; + + this.datasetReadOnly = true; + this.volumeMounts = new ArrayList(); + this.volumes = new ArrayList(); + this.taskYamlBO = new TaskYamlBO(); + } + + /** + * 部署Notebook + * + * @return PtJupyterDeployVO Notebook 结果类 + */ + public PtJupyterDeployVO deploy() { + //部署secret + Secret secret = deploySecret(Base64.encode(defaultJupyterPwd), Base64.encode(baseUrl)); + LogUtil.info(LogEnum.BIZ_K8S, YamlUtils.dumpAsYaml(secret)); + //部署statefulset + StatefulSet statefulSet = deployStatefulSet(); + //部署svc + Service service = deployService(); + //部署ingress + Ingress ingress = deployIngress(); + + if (delayDelete != null && delayDelete > ZERO) { + taskYamlBO.append(secret); + taskYamlBO.append(statefulSet); + taskYamlBO.append(service); + taskYamlBO.append(ingress); + + long stopUnixTime = System.currentTimeMillis() / THOUSAND_LONG + delayDelete * SIXTY_LONG; + Timestamp stopDisplayTime = new Timestamp(stopUnixTime * THOUSAND_LONG); + K8sTask k8sTask = new K8sTask() {{ + setNamespace(namespace); + setResourceName(baseName); + setTaskYaml(JSON.toJSONString(taskYamlBO)); + setBusiness(businessLabel); + setStopUnixTime(stopUnixTime); + setStopDisplayTime(stopDisplayTime); + setStopStatus(MagicNumConstant.ONE); + }}; + k8sTaskService.createOrUpdateTask(k8sTask); + } + + return new PtJupyterDeployVO(secret, statefulSet, service, ingress); + } + + /** + * 部署secret + * + * @param base64Pwd base64密码 + * @param base64BaseUrl base64路径 + * @return Secret 加密后的密码 + */ + private Secret deploySecret(String base64Pwd, String base64BaseUrl) { + Secret secret = null; + SecretList list = client.secrets().inNamespace(namespace).withLabels(LabelUtils.withEnvResourceName(baseName)).list(); + if (CollectionUtil.isNotEmpty(list.getItems())) { + secret = list.getItems().get(0); + secretName = secret.getMetadata().getName(); + LogUtil.info(LogEnum.BIZ_K8S, "Skip creating secret, {} already exists", secretName); + } else { + secret = new SecretBuilder() + .withNewMetadata() + .withName(secretName) + .addToLabels(baseLabels) + .withNamespace(namespace) + .endMetadata() + .addToData(ImmutableMap.of(K8sParamConstants.SECRET_PWD_KEY, base64Pwd, K8sParamConstants.SECRET_URL_KEY, base64BaseUrl)) + .build(); + + LogUtil.info(LogEnum.BIZ_K8S, "Ready to deploy {}", secretName); + secret = client.secrets().create(secret); + LogUtil.info(LogEnum.BIZ_K8S, "{} deployed successfully", secretName); + } + + return secret; + } + + /** + * 构建VolumeMount + */ + private void buildDatasetFsVolume() { + //挂载点 + if (StrUtil.isNotBlank(datasetDir)) { + volumeMounts.add(new VolumeMountBuilder() + .withName(PVC_DATASET) + .withMountPath(datasetMountPath) + .withReadOnly(datasetReadOnly) + .build()); + + volumes.add(new VolumeBuilder() + .withName(PVC_DATASET) + .withNewHostPath() + .withPath(datasetDir) + .withType(K8sParamConstants.HOST_PATH_TYPE) + .endHostPath() + .build()); + } + } + + /** + * 构建VolumeMount + */ + private void buildWorkspaceFsVolume() { + if (StrUtil.isNotBlank(workspaceDir)) { + volumeMounts.add(new VolumeMountBuilder() + .withName(PVC_WORKSPACE) + .withMountPath(workspaceMountPath) + .build()); + + volumes.add(new VolumeBuilder() + .withName(PVC_WORKSPACE) + .withNewHostPath() + .withPath(workspaceDir) + .withType(K8sParamConstants.HOST_PATH_TYPE) + .endHostPath() + .build()); + } + } + + /** + * 构建VolumeMount + */ + private void buildWorkspaceFsPvcVolume() { + //挂载点 + if (StrUtil.isNotBlank(workSpacePvcName)) { + volumeMounts.add(new VolumeMountBuilder() + .withName(PVC_WORKSPACE) + .withMountPath(workspaceMountPath) + .build()); + + volumes.add(new VolumeBuilder() + .withName(PVC_WORKSPACE) + .withNewPersistentVolumeClaim(workSpacePvcName, false) + .build()); + } + } + + /** + * 挂载存储 + * + * @return JupyterDeployer Notebook 部署类 + */ + private JupyterDeployer buildFsVolumes() { + buildDatasetFsVolume(); + buildWorkspaceFsVolume(); + return this; + } + + /** + * 按照存储资源声明挂载存储 + * + * @return JupyterDeployer Notebook 部署类 + */ + private JupyterDeployer buildFsPvcVolumes() { + buildDatasetFsVolume(); + buildWorkspaceFsPvcVolume(); + return this; + } + + /** + * 部署statefulset + * + * @return StatefulSet 类 + */ + private StatefulSet deployStatefulSet() { + StatefulSet statefulSet = null; + StatefulSetList list = client.apps().statefulSets().inNamespace(namespace).withLabels(LabelUtils.withEnvResourceName(baseName)).list(); + if (CollectionUtil.isNotEmpty(list.getItems())) { + statefulSet = list.getItems().get(0); + statefulSetName = statefulSet.getMetadata().getName(); + LogUtil.info(LogEnum.BIZ_K8S, "Skip creating statefulSet, {} already exists", statefulSetName); + return statefulSet; + } + LabelSelector labelSelector = new LabelSelector(); + labelSelector.setMatchLabels(ImmutableMap.of(K8sLabelConstants.BASE_TAG_P_NAME, statefulSetName)); + //容器 + Container container = new Container(); + container.setName(statefulSetName); + container.setImage(image); + container.setImagePullPolicy(ImagePullPolicyEnum.IFNOTPRESENT.getPolicy()); + //端口映射 + container.setPorts(Arrays.asList(new ContainerPortBuilder() + .withContainerPort(CONTAINER_PORT) + .withName(CONTAINER_NAME).build())); + container.setVolumeMounts(volumeMounts); + + //环境变量 + List env = new ArrayList(); + env.add(new EnvVarBuilder().withName(K8sParamConstants.ENV_PWD_KEY) + .withNewValueFrom() + .withNewSecretKeyRef() + .withName(secretName) + .withKey(K8sParamConstants.SECRET_PWD_KEY) + .endSecretKeyRef() + .endValueFrom().build()); + env.add(new EnvVarBuilder().withName(K8sParamConstants.ENV_URL_KEY) + .withNewValueFrom() + .withNewSecretKeyRef() + .withName(secretName) + .withKey(K8sParamConstants.SECRET_URL_KEY) + .endSecretKeyRef() + .endValueFrom().build()); + + container.setResources(new ResourceRequirementsBuilder() + .addToLimits(resourcesLimitsMap) + .build()); + Map gpuLabel = new HashMap<>(2); + if (useGpu) { + gpuLabel.put(K8sLabelConstants.NODE_GPU_LABEL_KEY, K8sLabelConstants.NODE_GPU_LABEL_VALUE); + } + + statefulSet = new StatefulSetBuilder() + .withNewMetadata() + .withName(statefulSetName) + .addToLabels(baseLabels) + .withNamespace(namespace) + .endMetadata() + .withNewSpec() + .withSelector(labelSelector) + .withServiceName(statefulSetName) + .withReplicas(1) + .withNewTemplate() + .withNewMetadata() + .withName(statefulSetName) + .addToLabels(podLabels) + .withNamespace(namespace) + .endMetadata() + .withNewSpec() + .withTerminationGracePeriodSeconds(ZERO_LONG) + .addToNodeSelector(gpuLabel) + .withTerminationGracePeriodSeconds(SIXTY_LONG) + .addToContainers(container) + .addToVolumes(volumes.toArray(new Volume[0])) + .endSpec() + .endTemplate() + .endSpec() + .build(); + LogUtil.info(LogEnum.BIZ_K8S, "Ready to deploy {}, yaml info is : {}", statefulSetName, YamlUtils.dumpAsYaml(statefulSet)); + resourceIisolationApi.addIisolationInfo(statefulSet); + statefulSet = client.apps().statefulSets().create(statefulSet); + LogUtil.info(LogEnum.BIZ_K8S, "{} deployed successfully", statefulSetName); + return statefulSet; + } + + /** + * 部署service + * + * @return Service 类 + */ + private Service deployService() { + Service svc = null; + ServiceList list = client.services().inNamespace(namespace).withLabels(LabelUtils.withEnvResourceName(baseName)).list(); + if (CollectionUtil.isNotEmpty(list.getItems())) { + svc = list.getItems().get(0); + svcName = svc.getMetadata().getName(); + LogUtil.info(LogEnum.BIZ_K8S, "Skip creating service, {} already exists", svcName); + return svc; + } + svc = new ServiceBuilder() + .withNewMetadata() + .withName(svcName) + .addToLabels(baseLabels) + .withNamespace(namespace) + .endMetadata() + .withNewSpec() + .addNewPort() + .withPort(SVC_PORT) + .withTargetPort(new IntOrString(CONTAINER_PORT)) + .withName(CONTAINER_NAME) + .endPort() + .withClusterIP("None") + .withSelector(podLabels) + .endSpec() + .build(); + + LogUtil.info(LogEnum.BIZ_K8S, "Ready to deploy {}, yaml info is : {}", svcName, YamlUtils.dumpAsYaml(svc)); + svc = client.services().create(svc); + LogUtil.info(LogEnum.BIZ_K8S, "{} deployed successfully", svcName); + return svc; + } + + /** + * 部署ingress + * + * @return Ingress 类 + */ + private Ingress deployIngress() { + Ingress ingress = null; + IngressList list = client.extensions().ingresses().inNamespace(namespace).withLabels(LabelUtils.withEnvResourceName(baseName)).list(); + if (CollectionUtil.isNotEmpty(list.getItems())) { + ingress = list.getItems().get(0); + ingressName = ingress.getMetadata().getName(); + LogUtil.info(LogEnum.BIZ_K8S, "Skip creating ingress, {} already exists", ingressName); + return ingress; + } + ingress = new IngressBuilder() + .withNewMetadata() + .withName(ingressName) + .addToLabels(baseLabels) + .withNamespace(namespace) + .addToAnnotations(K8sParamConstants.INGRESS_PROXY_BODY_SIZE_KEY, NOTEBOOK_MAX_UPLOAD_SIZE) + .endMetadata() + .withNewSpec() + .addNewRule() + .withHost(secondaryDomain + host) + .withNewHttp() + .withPaths() + .addNewPath() + .withNewPath(SymbolConstant.SLASH) + .withNewBackend() + .withServiceName(svcName) + .withServicePort(new IntOrString(SVC_PORT)) + .endBackend() + .endPath() + .endHttp() + .endRule() + .endSpec() + .build(); + LogUtil.info(LogEnum.BIZ_K8S, "Ready to deploy {}, yaml info is : {}", ingressName, YamlUtils.dumpAsYaml(ingress)); + ingress = client.extensions().ingresses().create(ingress); + LogUtil.info(LogEnum.BIZ_K8S, "{} deployed successfully", ingressName); + return ingress; + } + + /** + * 生成资源名 + */ + private void generateResourceName() { + String randomStr = RandomUtil.randomString(MagicNumConstant.FIVE); + this.secretName = StrUtil.format(SUB_RESOURCE_NAME_TEMPLATE, baseName, SymbolConstant.TOKEN, randomStr); + this.ingressName = StrUtil.format(SUB_RESOURCE_NAME_TEMPLATE, baseName, K8sParamConstants.INGRESS_SUFFIX, randomStr); + this.svcName = StrUtil.format(SUB_RESOURCE_NAME_TEMPLATE, baseName, K8sParamConstants.SVC_SUFFIX, randomStr); + } + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/impl/LimitRangeApiImpl.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/impl/LimitRangeApiImpl.java new file mode 100644 index 0000000..ee488f7 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/impl/LimitRangeApiImpl.java @@ -0,0 +1,128 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.api.impl; + +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; +import io.fabric8.kubernetes.api.model.LimitRange; +import io.fabric8.kubernetes.api.model.LimitRangeBuilder; +import io.fabric8.kubernetes.api.model.LimitRangeItem; +import io.fabric8.kubernetes.api.model.LimitRangeList; +import io.fabric8.kubernetes.client.KubernetesClient; +import io.fabric8.kubernetes.client.KubernetesClientException; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.k8s.api.LimitRangeApi; +import org.dubhe.k8s.domain.PtBaseResult; +import org.dubhe.k8s.domain.bo.PtLimitRangeBO; +import org.dubhe.k8s.domain.resource.BizLimitRange; +import org.dubhe.k8s.enums.K8sResponseEnum; +import org.dubhe.k8s.utils.BizConvertUtils; +import org.dubhe.k8s.utils.K8sUtils; +import org.dubhe.biz.log.utils.LogUtil; +import org.dubhe.biz.base.utils.StringUtils; + +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; + +/** + * @description LimitRangeApi 实现类 + * @date 2020-04-23 + */ +public class LimitRangeApiImpl implements LimitRangeApi { + private KubernetesClient client; + + public LimitRangeApiImpl(K8sUtils k8sUtils) { + this.client = k8sUtils.getClient(); + } + + /** + * 创建LimitRange + * + * @param bo LimitRange BO + * @return BizLimitRange LimitRange 业务类 + */ + @Override + public BizLimitRange create(PtLimitRangeBO bo) { + try { + LogUtil.info(LogEnum.BIZ_K8S, "Input {}", bo); + Gson gson = new Gson(); + List limits = gson.fromJson(gson.toJson(bo.getLimits()), new TypeToken>() { + }.getType()); + LimitRange limitRange = new LimitRangeBuilder().withNewMetadata().withName(bo.getName()).endMetadata() + .withNewSpec().withLimits(limits).endSpec().build(); + BizLimitRange bizLimitRange = BizConvertUtils.toBizLimitRange(client.limitRanges().inNamespace(bo.getNamespace()).create(limitRange)); + LogUtil.info(LogEnum.BIZ_K8S, "Output {}", bizLimitRange); + return bizLimitRange; + } catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "LimitRangeApiImpl.create error, param:{} error:{}", bo, e); + return new BizLimitRange().error(String.valueOf(e.getCode()), e.getMessage()); + } + } + + /** + * 查询命名空间下所有LimitRange + * + * @param namespace 命名空间 + * @return List LimitRange 业务类集合 + */ + @Override + public List list(String namespace) { + try { + LogUtil.info(LogEnum.BIZ_K8S, "Input namespace={}", namespace); + if (StringUtils.isEmpty(namespace)) { + LimitRangeList limitRangeList = client.limitRanges().inAnyNamespace().list(); + return limitRangeList.getItems().parallelStream().map(obj -> BizConvertUtils.toBizLimitRange(obj)).collect(Collectors.toList()); + } else { + LimitRangeList limitRangeList = client.limitRanges().inNamespace(namespace).list(); + List bizLimitRangeList = limitRangeList.getItems().parallelStream().map(obj -> BizConvertUtils.toBizLimitRange(obj)).collect(Collectors.toList()); + LogUtil.info(LogEnum.BIZ_K8S, "Output {}", bizLimitRangeList); + return bizLimitRangeList; + } + } catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "LimitRangeApiImpl.list error, param:[namespace]={},error:", namespace, e); + return Collections.EMPTY_LIST; + } + + } + + /** + * 删除LimitRange + * + * @param namespace 命名空间 + * @param name LimitRange 名称 + * @return PtBaseResult 基本结果类 + */ + @Override + public PtBaseResult delete(String namespace, String name) { + LogUtil.info(LogEnum.BIZ_K8S, "Input namespace={};name={}", namespace, name); + if (StringUtils.isEmpty(namespace) || StringUtils.isEmpty(name)) { + return new PtBaseResult().baseErrorBadRequest(); + } + try { + if (client.limitRanges().inNamespace(namespace).withName(name).delete()) { + return new PtBaseResult(); + } else { + return K8sResponseEnum.REPEAT.toPtBaseResult(); + } + } catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "LimitRangeApiImpl.delete error, param:[namespace]={}, [name]={}, error:",namespace, name, e); + return new PtBaseResult(String.valueOf(e.getCode()), e.getMessage()); + } + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/impl/LogMonitoringApiImpl.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/impl/LogMonitoringApiImpl.java new file mode 100644 index 0000000..a61b2d8 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/impl/LogMonitoringApiImpl.java @@ -0,0 +1,369 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.api.impl; + +import com.alibaba.fastjson.JSON; +import com.baomidou.mybatisplus.core.toolkit.CollectionUtils; +import io.fabric8.kubernetes.api.model.DoneablePod; +import io.fabric8.kubernetes.api.model.Pod; +import io.fabric8.kubernetes.client.KubernetesClient; +import io.fabric8.kubernetes.client.dsl.PodResource; +import org.dubhe.biz.base.constant.MagicNumConstant; +import org.dubhe.biz.base.utils.StringUtils; +import org.dubhe.biz.base.utils.TimeTransferUtil; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.dubhe.k8s.api.LogMonitoringApi; +import org.dubhe.k8s.cache.ResourceCache; +import org.dubhe.k8s.domain.bo.LogMonitoringBO; +import org.dubhe.k8s.domain.vo.LogMonitoringVO; +import org.dubhe.k8s.utils.K8sUtils; +import org.elasticsearch.action.bulk.BulkRequest; +import org.elasticsearch.action.index.IndexRequest; +import org.elasticsearch.action.search.SearchRequest; +import org.elasticsearch.action.search.SearchResponse; +import org.elasticsearch.client.RequestOptions; +import org.elasticsearch.client.RestHighLevelClient; +import org.elasticsearch.index.query.BoolQueryBuilder; +import org.elasticsearch.index.query.Operator; +import org.elasticsearch.index.query.QueryBuilders; +import org.elasticsearch.search.SearchHit; +import org.elasticsearch.search.SearchHits; +import org.elasticsearch.search.builder.SearchSourceBuilder; +import org.elasticsearch.search.sort.SortOrder; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; + +import java.io.IOException; +import java.text.SimpleDateFormat; +import java.util.*; +import java.util.stream.Collectors; + +import static org.dubhe.biz.base.constant.MagicNumConstant.ZERO; +import static org.dubhe.biz.base.constant.MagicNumConstant.*; +import static org.dubhe.biz.base.constant.SymbolConstant.*; + + +/** + * @description k8s集群日志查询接口 + * @date 2020-06-29 + */ +public class LogMonitoringApiImpl implements LogMonitoringApi { + @Value("${k8s.elasticsearch.log.source_field}") + private String sourceField; + + @Value("${k8s.elasticsearch.log.type}") + private String type; + + @Autowired + private RestHighLevelClient restHighLevelClient; + + @Autowired + private ResourceCache resourceCache; + + private KubernetesClient kubernetesClient; + private static final String INDEX_NAME = "kubelogs"; + private static final String POD_NAME_KEY = "kubernetes.pod_name.keyword"; + private static final String POD_NAME = "kubernetes.pod_name"; + private static final String NAMESPACE_KEY = "kubernetes.namespace_name.keyword"; + private static final String NAMESPACE = "kubernetes.namespace_name"; + private static final String TIMESTAMP = "@timestamp"; + private static final String MESSAGE = "log"; + private static final String LOG_PREFIX = "[Dubhe Service Log] "; + private static final String INDEX_FORMAT = "yyyy.MM.dd"; + + public LogMonitoringApiImpl(K8sUtils k8sUtils) { + this.kubernetesClient = k8sUtils.getClient(); + } + + + /** + * 添加Pod日志到ES,无日志参数,默认从k8s集群查询日志添加到ES + * + * @param podName Pod名称 + * @param namespace 命名空间 + * @return boolean 日志添加是否成功 + */ + @Override + public boolean addLogsToEs(String podName, String namespace) { + + if (StringUtils.isBlank(podName) || StringUtils.isBlank(namespace)) { + LogUtil.error(LogEnum.BIZ_K8S, "LogMonitoringApiImpl.addLogsToEs error: param [podName] and [namespace] are required"); + return false; + } + List logList = searchLogInfoByEs(ZERO, ONE, new LogMonitoringBO(namespace,podName)); + if (CollectionUtils.isNotEmpty(logList)) { + return true; + } + + String logInfoString = getLogInfoString(podName, namespace); + if (StringUtils.isBlank(logInfoString)) { + LogUtil.info(LogEnum.BIZ_K8S, "LogMonitoringApiImpl.getLogInfoString could not get any log,no doc created in Elasticsearch"); + return false; + } + logList = Arrays.asList(logInfoString.split(LINEBREAK)).stream().limit(TEN_THOUSAND).collect(Collectors.toList()); + return addLogsToEs(podName, namespace, logList); + } + + /** + * 添加Pod自定义日志到ES + * + * @param podName Pod名称 + * @param namespace 命名空间 + * @param logList 日志信息 + * @return boolean 日志添加是否成功 + */ + @Override + public boolean addLogsToEs(String podName, String namespace, List logList) { + Date date = new Date(); + SimpleDateFormat indexFormat = new SimpleDateFormat(INDEX_FORMAT); + String timestamp = TimeTransferUtil.dateTransferToUtc(date); + BulkRequest bulkRequest = new BulkRequest(); + try { + for (int i = 0; i < logList.size(); i++) { + /**准备日志json数据**/ + String logString = logList.get(i); + LinkedHashMap jsonMap = new LinkedHashMap() {{ + put(POD_NAME, podName); + put(NAMESPACE, namespace); + put(MESSAGE, logString); + put(TIMESTAMP, timestamp); + }}; + + /**添加索引创建对象到bulkRequest**/ + bulkRequest.add(new IndexRequest(INDEX_NAME).source(jsonMap)); + } + + /**通过restHighLevelClient发送http的请求批量创建文档**/ + restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT); + } catch (IOException e) { + LogUtil.error(LogEnum.BIZ_K8S, "LogMonitoringApi.addLogsToEs error:{}", e); + return false; + } + return true; + } + + /** + * 日志查询方法 + * + * @param from 日志查询起始值,初始值为1,表示从第一条日志记录开始查询 + * @param size 日志查询记录数 + * @param logMonitoringBo 日志查询bo + * @return LogMonitoringVO 日志查询结果类 + */ + @Override + public LogMonitoringVO searchLogByResName(int from, int size, LogMonitoringBO logMonitoringBo) { + List logList = new ArrayList<>(); + LogMonitoringVO logMonitoringResult = new LogMonitoringVO(ZERO_LONG, logList); + String namespace = logMonitoringBo.getNamespace(); + String resourceName = logMonitoringBo.getResourceName(); + if (StringUtils.isBlank(resourceName) || StringUtils.isBlank(namespace)) { + LogUtil.error(LogEnum.BIZ_K8S, "LogMonitoringApiImpl.searchLogByResName error: param [resourceName] and [namespace] are required"); + return logMonitoringResult; + } + + Set podNameSet = resourceCache.getPodNameByResourceName(logMonitoringBo.getNamespace(), logMonitoringBo.getResourceName()); + + if (CollectionUtils.isEmpty(podNameSet)) { + return logMonitoringResult; + } + /**遍历podNameSet,根据podName查询日志信息**/ + for (String podName : podNameSet) { + logMonitoringBo.setPodName(podName); + + /**查询ES存储的日志信息**/ + List logs = searchLogInfoByEs(from, size, logMonitoringBo); + + if (!CollectionUtils.isEmpty(logs)) { + logList.addAll(MagicNumConstant.ZERO, logs); + } + } + + logMonitoringResult.setLogs(logList); + logMonitoringResult.setTotalLogs(Long.valueOf(logList.size())); + return logMonitoringResult; + } + + /** + * 日志查询方法 + * + * @param from 日志查询起始值,初始值为1,表示从第一条日志记录开始查询 + * @param size 日志查询记录数 + * @param logMonitoringBo 日志查询bo + * @return LogMonitoringVO 日志查询结果类 + */ + @Override + public LogMonitoringVO searchLogByPodName(int from, int size, LogMonitoringBO logMonitoringBo) { + LogMonitoringVO logMonitoringResult = new LogMonitoringVO(); + List logs = searchLogInfoByEs(from, size, logMonitoringBo); + logMonitoringResult.setLogs(logs); + logMonitoringResult.setTotalLogs(Long.valueOf(logs.size())); + return logMonitoringResult; + + } + + /** + * Pod 日志总量查询方法 + * + * @param logMonitoringBo 日志查询bo + * @return long Pod 产生的日志总量 + */ + @Override + public long searchLogCountByPodName(LogMonitoringBO logMonitoringBo) { + SearchRequest searchRequest = buildSearchRequest(ZERO, ZERO, logMonitoringBo); + try { + /**执行搜索,获得响应结果**/ + return restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT).getHits().getTotalHits().value; + } catch (Exception e) { + LogUtil.error(LogEnum.BIZ_K8S, "LogMonitoringApiImpl.searchLogCountByPodName error,param:[logMonitoringBo]={}, error:{}", JSON.toJSONString(logMonitoringBo), e); + return ZERO_LONG; + } + } + + /** + * 得到日志信息String + * + * @param podName Pod名称 + * @param namespace 命名空间 + * @return String 所有日志 + */ + private String getLogInfoString(String podName, String namespace) { + PodResource podResource = kubernetesClient.pods().inNamespace(namespace).withName(podName); + Pod pod = podResource.get(); + if (pod != null) { + /**通过k8s客户端获取具体pod的日志监听类**/ + try { + return podResource.getLog(); + } catch (Exception e) { + LogUtil.error(LogEnum.BIZ_K8S, "LogMonitoringApi.getLogInfoString error, param:[podName]={}, [namespace]={}, error:{}", podName, namespace, e); + } + } + return null; + } + + + /** + * 从Elasticsearch查询日志 + * + * @param from 日志查询起始值 + * @param size 日志查询记录数 + * @param logMonitoringBo 日志查询bo + * @return List 日志集合 + */ + private List searchLogInfoByEs(int from, int size, LogMonitoringBO logMonitoringBo) { + + List logList = new ArrayList<>(); + + SearchRequest searchRequest = buildSearchRequest(from, size, logMonitoringBo); + /**执行搜索**/ + SearchResponse searchResponse; + try { + searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT); + } catch (Exception e) { + LogUtil.error(LogEnum.BIZ_K8S, "LogMonitoringApiImpl.searchLogInfoByEs error,param:[logMonitoringBo]={}, error:{}", JSON.toJSONString(logMonitoringBo), e); + return logList; + } + /**获取响应结果**/ + SearchHits hits = searchResponse.getHits(); + + SearchHit[] searchHits = hits.getHits(); + if (searchHits.length == MagicNumConstant.ZERO) { + return logList; + } + + for (SearchHit hit : searchHits) { + /**源文档**/ + Map sourceAsMap = hit.getSourceAsMap(); + /**取出message**/ + String message = (String) sourceAsMap.get(MESSAGE); + message = message.replace(LINEBREAK, BLANK); + + /**拼接日志信息**/ + String logString = LOG_PREFIX + message; + /**添加日志信息到集合**/ + logList.add(logString); + } + return logList; + } + + /** + * 构建搜索请求对象 + * + * @param from 日志查询起始值 + * @param size 日志查询记录数 + * @param logMonitoringBo 日志查询bo + * @return SearchRequest ES搜索请求对象 + */ + private SearchRequest buildSearchRequest(int from, int size, LogMonitoringBO logMonitoringBo) { + + /**处理查询范围参数起始值**/ + from = from <= MagicNumConstant.ZERO ? MagicNumConstant.ZERO : --from; + size = size <= MagicNumConstant.ZERO || size > TEN_THOUSAND ? TEN_THOUSAND : size; + + /**创建搜索请求对象**/ + SearchRequest searchRequest = new SearchRequest(); + searchRequest.indices(INDEX_NAME); + SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); + searchSourceBuilder.trackTotalHits(true).from(from).size(size); + + /**根据时间戳排序**/ + searchSourceBuilder.sort(TIMESTAMP, SortOrder.ASC); + /**过虑源字段**/ + String[] sourceFieldArray = sourceField.split(COMMA); + + searchSourceBuilder.fetchSource(sourceFieldArray, new String[]{}); + + /**创建布尔查询对象**/ + BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); + + /**添加podName查询条件**/ + String podName = logMonitoringBo.getPodName(); + if (StringUtils.isNotEmpty(podName)) { + boolQueryBuilder.filter(QueryBuilders.matchQuery(POD_NAME_KEY, podName)); + } + /**添加namespace查询条件**/ + String namespace = logMonitoringBo.getNamespace(); + if (StringUtils.isNotEmpty(namespace)) { + boolQueryBuilder.filter(QueryBuilders.matchQuery(NAMESPACE_KEY, namespace)); + } + /**添加关键字查询条件**/ + String logKeyword = logMonitoringBo.getLogKeyword(); + if (StringUtils.isNotEmpty(logKeyword)) { + boolQueryBuilder.filter(QueryBuilders.matchQuery(MESSAGE, logKeyword).operator(Operator.AND)); + } + /**添加时间范围查询条件**/ + Long beginTimeMillis = logMonitoringBo.getBeginTimeMillis(); + Long endTimeMillis = logMonitoringBo.getEndTimeMillis(); + if (beginTimeMillis != null || endTimeMillis != null){ + beginTimeMillis = beginTimeMillis == null ? ZERO_LONG : beginTimeMillis; + endTimeMillis = endTimeMillis == null ? System.currentTimeMillis() : endTimeMillis; + + /**将毫秒值转换为UTC时间**/ + String beginUtcTime = TimeTransferUtil.dateTransferToUtc(new Date(beginTimeMillis)); + String endUtcTime = TimeTransferUtil.dateTransferToUtc(new Date(endTimeMillis)); + boolQueryBuilder.filter(QueryBuilders.rangeQuery(TIMESTAMP).gte(beginUtcTime).lte(endUtcTime)); + } + + + /**设置boolQueryBuilder到searchSourceBuilder**/ + searchSourceBuilder.query(boolQueryBuilder); + + return searchRequest.source(searchSourceBuilder); + } + +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/impl/MetricsApiImpl.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/impl/MetricsApiImpl.java new file mode 100644 index 0000000..b4f1e9d --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/impl/MetricsApiImpl.java @@ -0,0 +1,498 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.api.impl; + +import cn.hutool.core.util.NumberUtil; +import cn.hutool.core.util.StrUtil; +import io.fabric8.kubernetes.api.model.Quantity; +import io.fabric8.kubernetes.api.model.metrics.v1beta1.ContainerMetrics; +import io.fabric8.kubernetes.api.model.metrics.v1beta1.NodeMetricsList; +import io.fabric8.kubernetes.api.model.metrics.v1beta1.PodMetrics; +import io.fabric8.kubernetes.api.model.metrics.v1beta1.PodMetricsList; +import io.fabric8.kubernetes.client.KubernetesClient; +import io.fabric8.kubernetes.client.KubernetesClientException; +import org.dubhe.biz.base.constant.MagicNumConstant; +import org.dubhe.biz.base.constant.SymbolConstant; +import org.dubhe.biz.base.functional.StringFormat; +import org.dubhe.biz.base.utils.StringUtils; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.dubhe.k8s.api.MetricsApi; +import org.dubhe.k8s.api.PodApi; +import org.dubhe.k8s.constant.K8sParamConstants; +import org.dubhe.k8s.domain.bo.PrometheusMetricBO; +import org.dubhe.k8s.domain.dto.PodQueryDTO; +import org.dubhe.k8s.domain.resource.BizContainer; +import org.dubhe.k8s.domain.resource.BizPod; +import org.dubhe.k8s.domain.resource.BizQuantity; +import org.dubhe.k8s.domain.vo.PodRangeMetricsVO; +import org.dubhe.k8s.domain.vo.PtContainerMetricsVO; +import org.dubhe.k8s.domain.vo.PtNodeMetricsVO; +import org.dubhe.k8s.domain.vo.PtPodsVO; +import org.dubhe.k8s.utils.BizConvertUtils; +import org.dubhe.k8s.utils.K8sUtils; +import org.dubhe.k8s.utils.PrometheusUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.util.CollectionUtils; + +import java.util.*; +import java.util.stream.Collectors; + +/** + * @description metrics api + * @date 2020-05-22 + */ +public class MetricsApiImpl implements MetricsApi { + private KubernetesClient client; + + @Autowired + private PodApi podApi; + /** + * prometheus 地址 + */ + @Value("${k8s.prometheus.url}") + private String k8sPrometheusUrl; + /** + * prometheus 查询接口 + */ + @Value("${k8s.prometheus.query}") + private String k8sPrometheusQuery; + /** + * prometheus 范围查询接口 + */ + @Value("${k8s.prometheus.query-range}") + private String k8sPrometheusQueryRange; + /** + * prometheus gpu指标查询参数 + */ + @Value("${k8s.prometheus.gpu-query-param}") + private String k8sPrometheusGpuQueryParam; + /** + * prometheus cpu指标范围查询参数 + */ + @Value("${k8s.prometheus.cpu-range-query-param}") + private String k8sPrometheusCpuRangeQueryParam; + /** + * prometheus 内存指标范围查询参数 + */ + @Value("${k8s.prometheus.mem-range-query-param}") + private String k8sPrometheusMemRangeQueryParam; + /** + * prometheus gpu指标范围查询参数 + */ + @Value("${k8s.prometheus.gpu-range-query-param}") + private String k8sPrometheusGpuRangeQueryParam; + + public MetricsApiImpl(K8sUtils k8sUtils) { + this.client = k8sUtils.getClient(); + } + + /** + * 获取k8s所有节点当前cpu、内存用量 + * + * @return List NodeMetrics 结果类集合 + */ + @Override + public List getNodeMetrics() { + try { + List list = new ArrayList<>(); + NodeMetricsList nodeMetricList = client.top().nodes().metrics(); + nodeMetricList.getItems().forEach(nodeMetrics -> + list.add(new PtNodeMetricsVO(nodeMetrics.getMetadata().getName(), + nodeMetrics.getTimestamp(), + nodeMetrics.getUsage().get(K8sParamConstants.QUANTITY_CPU_KEY).getAmount(), + nodeMetrics.getUsage().get(K8sParamConstants.QUANTITY_CPU_KEY).getFormat(), + nodeMetrics.getUsage().get(K8sParamConstants.QUANTITY_MEMORY_KEY).getAmount(), + nodeMetrics.getUsage().get(K8sParamConstants.QUANTITY_MEMORY_KEY).getFormat() + )) + ); + return list; + } catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "MetricsApiImpl.getNodeMetrics error:{}", e); + return Collections.EMPTY_LIST; + } + } + + /** + * 获取k8s所有Pod资源用量的实时信息 + * + * @return List Pod资源用量结果类集合 + */ + @Override + public List getPodsMetricsRealTime() { + /**查询所有pod的信息一些信息**/ + PodMetricsList metrics = client.top().pods().metrics(); + List list = new ArrayList<>(); + /**将Pod和podName形成映射关系**/ + Map> listMap = client.pods().inAnyNamespace().list().getItems().parallelStream().map(obj -> BizConvertUtils.toBizPod(obj)).collect(Collectors.groupingBy(BizPod::getName)); + if(null == listMap) { + return list; + } + metrics.getItems().stream().forEach(metric -> { + /**创建集合保存PtPodsResult信息**/ + List containers = metric.getContainers(); + containers.stream().forEach(containerMetrics -> { + Map usage = containerMetrics.getUsage(); + PtPodsVO ptContainerMetricsResult = new PtPodsVO(metric.getMetadata().getNamespace(),metric.getMetadata().getName(), + usage.get(K8sParamConstants.QUANTITY_CPU_KEY).getAmount(), + usage.get(K8sParamConstants.QUANTITY_CPU_KEY).getFormat(), + usage.get(K8sParamConstants.QUANTITY_MEMORY_KEY).getAmount(), + usage.get(K8sParamConstants.QUANTITY_MEMORY_KEY).getFormat(), + listMap.get(metric.getMetadata().getName()).get(0).getNodeName(), + listMap.get(metric.getMetadata().getName()).get(0).getPhase(), null); + + List containerList = listMap.get(metric.getMetadata().getName()).get(0).getContainers(); + countGpuUsed(containerList,ptContainerMetricsResult); + list.add(ptContainerMetricsResult); + }); + }); + return list; + } + + /** + * 获取k8s所有pod当前cpu、内存用量的实时使用情况 + * + * @return List Pod资源用量结果类集合 + */ + @Override + public List getPodMetricsRealTime() { + try { + List list = new ArrayList<>(); + Map podNode = new HashMap<>(); + PodMetricsList metrics = client.top().pods().metrics(); + List bizPodList = client.pods().inAnyNamespace().list().getItems().parallelStream().map(obj -> BizConvertUtils.toBizPod(obj)).collect(Collectors.toList()); + bizPodList.stream().forEach(bizPod -> podNode.put(bizPod.getName(), bizPod.getNodeName())); + metrics.getItems().stream().forEach(metric -> { + for (BizPod bizPod : bizPodList) { + if (bizPod.getName().equals(metric.getMetadata().getName())) { + List containers = metric.getContainers(); + containers.stream().forEach(containerMetrics -> + { + Map usage = containerMetrics.getUsage(); + PtPodsVO ptContainerMetricsResult = new PtPodsVO(metric.getMetadata().getNamespace(),metric.getMetadata().getName(), + usage.get(K8sParamConstants.QUANTITY_CPU_KEY).getAmount(), + usage.get(K8sParamConstants.QUANTITY_CPU_KEY).getFormat(), + usage.get(K8sParamConstants.QUANTITY_MEMORY_KEY).getAmount(), + usage.get(K8sParamConstants.QUANTITY_MEMORY_KEY).getFormat(), + podNode.get(metric.getMetadata().getName()), + bizPod.getPhase(), null + ); + List containerList = bizPod.getContainers(); + countGpuUsed(containerList,ptContainerMetricsResult); + list.add(ptContainerMetricsResult); + }); + } + } + + }); + + return list; + } catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "MetricsApiImpl.getPodMetricsRealTime error:{}", e); + return Collections.EMPTY_LIST; + } + } + + /** + * 计算GPU使用数量 + * + * @param containerList BizContainer对象 + * @param ptContainerMetricsResult 封装pod信息 + */ + private void countGpuUsed(List containerList,PtPodsVO ptContainerMetricsResult){ + for (BizContainer container : containerList) { + Map limits = container.getLimits(); + if (limits == null) { + ptContainerMetricsResult.setGpuUsed(SymbolConstant.ZERO); + } else { + BizQuantity bizQuantity = limits.get(K8sParamConstants.GPU_RESOURCE_KEY); + String count = bizQuantity != null ? bizQuantity.getAmount() : SymbolConstant.ZERO; + /**将显卡数量保存起来**/ + ptContainerMetricsResult.setGpuUsed(count); + } + } + } + + /** + * 获取k8s resourceName 下pod当前cpu、内存用量的实时使用情况 + * @param namespace 命名空间 + * @param resourceName 资源名称 + * @return List Pod资源用量结果类集合 + */ + @Override + public List getPodMetricsRealTime(String namespace, String resourceName) { + List ptPodsVOS = new ArrayList<>(); + if (StringUtils.isEmpty(namespace) || StringUtils.isEmpty(resourceName)){ + return ptPodsVOS; + } + List pods = podApi.getListByResourceName(namespace,resourceName); + if (CollectionUtils.isEmpty(pods)){ + return ptPodsVOS; + } + List podMetricsList = client.top().pods().metrics(namespace).getItems(); + if (!CollectionUtils.isEmpty(pods)){ + Map podMetricsMap = podMetricsList.stream().collect(Collectors.toMap(obj -> obj.getMetadata().getName(), obj -> obj)); + for (BizPod pod : pods){ + List ptPodsVOList = getPtPodsVO(pod,podMetricsMap.get(pod.getName())); + if (!CollectionUtils.isEmpty(ptPodsVOList)){ + ptPodsVOS.addAll(ptPodsVOList); + } + } + } + for (PtPodsVO ptPodsVO : ptPodsVOS){ + generateGpuUsage(ptPodsVO); + ptPodsVO.calculationPercent(); + } + return ptPodsVOS; + } + + /** + * 获取k8s pod当前cpu、内存用量的实时使用情况 + * @param namespace 命名空间 + * @param podName pod名称 + * @return List Pod资源用量结果类集合 + */ + @Override + public List getPodMetricsRealTimeByPodName(String namespace, String podName) { + List ptPodsVOS = new ArrayList<>(); + if (StringUtils.isEmpty(namespace) || StringUtils.isEmpty(podName)){ + return ptPodsVOS; + } + BizPod pod = podApi.get(namespace,podName); + if (null == pod){ + return ptPodsVOS; + } + PodMetrics podMetrics = null; + try{ + podMetrics = client.top().pods().metrics(namespace,podName); + }catch (KubernetesClientException e){ + LogUtil.error(LogEnum.BIZ_K8S, "MetricsApiImpl.getPodMetricsRealTimeByPodName error:{}", e); + } + ptPodsVOS = getPtPodsVO(pod,podMetrics); + for (PtPodsVO ptPodsVO : ptPodsVOS){ + generateGpuUsage(ptPodsVO); + ptPodsVO.calculationPercent(); + } + return ptPodsVOS; + } + + /** + * 获取k8s pod当前cpu、内存用量的实时使用情况 + * @param namespace 命名空间 + * @param podNames pod名称列表 + * @return List Pod资源用量结果类集合 + */ + @Override + public List getPodMetricsRealTimeByPodName(String namespace, List podNames) { + List ptPodsVOS = new ArrayList<>(); + for (String podName : podNames){ + ptPodsVOS.addAll(getPodMetricsRealTimeByPodName(namespace,podName)); + } + return ptPodsVOS; + } + + /** + * 获取k8s resourceName 下pod 时间范围内cpu、内存用量的实时使用情况 + * @param podQueryDTO Pod基础信息查询入参 + * @return List Pod监控指标 列表 + */ + @Override + public List getPodRangeMetrics(PodQueryDTO podQueryDTO) { + List podRangeMetricsVOS = new ArrayList<>(); + if (StringUtils.isEmpty(podQueryDTO.getNamespace()) || StringUtils.isEmpty(podQueryDTO.getResourceName())){ + return podRangeMetricsVOS; + } + List pods = podApi.getListByResourceName(podQueryDTO.getNamespace(),podQueryDTO.getResourceName()); + if (CollectionUtils.isEmpty(pods)){ + return podRangeMetricsVOS; + } + podQueryDTO.generateDefaultParam(); + for (BizPod pod : pods){ + podRangeMetricsVOS.add(getPodRangeMetricsVO(pod,podQueryDTO)); + } + return podRangeMetricsVOS; + } + + /** + * 根据namespace、podName获取k8s pod 时间范围内cpu、内存用量的实时使用情况 + * @param podQueryDTO Pod基础信息查询入参 + * @return List Pod监控指标 列表 + */ + @Override + public List getPodRangeMetricsByPodName(PodQueryDTO podQueryDTO) { + List podRangeMetricsVOS = new ArrayList<>(); + if (StringUtils.isEmpty(podQueryDTO.getNamespace()) || CollectionUtils.isEmpty(podQueryDTO.getPodNames())){ + return podRangeMetricsVOS; + } + List pods = podApi.get(podQueryDTO.getNamespace(),podQueryDTO.getPodNames()); + if (null == pods){ + return podRangeMetricsVOS; + } + podQueryDTO.generateDefaultParam(); + for (BizPod pod : pods){ + podRangeMetricsVOS.add(getPodRangeMetricsVO(pod,podQueryDTO)); + } + return podRangeMetricsVOS; + } + + /** + * 组装Pod历史监控指标 + * + * @param pod pod业务类 + * @param podQueryDTO 查询参数 + * @return PodRangeMetricsVO Pod历史监控指标 VO + */ + private PodRangeMetricsVO getPodRangeMetricsVO(BizPod pod,PodQueryDTO podQueryDTO){ + PodRangeMetricsVO podRangeMetricsVO = new PodRangeMetricsVO(pod.getName()); + PrometheusMetricBO cpuRangeMetrics = PrometheusUtil.getQuery(k8sPrometheusUrl+k8sPrometheusQueryRange,PrometheusUtil.getQueryParamMap(k8sPrometheusCpuRangeQueryParam,pod.getName(),podQueryDTO)); + PrometheusMetricBO memRangeMetrics = PrometheusUtil.getQuery(k8sPrometheusUrl+k8sPrometheusQueryRange,PrometheusUtil.getQueryParamMap(k8sPrometheusMemRangeQueryParam,pod.getName(),podQueryDTO)); + PrometheusMetricBO gpuRangeMetrics = PrometheusUtil.getQuery(k8sPrometheusUrl+k8sPrometheusQueryRange,PrometheusUtil.getQueryParamMap(k8sPrometheusGpuRangeQueryParam,pod.getName(),podQueryDTO)); + + StringFormat cpuMetricsFormat = (value)->{ + return value == null ? String.valueOf(MagicNumConstant.ZERO) : NumberUtil.round(Double.valueOf(value.toString()), MagicNumConstant.TWO).toString(); + }; + podRangeMetricsVO.setCpuMetrics(cpuRangeMetrics.getValues(cpuMetricsFormat)); + + StringFormat memMetricsFormat = (value)->{ + return NumberUtil.isNumber(String.valueOf(value)) ? String.valueOf(Long.valueOf(String.valueOf(value)) / MagicNumConstant.BINARY_TEN_EXP) : String.valueOf(MagicNumConstant.ZERO); + }; + podRangeMetricsVO.setMemoryMetrics(memRangeMetrics.getValues(memMetricsFormat)); + podRangeMetricsVO.setGpuMetrics(gpuRangeMetrics.getResults()); + return podRangeMetricsVO; + } + + /** + * 查询Gpu使用率 + * @param ptPodsVO pod信息 + */ + private void generateGpuUsage(PtPodsVO ptPodsVO){ + PrometheusMetricBO prometheusMetricBO = PrometheusUtil.getQuery(k8sPrometheusUrl+k8sPrometheusQuery, PrometheusUtil.getQueryParamMap(k8sPrometheusGpuQueryParam,ptPodsVO.getPodName())); + if (prometheusMetricBO == null){ + return; + } + ptPodsVO.setGpuUsagePersent(prometheusMetricBO.getGpuUsage()); + } + + /** + * assemble PtPodsVO + * @param bizPod pod + * @param metric 查询指标 + * @return List pod信息列表 + */ + private List getPtPodsVO(BizPod bizPod,PodMetrics metric){ + List ptPodsVOList = new ArrayList<>(); + if (metric == null){ + return ptPodsVOList; + } + Map containerMetricsMap = metric.getContainers().stream().collect(Collectors.toMap(obj -> obj.getName(), obj -> obj)); + for (BizContainer container : bizPod.getContainers()){ + Map request = container.getRequests(); + if (containerMetricsMap.get(container.getName()) == null){ + continue; + } + Map usage = containerMetricsMap.get(container.getName()).getUsage(); + PtPodsVO ptContainerMetricsResult = new PtPodsVO(metric.getMetadata().getNamespace(),metric.getMetadata().getName(), + request.get(K8sParamConstants.QUANTITY_CPU_KEY) ==null ? null : request.get(K8sParamConstants.QUANTITY_CPU_KEY).getAmount(), + usage.get(K8sParamConstants.QUANTITY_CPU_KEY).getAmount(), + request.get(K8sParamConstants.QUANTITY_CPU_KEY) ==null ? null : request.get(K8sParamConstants.QUANTITY_CPU_KEY).getFormat(), + usage.get(K8sParamConstants.QUANTITY_CPU_KEY).getFormat(), + request.get(K8sParamConstants.QUANTITY_MEMORY_KEY) == null ? null : request.get(K8sParamConstants.QUANTITY_MEMORY_KEY).getAmount(), + usage.get(K8sParamConstants.QUANTITY_MEMORY_KEY).getAmount(), + request.get(K8sParamConstants.QUANTITY_MEMORY_KEY) == null ? null : request.get(K8sParamConstants.QUANTITY_MEMORY_KEY).getFormat(), + usage.get(K8sParamConstants.QUANTITY_MEMORY_KEY).getFormat(), + bizPod.getNodeName(), + bizPod.getPhase(), null + ); + + Map limits = container.getLimits(); + if (limits == null) { + ptContainerMetricsResult.setGpuUsed(SymbolConstant.ZERO); + } else { + BizQuantity bizQuantity = limits.get(K8sParamConstants.GPU_RESOURCE_KEY); + String count = bizQuantity != null ? bizQuantity.getAmount() : SymbolConstant.ZERO; + /**将显卡数量保存起来**/ + ptContainerMetricsResult.setGpuUsed(count); + } + ptPodsVOList.add(ptContainerMetricsResult); + }; + + return ptPodsVOList; + } + + /** + * 查询命名空间下所有Pod的cpu和内存使用 + * + * @param namespace 命名空间 + * @return List Pod资源用量结果类集合 + */ + @Override + public List getContainerMetrics(String namespace) { + if(StringUtils.isEmpty(namespace)){ + return Collections.EMPTY_LIST; + } + try { + return getContainerMetrics(client.top().pods().metrics(namespace).getItems()); + } catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "MetricsApiImpl.getContainerMetrics error:{}", e); + return Collections.EMPTY_LIST; + } + } + + /** + * 查询所有命名空间下所有pod的cpu和内存使用 + * + * @return List Pod资源用量结果类集合 + */ + @Override + public List getContainerMetrics() { + try { + return getContainerMetrics(client.top().pods().metrics().getItems()); + } catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "MetricsApiImpl.getContainerMetrics error:{}", e); + return Collections.EMPTY_LIST; + } + } + + /** + * 查询所有命名空间下所有pod的cpu和内存使用 + * + * @param pods + * @return List Pod资源用量结果类集合 + */ + private List getContainerMetrics(List pods) { + try { + List list = new ArrayList<>(); + pods.forEach(podMetrics -> + podMetrics.getContainers().forEach(containerMetrics -> + list.add(new PtContainerMetricsVO(podMetrics.getMetadata().getName(), + containerMetrics.getName(), + podMetrics.getTimestamp(), + containerMetrics.getUsage().get(K8sParamConstants.QUANTITY_CPU_KEY).getAmount(), + containerMetrics.getUsage().get(K8sParamConstants.QUANTITY_CPU_KEY).getFormat(), + containerMetrics.getUsage().get(K8sParamConstants.QUANTITY_MEMORY_KEY).getAmount(), + containerMetrics.getUsage().get(K8sParamConstants.QUANTITY_MEMORY_KEY).getFormat())) + ) + ); + return list; + } catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "MetricsApiImpl.getContainerMetrics error, param:{} error:{}", pods, e); + return Collections.EMPTY_LIST; + } + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/impl/ModelOptJobApiImpl.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/impl/ModelOptJobApiImpl.java new file mode 100644 index 0000000..acd5939 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/impl/ModelOptJobApiImpl.java @@ -0,0 +1,432 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.api.impl; + +import cn.hutool.core.collection.CollectionUtil; +import cn.hutool.core.util.RandomUtil; +import cn.hutool.core.util.StrUtil; +import com.google.common.collect.Maps; +import io.fabric8.kubernetes.api.model.Container; +import io.fabric8.kubernetes.api.model.ContainerBuilder; +import io.fabric8.kubernetes.api.model.Quantity; +import io.fabric8.kubernetes.api.model.Volume; +import io.fabric8.kubernetes.api.model.VolumeBuilder; +import io.fabric8.kubernetes.api.model.VolumeMount; +import io.fabric8.kubernetes.api.model.VolumeMountBuilder; +import io.fabric8.kubernetes.api.model.batch.Job; +import io.fabric8.kubernetes.api.model.batch.JobBuilder; +import io.fabric8.kubernetes.api.model.batch.JobList; +import io.fabric8.kubernetes.client.KubernetesClient; +import io.fabric8.kubernetes.client.KubernetesClientException; +import org.dubhe.biz.base.constant.MagicNumConstant; +import org.dubhe.biz.base.constant.SymbolConstant; +import org.dubhe.biz.base.utils.StringUtils; +import org.dubhe.biz.file.api.FileStoreApi; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.dubhe.k8s.api.ModelOptJobApi; +import org.dubhe.k8s.api.NodeApi; +import org.dubhe.k8s.api.PersistentVolumeClaimApi; +import org.dubhe.k8s.api.ResourceIisolationApi; +import org.dubhe.k8s.api.ResourceQuotaApi; +import org.dubhe.k8s.constant.K8sLabelConstants; +import org.dubhe.k8s.constant.K8sParamConstants; +import org.dubhe.k8s.domain.PtBaseResult; +import org.dubhe.k8s.domain.bo.PtModelOptimizationJobBO; +import org.dubhe.k8s.domain.bo.PtMountDirBO; +import org.dubhe.k8s.domain.bo.PtPersistentVolumeClaimBO; +import org.dubhe.k8s.domain.resource.BizJob; +import org.dubhe.k8s.domain.resource.BizPersistentVolumeClaim; +import org.dubhe.k8s.enums.ImagePullPolicyEnum; +import org.dubhe.k8s.enums.K8sKindEnum; +import org.dubhe.k8s.enums.K8sResponseEnum; +import org.dubhe.k8s.enums.LackOfResourcesEnum; +import org.dubhe.k8s.enums.LimitsOfResourcesEnum; +import org.dubhe.k8s.enums.RestartPolicyEnum; +import org.dubhe.k8s.enums.ShellCommandEnum; +import org.dubhe.k8s.utils.BizConvertUtils; +import org.dubhe.k8s.utils.K8sUtils; +import org.dubhe.k8s.utils.LabelUtils; +import org.dubhe.k8s.utils.YamlUtils; +import org.springframework.beans.factory.annotation.Autowired; + +import javax.annotation.Resource; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; + +/** + * @description ModelOptJobApi 实现类 + * @date 2020-05-29 + */ +public class ModelOptJobApiImpl implements ModelOptJobApi { + private K8sUtils k8sUtils; + private KubernetesClient client; + + @Resource(name = "hostFileStoreApiImpl") + private FileStoreApi fileStoreApi; + @Autowired + private NodeApi nodeApi; + @Autowired + private PersistentVolumeClaimApi persistentVolumeClaimApi; + @Autowired + private ResourceQuotaApi resourceQuotaApi; + @Autowired + private ResourceIisolationApi resourceIisolationApi; + + public ModelOptJobApiImpl(K8sUtils k8sUtils) { + this.k8sUtils = k8sUtils; + this.client = k8sUtils.getClient(); + } + + /** + * 创建模型优化 Job + * + * @param bo 模型优化 Job BO + * @return BizJob Job 业务类 + */ + @Override + public BizJob create(PtModelOptimizationJobBO bo) { + try { + LimitsOfResourcesEnum limitsOfResources = resourceQuotaApi.reachLimitsOfResources(bo.getNamespace(), bo.getCpuNum(), bo.getMemNum(), bo.getGpuNum()); + if (!LimitsOfResourcesEnum.ADEQUATE.equals(limitsOfResources)) { + return new BizJob().error(K8sResponseEnum.LACK_OF_RESOURCES.getCode(), limitsOfResources.getMessage()); + } + LackOfResourcesEnum lack = nodeApi.isAllocatable(bo.getCpuNum(), bo.getMemNum(), bo.getGpuNum()); + if (!LackOfResourcesEnum.ADEQUATE.equals(lack)) { + return new BizJob().error(K8sResponseEnum.LACK_OF_RESOURCES.getCode(), lack.getMessage()); + } + LogUtil.info(LogEnum.BIZ_K8S, "Params of creating Job--create:{}", bo); + if (!fileStoreApi.createDirs(bo.getDirList().toArray(new String[MagicNumConstant.ZERO]))) { + return new BizJob().error(K8sResponseEnum.INTERNAL_SERVER_ERROR.getCode(), K8sResponseEnum.INTERNAL_SERVER_ERROR.getMessage()); + } + BizJob result = new JobDeployer(bo).buildVolumes().deploy(); + LogUtil.info(LogEnum.BIZ_K8S, "Return value of creating Job--create:{}", result); + return result; + } catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "ModelOptJobApiImpl.create error, param:{} error:{}", bo, e); + return new BizJob().error(String.valueOf(e.getCode()), e.getMessage()); + } + } + + /** + * 通过命名空间和资源名称查找Job资源 + * + * @param namespace 命名空间 + * @param resourceName 资源名称 + * @return BizJob Job 业务类 + */ + @Override + public BizJob getWithResourceName(String namespace, String resourceName) { + if (StringUtils.isEmpty(namespace)) { + return new BizJob().baseErrorBadRequest(); + } + JobList bizJobList = client.batch().jobs().inNamespace(namespace).withLabels(LabelUtils.withEnvResourceName(resourceName)).list(); + if (CollectionUtil.isEmpty(bizJobList.getItems())) { + return new BizJob().error(K8sResponseEnum.NOT_FOUND.getCode(), K8sResponseEnum.NOT_FOUND.getMessage()); + } + Job job = bizJobList.getItems().get(0); + return BizConvertUtils.toBizJob(job); + } + + /** + * 通过命名空间查找Job资源 + * + * @param namespace 命名空间 + * @return List Job 业务类集合 + */ + @Override + public List getWithNamespace(String namespace) { + List bizJobList = new ArrayList<>(); + JobList jobList = client.batch().jobs().inNamespace(namespace).list(); + if (CollectionUtil.isEmpty(jobList.getItems())) { + return bizJobList; + } + return BizConvertUtils.toBizJobList(jobList.getItems()); + } + + /** + * 查询所有Job资源 + * + * @return List Job 业务类集合 + */ + @Override + public List listAll() { + return client.batch().jobs().inAnyNamespace().list() + .getItems().parallelStream().map(obj -> BizConvertUtils.toBizJob(obj)).collect(Collectors.toList()); + } + + /** + * 通过命名空间和资源名删除Job + * + * @param namespace 命名空间 + * @param resourceName 资源名称 + * @return PtBaseResult 基础结果类 + */ + @Override + public PtBaseResult deleteByResourceName(String namespace, String resourceName) { + LogUtil.info(LogEnum.BIZ_K8S, "Param of deleteByResourceName namespace {} resourceName {}", namespace,resourceName); + if (StringUtils.isEmpty(namespace) || StringUtils.isEmpty(resourceName)) { + return new PtBaseResult().baseErrorBadRequest(); + } + try { + client.batch().jobs().inNamespace(namespace).withLabels(LabelUtils.withEnvResourceName(resourceName)).delete(); + return new PtBaseResult(); + } catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "ModelOptJobApiImpl.deleteByResourceName error, param:[namespace]={}, [resourceName]={}, error:{}", namespace, resourceName, e); + return new PtBaseResult(String.valueOf(e.getCode()), e.getMessage()); + } + } + + private class JobDeployer { + private String baseName; + private String jobName; + + private String namespace; + private String image; + + private List cmdLines; + + private Map fsMounts; + + private Map resourcesLimitsMap; + private Map baseLabels; + private List volumeMounts; + private List volumes; + private String businessLabel; + private Integer gpuNum; + + private String errCode; + private String errMessage; + + private JobDeployer(PtModelOptimizationJobBO bo) { + this.baseName = bo.getName(); + this.jobName = StrUtil.format(K8sParamConstants.RESOURCE_NAME_TEMPLATE, baseName, RandomUtil.randomString(MagicNumConstant.EIGHT)); + this.namespace = bo.getNamespace(); + this.image = bo.getImage(); + this.cmdLines = new ArrayList(); + this.gpuNum = bo.getGpuNum(); + Optional.ofNullable(bo.getCmdLines()).ifPresent(v -> cmdLines = v); + + this.resourcesLimitsMap = Maps.newHashMap(); + Optional.ofNullable(bo.getCpuNum()).ifPresent(v -> resourcesLimitsMap.put(K8sParamConstants.QUANTITY_CPU_KEY, new Quantity(v.toString(), K8sParamConstants.CPU_UNIT))); + Optional.ofNullable(bo.getGpuNum()).ifPresent(v -> resourcesLimitsMap.put(K8sParamConstants.GPU_RESOURCE_KEY, new Quantity(v.toString()))); + Optional.ofNullable(bo.getMemNum()).ifPresent(v -> resourcesLimitsMap.put(K8sParamConstants.QUANTITY_MEMORY_KEY, new Quantity(v.toString(), K8sParamConstants.MEM_UNIT))); + this.businessLabel = bo.getBusinessLabel(); + this.fsMounts = bo.getFsMounts(); + this.baseLabels = LabelUtils.getBaseLabels(baseName, businessLabel); + + this.volumeMounts = new ArrayList<>(); + this.volumes = new ArrayList<>(); + this.errCode = K8sResponseEnum.SUCCESS.getCode(); + this.errMessage = SymbolConstant.BLANK; + } + + /** + * 部署Job + * + * @return BizJob Job业务类 + */ + public BizJob deploy() { + if (!K8sResponseEnum.SUCCESS.getCode().equals(errCode)) { + return new BizJob().error(errCode, errMessage); + } + //部署job + try { + Job job = deployJob(); + return BizConvertUtils.toBizJob(job); + } catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "ModelOptJobApiImpl.deploy error:{}", e); + return new BizJob().error(String.valueOf(e.getCode()), e.getMessage()); + } + } + + /** + * 挂载存储 + * + * @return JobDeployer Job 部署类 + */ + private JobDeployer buildVolumes() { + if (CollectionUtil.isNotEmpty(fsMounts)) { + int i = MagicNumConstant.ZERO; + for (Map.Entry mount : fsMounts.entrySet()) { + boolean availableMount = (mount != null && StringUtils.isNotEmpty(mount.getKey()) && mount.getValue() != null && StringUtils.isNotEmpty(mount.getValue().getDir())); + if (availableMount) { + boolean success = mount.getValue().isRecycle() ? buildFsPvcVolumes(mount.getKey(), mount.getValue(), i) : buildFsVolumes(mount.getKey(), mount.getValue(), i); + if (!success) { + break; + } + i++; + } + } + } + return this; + } + + /** + * 挂载存储 + * + * @param mountPath 挂载路径 + * @param dirBO 挂载路径参数 + * @param i 名称序号 + * @return boolean true成功 false失败 + */ + private boolean buildFsVolumes(String mountPath, PtMountDirBO dirBO, int i) { + volumeMounts.add(new VolumeMountBuilder() + .withName(K8sParamConstants.VOLUME_PREFIX + i) + .withMountPath(mountPath) + .withReadOnly(dirBO.isReadOnly()) + .build()); + volumes.add(new VolumeBuilder() + .withName(K8sParamConstants.VOLUME_PREFIX + i) + .withNewHostPath() + .withPath(dirBO.getDir()) + .withType(K8sParamConstants.HOST_PATH_TYPE) + .endHostPath() + .build()); + return true; + } + + /** + * 按照存储资源声明挂载存储 + * + * @param mountPath 挂载路径 + * @param dirBO 挂载路径参数 + * @param i 名称序号 + * @return boolean true成功 false失败 + */ + private boolean buildFsPvcVolumes(String mountPath, PtMountDirBO dirBO, int i) { + BizPersistentVolumeClaim bizPersistentVolumeClaim = persistentVolumeClaimApi.createWithFsPv(new PtPersistentVolumeClaimBO(namespace, baseName, dirBO)); + if (bizPersistentVolumeClaim.isSuccess()) { + volumeMounts.add(new VolumeMountBuilder() + .withName(K8sParamConstants.VOLUME_PREFIX + i) + .withMountPath(mountPath) + .withReadOnly(dirBO.isReadOnly()) + .build()); + volumes.add(new VolumeBuilder() + .withName(K8sParamConstants.VOLUME_PREFIX + i) + .withNewPersistentVolumeClaim(bizPersistentVolumeClaim.getName(), dirBO.isReadOnly()) + .build()); + return true; + } else { + this.errCode = bizPersistentVolumeClaim.getCode(); + this.errMessage = bizPersistentVolumeClaim.getMessage(); + } + return false; + } + + /** + * 检查是否已经存在,存在则返回 + * + * @return Job 任务类 + */ + private Job alreadyHaveJob() { + JobList list = client.batch().jobs().inNamespace(namespace).withLabels(LabelUtils.withEnvResourceName(baseName)).list(); + if (CollectionUtil.isNotEmpty(list.getItems())) { + Job job = list.getItems().get(0); + LogUtil.info(LogEnum.BIZ_K8S, "Skip creating job, {} already exists", job.getMetadata().getName()); + return job; + } + return null; + } + + /** + * 部署Job + * + * @return Job 任务job类 + */ + private Job deployJob() { + //已经存在直接返回 + Job job = alreadyHaveJob(); + if (job != null) { + return job; + } + job = buildJob(); + resourceIisolationApi.addIisolationInfo(job); + LogUtil.info(LogEnum.BIZ_K8S, YamlUtils.dumpAsYaml(job)); + job = client.batch().jobs().inNamespace(namespace).create(job); + return job; + } + + /** + * 构建Job + * + * @return Job 任务job类 + */ + private Job buildJob() { + Map childLabels = LabelUtils.getChildLabels(baseName, jobName, K8sKindEnum.JOB.getKind(), businessLabel); + return new JobBuilder() + .withNewMetadata() + .withName(jobName) + .addToLabels(baseLabels) + .withNamespace(namespace) + .endMetadata() + .withNewSpec() + .withBackoffLimit(0) + .withParallelism(1) + .withNewTemplate() + .withNewMetadata() + .withName(jobName) + .addToLabels(childLabels) + .withNamespace(namespace) + .endMetadata() + .withNewSpec() + .addToNodeSelector(gpuSelector()) + .addToContainers(buildContainer()) + .addToVolumes(volumes.toArray(new Volume[0])) + .withRestartPolicy(RestartPolicyEnum.NEVER.getRestartPolicy()) + .endSpec() + .endTemplate() + .endSpec() + .build(); + } + + /** + * 添加Gpu label + * + * @return Map Gpu label键值 + */ + private Map gpuSelector() { + Map gpuSelector = new HashMap<>(2); + if (gpuNum != null && gpuNum > 0) { + gpuSelector.put(K8sLabelConstants.NODE_GPU_LABEL_KEY, K8sLabelConstants.NODE_GPU_LABEL_VALUE); + } + return gpuSelector; + } + + /** + * 构建Container + * + * @return Container 容器类 + */ + private Container buildContainer() { + return new ContainerBuilder() + .withNewName(jobName) + .withNewImage(image) + .withNewImagePullPolicy(ImagePullPolicyEnum.IFNOTPRESENT.getPolicy()) + .withVolumeMounts(volumeMounts) + .addNewCommand(ShellCommandEnum.BASH.getShell()) + .addAllToArgs(cmdLines) + .withNewResources().addToLimits(resourcesLimitsMap).endResources() + .build(); + } + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/impl/ModelServingApiImpl.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/impl/ModelServingApiImpl.java new file mode 100644 index 0000000..5169171 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/impl/ModelServingApiImpl.java @@ -0,0 +1,337 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.api.impl; + +import cn.hutool.core.collection.CollectionUtil; +import cn.hutool.core.util.RandomUtil; +import cn.hutool.core.util.StrUtil; +import com.google.common.collect.Maps; +import io.fabric8.kubernetes.api.model.Container; +import io.fabric8.kubernetes.api.model.ContainerBuilder; +import io.fabric8.kubernetes.api.model.ContainerPort; +import io.fabric8.kubernetes.api.model.ContainerPortBuilder; +import io.fabric8.kubernetes.api.model.LabelSelector; +import io.fabric8.kubernetes.api.model.Quantity; +import io.fabric8.kubernetes.api.model.Secret; +import io.fabric8.kubernetes.api.model.SecretList; +import io.fabric8.kubernetes.api.model.Service; +import io.fabric8.kubernetes.api.model.ServiceList; +import io.fabric8.kubernetes.api.model.Volume; +import io.fabric8.kubernetes.api.model.apps.Deployment; +import io.fabric8.kubernetes.api.model.apps.DeploymentBuilder; +import io.fabric8.kubernetes.api.model.apps.DeploymentList; +import io.fabric8.kubernetes.api.model.extensions.Ingress; +import io.fabric8.kubernetes.api.model.extensions.IngressList; +import io.fabric8.kubernetes.client.KubernetesClient; +import io.fabric8.kubernetes.client.KubernetesClientException; +import org.dubhe.biz.base.constant.MagicNumConstant; +import org.dubhe.biz.base.constant.StringConstant; +import org.dubhe.biz.base.constant.SymbolConstant; +import org.dubhe.biz.base.utils.StringUtils; +import org.dubhe.biz.file.api.FileStoreApi; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.dubhe.k8s.api.ModelServingApi; +import org.dubhe.k8s.api.NodeApi; +import org.dubhe.k8s.api.PodApi; +import org.dubhe.k8s.api.ResourceIisolationApi; +import org.dubhe.k8s.api.ResourceQuotaApi; +import org.dubhe.k8s.api.VolumeApi; +import org.dubhe.k8s.constant.K8sParamConstants; +import org.dubhe.k8s.domain.PtBaseResult; +import org.dubhe.k8s.domain.bo.BuildIngressBO; +import org.dubhe.k8s.domain.bo.BuildFsVolumeBO; +import org.dubhe.k8s.domain.bo.BuildServiceBO; +import org.dubhe.k8s.domain.bo.ModelServingBO; +import org.dubhe.k8s.domain.vo.ModelServingVO; +import org.dubhe.k8s.domain.vo.VolumeVO; +import org.dubhe.k8s.enums.ImagePullPolicyEnum; +import org.dubhe.k8s.enums.K8sKindEnum; +import org.dubhe.k8s.enums.K8sResponseEnum; +import org.dubhe.k8s.enums.LimitsOfResourcesEnum; +import org.dubhe.k8s.enums.RestartPolicyEnum; +import org.dubhe.k8s.enums.ShellCommandEnum; +import org.dubhe.k8s.utils.BizConvertUtils; +import org.dubhe.k8s.utils.K8sUtils; +import org.dubhe.k8s.utils.LabelUtils; +import org.dubhe.k8s.utils.ResourceBuildUtils; +import org.dubhe.k8s.utils.YamlUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; + +import javax.annotation.Resource; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +/** + * @description 模型部署接口实现 + * @date 2020-09-10 + */ +public class ModelServingApiImpl implements ModelServingApi { + private K8sUtils k8sUtils; + private KubernetesClient client; + @Resource(name = "hostFileStoreApiImpl") + private FileStoreApi fileStoreApi; + @Autowired + private VolumeApi volumeApi; + @Autowired + private NodeApi nodeApi; + @Autowired + private PodApi podApi; + @Autowired + private ResourceQuotaApi resourceQuotaApi; + @Autowired + private ResourceIisolationApi resourceIisolationApi; + + @Value("${k8s.serving.host}") + String servingHost; + + @Value("${k8s.serving.tls-crt}") + String servingTlsCrt; + + @Value("${k8s.serving.tls-key}") + String servingTlsKey; + + private static final String MODEL_SERVING_MAX_UPLOAD_SIZE = "100m"; + + public ModelServingApiImpl(K8sUtils k8sUtils) { + this.k8sUtils = k8sUtils; + this.client = k8sUtils.getClient(); + } + + /** + * 创建 + * @param bo + * @return + */ + @Override + public ModelServingVO create(ModelServingBO bo) { + try { + //资源配额校验 + LimitsOfResourcesEnum limitsOfResources = resourceQuotaApi.reachLimitsOfResources(bo.getNamespace(), bo.getCpuNum(), bo.getMemNum(), bo.getGpuNum()); + if (!LimitsOfResourcesEnum.ADEQUATE.equals(limitsOfResources)) { + return new ModelServingVO().error(K8sResponseEnum.LACK_OF_RESOURCES.getCode(), limitsOfResources.getMessage()); + } + LogUtil.info(LogEnum.BIZ_K8S, "Params of creating ModelServing--create:{}", bo); + if (!fileStoreApi.createDirs(bo.getDirList().toArray(new String[MagicNumConstant.ZERO]))) { + return new ModelServingVO().error(K8sResponseEnum.INTERNAL_SERVER_ERROR.getCode(), K8sResponseEnum.INTERNAL_SERVER_ERROR.getMessage()); + } + //存储卷构建 + VolumeVO volumeVO = volumeApi.buildFsVolumes(new BuildFsVolumeBO(bo.getNamespace(), bo.getResourceName(), bo.getFsMounts())); + if (!K8sResponseEnum.SUCCESS.getCode().equals(volumeVO.getCode())) { + return new ModelServingVO().error(volumeVO.getCode(), volumeVO.getMessage()); + } + + //名称生成 + String deploymentName = StrUtil.format(K8sParamConstants.RESOURCE_NAME_TEMPLATE, bo.getResourceName(), RandomUtil.randomString(MagicNumConstant.EIGHT)); + String svcName = StrUtil.format(K8sParamConstants.SUB_RESOURCE_NAME_TEMPLATE, bo.getResourceName(), K8sParamConstants.SVC_SUFFIX, RandomUtil.randomString(MagicNumConstant.FIVE)); + String ingressName = StrUtil.format(K8sParamConstants.SUB_RESOURCE_NAME_TEMPLATE, bo.getResourceName(), K8sParamConstants.INGRESS_SUFFIX, RandomUtil.randomString(MagicNumConstant.FIVE)); + + //标签生成 + Map baseLabels = LabelUtils.getBaseLabels(bo.getResourceName(), bo.getBusinessLabel()); + Map podLabels = LabelUtils.getChildLabels(bo.getResourceName(), deploymentName, K8sKindEnum.DEPLOYMENT.getKind(), bo.getBusinessLabel()); + + //部署deployment + Deployment deployment = buildDeployment(bo, volumeVO, deploymentName); + LogUtil.info(LogEnum.BIZ_K8S, "Ready to deploy {}, yaml信息为{}", deploymentName, YamlUtils.dumpAsYaml(deployment)); + resourceIisolationApi.addIisolationInfo(deployment); + Deployment deploymentResult = client.apps().deployments().inNamespace(bo.getNamespace()).create(deployment); + + //部署service + BuildServiceBO buildServiceBO = new BuildServiceBO(bo.getNamespace(), svcName, baseLabels, podLabels); + if (bo.getHttpPort() != null) { + buildServiceBO.addPort(ResourceBuildUtils.buildServicePort(bo.getHttpPort(), bo.getHttpPort(), SymbolConstant.HTTP)); + } + if (bo.getGrpcPort() != null) { + buildServiceBO.addPort(ResourceBuildUtils.buildServicePort(bo.getGrpcPort(), bo.getGrpcPort(), SymbolConstant.GRPC)); + } + Service service = ResourceBuildUtils.buildService(buildServiceBO); + LogUtil.info(LogEnum.BIZ_K8S, "Ready to deploy {}, yaml信息为{}", svcName, YamlUtils.dumpAsYaml(service)); + Service serviceResult = client.services().create(service); + + //部署ingress + BuildIngressBO buildIngressBO = new BuildIngressBO(bo.getNamespace(), ingressName, baseLabels); + if (StringUtils.isNotEmpty(buildIngressBO.getMaxUploadSize())) { + buildIngressBO.putAnnotation(K8sParamConstants.INGRESS_PROXY_BODY_SIZE_KEY, buildIngressBO.getMaxUploadSize()); + } + if (bo.getHttpPort() != null) { + String httpHost = RandomUtil.randomString(MagicNumConstant.SIX) + SymbolConstant.DOT + servingHost; + buildIngressBO.addIngressRule(ResourceBuildUtils.buildIngressRule(httpHost, svcName, SymbolConstant.HTTP)); + } + Secret secretResult = null; + if (bo.getGrpcPort() != null) { + String secretName = StrUtil.format(K8sParamConstants.SUB_RESOURCE_NAME_TEMPLATE, bo.getResourceName(), SymbolConstant.TOKEN, RandomUtil.randomString(MagicNumConstant.FIVE)); + Map data = new HashMap(MagicNumConstant.FOUR) { + { + put(K8sParamConstants.SECRET_TLS_TLS_CRT, servingTlsCrt); + put(K8sParamConstants.SECRET_TLS_TLS_KEY, servingTlsKey); + } + }; + Secret secret = ResourceBuildUtils.buildTlsSecret(bo.getNamespace(), secretName, baseLabels, data); + secretResult = client.secrets().create(secret); + + String grpcHost = RandomUtil.randomString(MagicNumConstant.SIX) + SymbolConstant.DOT + servingHost; + buildIngressBO.addIngressRule(ResourceBuildUtils.buildIngressRule(grpcHost, svcName, SymbolConstant.GRPC)); + buildIngressBO.addIngressTLS(ResourceBuildUtils.buildIngressTLS(secretName, grpcHost)); + buildIngressBO.putAnnotation(K8sParamConstants.INGRESS_CLASS_KEY, StringConstant.NGINX_LOWERCASE); + buildIngressBO.putAnnotation(K8sParamConstants.INGRESS_SSL_REDIRECT_KEY, StringConstant.TRUE_LOWERCASE); + buildIngressBO.putAnnotation(K8sParamConstants.INGRESS_BACKEND_PROTOCOL_KEY, StringConstant.GRPC_CAPITALIZE); + } + Ingress ingress = ResourceBuildUtils.buildIngress(buildIngressBO); + LogUtil.info(LogEnum.BIZ_K8S, "Ready to deploy {}, yaml信息为{}", ingressName, YamlUtils.dumpAsYaml(ingress)); + Ingress ingressResult = client.extensions().ingresses().create(ingress); + + return new ModelServingVO(BizConvertUtils.toBizSecret(secretResult), BizConvertUtils.toBizService(serviceResult), BizConvertUtils.toBizDeployment(deploymentResult), BizConvertUtils.toBizIngress(ingressResult)); + } catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "ModelOptJobApiImpl.create error, param:{} error:", bo, e); + return new ModelServingVO().error(String.valueOf(e.getCode()), e.getMessage()); + } + } + + /** + * 删除 + * @param namespace 命名空间 + * @param resourceName 资源名称 + * @return PtBaseResult 基础结果类 + */ + @Override + public PtBaseResult delete(String namespace, String resourceName) { + try { + LogUtil.info(LogEnum.BIZ_K8S, "delete model serving namespace:{} resourceName:{}",namespace,resourceName); + DeploymentList deploymentList = client.apps().deployments().inNamespace(namespace).withLabels(LabelUtils.withEnvResourceName(resourceName)).list(); + if (deploymentList == null || deploymentList.getItems().size() == 0){ + return new PtBaseResult(); + } + Boolean res = client.extensions().ingresses().inNamespace(namespace).withLabels(LabelUtils.withEnvResourceName(resourceName)).delete() + && client.services().inNamespace(namespace).withLabels(LabelUtils.withEnvResourceName(resourceName)).delete() + && client.apps().deployments().inNamespace(namespace).withLabels(LabelUtils.withEnvResourceName(resourceName)).delete() + && client.secrets().inNamespace(namespace).withLabels(LabelUtils.withEnvResourceName(resourceName)).delete(); + if (res) { + return new PtBaseResult(); + } else { + return K8sResponseEnum.REPEAT.toPtBaseResult(); + } + } catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "delete error:", e); + return new PtBaseResult(String.valueOf(e.getCode()), e.getMessage()); + } + } + + /** + * 查询 + * @param namespace + * @param resourceName + * @return + */ + @Override + public ModelServingVO get(String namespace, String resourceName) { + try { + IngressList ingressList = client.extensions().ingresses().inNamespace(namespace).withLabels(LabelUtils.withEnvResourceName(resourceName)).list(); + Ingress ingress = CollectionUtil.isEmpty(ingressList.getItems()) ? null : ingressList.getItems().get(0); + ServiceList svcList = client.services().inNamespace(namespace).withLabels(LabelUtils.withEnvResourceName(resourceName)).list(); + Service svc = CollectionUtil.isEmpty(svcList.getItems()) ? null : svcList.getItems().get(0); + DeploymentList deploymentList = client.apps().deployments().inNamespace(namespace).withLabels(LabelUtils.withEnvResourceName(resourceName)).list(); + Deployment deployment = CollectionUtil.isEmpty(deploymentList.getItems()) ? null : deploymentList.getItems().get(0); + SecretList secretList = client.secrets().inNamespace(namespace).withLabels(LabelUtils.withEnvResourceName(resourceName)).list(); + Secret secret = CollectionUtil.isEmpty(secretList.getItems()) ? null : secretList.getItems().get(0); + return new ModelServingVO(BizConvertUtils.toBizSecret(secret), BizConvertUtils.toBizService(svc), BizConvertUtils.toBizDeployment(deployment), BizConvertUtils.toBizIngress(ingress)); + } catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "get error:", e); + return new ModelServingVO().error(String.valueOf(e.getCode()), e.getMessage()); + } + } + + /** + * 构建Deployment + * + * @return Deployment + */ + private Deployment buildDeployment(ModelServingBO bo, VolumeVO volumeVO, String deploymentName) { + Map childLabels = LabelUtils.getChildLabels(bo.getResourceName(), deploymentName, K8sKindEnum.DEPLOYMENT.getKind(), bo.getBusinessLabel()); + LabelSelector labelSelector = new LabelSelector(); + labelSelector.setMatchLabels(childLabels); + return new DeploymentBuilder() + .withNewMetadata() + .withName(deploymentName) + .addToLabels(LabelUtils.getBaseLabels(bo.getResourceName(), bo.getBusinessLabel())) + .withNamespace(bo.getNamespace()) + .endMetadata() + .withNewSpec() + .withReplicas(bo.getReplicas()) + .withSelector(labelSelector) + .withNewTemplate() + .withNewMetadata() + .withName(deploymentName) + .addToLabels(childLabels) + .withNamespace(bo.getNamespace()) + .endMetadata() + .withNewSpec() + .addToNodeSelector(k8sUtils.gpuSelector(bo.getGpuNum())) + .addToContainers(buildContainer(bo, volumeVO, deploymentName)) + .addToVolumes(volumeVO.getVolumes().toArray(new Volume[0])) + .withRestartPolicy(RestartPolicyEnum.ALWAYS.getRestartPolicy()) + .endSpec() + .endTemplate() + .endSpec() + .build(); + } + + /** + * 构建 Container + * @param bo + * @param volumeVO + * @param name + * @return + */ + private Container buildContainer(ModelServingBO bo, VolumeVO volumeVO, String name) { + Map resourcesLimitsMap = Maps.newHashMap(); + Optional.ofNullable(bo.getCpuNum()).ifPresent(v -> resourcesLimitsMap.put(K8sParamConstants.QUANTITY_CPU_KEY, new Quantity(v.toString(), K8sParamConstants.CPU_UNIT))); + Optional.ofNullable(bo.getGpuNum()).ifPresent(v -> resourcesLimitsMap.put(K8sParamConstants.GPU_RESOURCE_KEY, new Quantity(v.toString()))); + Optional.ofNullable(bo.getMemNum()).ifPresent(v -> resourcesLimitsMap.put(K8sParamConstants.QUANTITY_MEMORY_KEY, new Quantity(v.toString(), K8sParamConstants.MEM_UNIT))); + Container container = new ContainerBuilder() + .withNewName(name) + .withNewImage(bo.getImage()) + .withNewImagePullPolicy(ImagePullPolicyEnum.IFNOTPRESENT.getPolicy()) + .withVolumeMounts(volumeVO.getVolumeMounts()) + .withNewResources().addToLimits(resourcesLimitsMap).endResources() + .build(); + if (bo.getCmdLines() != null) { + container.setCommand(Arrays.asList(ShellCommandEnum.BIN_BANSH.getShell())); + container.setArgs(bo.getCmdLines()); + } + List ports = new ArrayList<>(); + if (bo.getHttpPort() != null) { + ports.add(new ContainerPortBuilder() + .withContainerPort(bo.getHttpPort()) + .withName(SymbolConstant.HTTP).build()); + } + if (bo.getGrpcPort() != null) { + ports.add(new ContainerPortBuilder() + .withContainerPort(bo.getGrpcPort()) + .withName(SymbolConstant.GRPC).build()); + } + if (CollectionUtil.isNotEmpty(ports)) { + container.setPorts(ports); + } + return container; + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/impl/NamespaceApiImpl.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/impl/NamespaceApiImpl.java new file mode 100644 index 0000000..8fe5dc6 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/impl/NamespaceApiImpl.java @@ -0,0 +1,332 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.api.impl; + +import com.alibaba.fastjson.JSON; +import io.fabric8.kubernetes.api.model.Namespace; +import io.fabric8.kubernetes.api.model.NamespaceBuilder; +import io.fabric8.kubernetes.api.model.NamespaceList; +import io.fabric8.kubernetes.api.model.ResourceQuota; +import io.fabric8.kubernetes.client.KubernetesClient; +import io.fabric8.kubernetes.client.KubernetesClientException; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.k8s.annotation.K8sValidation; +import org.dubhe.k8s.api.NamespaceApi; +import org.dubhe.k8s.api.ResourceQuotaApi; +import org.dubhe.k8s.domain.PtBaseResult; +import org.dubhe.k8s.domain.resource.BizNamespace; +import org.dubhe.k8s.enums.K8sResponseEnum; +import org.dubhe.k8s.enums.ValidationTypeEnum; +import org.dubhe.k8s.utils.BizConvertUtils; +import org.dubhe.k8s.utils.K8sUtils; +import org.dubhe.k8s.utils.LabelUtils; +import org.dubhe.biz.log.utils.LogUtil; +import org.dubhe.biz.base.utils.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.util.CollectionUtils; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * @description NamespaceApi 实现类 + * @date 2020-04-15 + */ +public class NamespaceApiImpl implements NamespaceApi { + + private KubernetesClient client; + + @Autowired + private ResourceQuotaApi resourceQuotaApi; + + @Value("${k8s.namespace-limits.cpu}") + private Integer cpuLimit; + + @Value("${k8s.namespace-limits.memory}") + private Integer memoryLimit; + + @Value("${k8s.namespace-limits.gpu}") + private Integer gpuLimit; + + + + public NamespaceApiImpl(K8sUtils k8sUtils) { + this.client = k8sUtils.getClient(); + } + + /** + * 创建NamespaceLabels,为null则不添加标签 + * + * @param namespace 命名空间 + * @param labels 标签Map + * @return BizNamespace Namespace 业务类 + */ + @Override + public BizNamespace create(@K8sValidation(ValidationTypeEnum.K8S_RESOURCE_NAME) String namespace, Map labels) { + try { + BizNamespace bizNamespace = get(namespace); + if (bizNamespace != null){ + return bizNamespace; + } + Namespace ns = new NamespaceBuilder().withNewMetadata().withName(namespace).addToLabels(LabelUtils.getBaseLabels(namespace, labels)).endMetadata().build(); + Namespace res = client.namespaces().create(ns); + resourceQuotaApi.create(res.getMetadata().getName(),res.getMetadata().getName(),cpuLimit,memoryLimit,gpuLimit); + return BizConvertUtils.toBizNamespace(res); + } catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "NamespaceApiImpl.create error, param:[namespace]={}, [labels]={},error:{}",namespace, labels, e); + return new BizNamespace().error(String.valueOf(e.getCode()), e.getMessage()); + } + } + + /** + * 根据namespace查询BizNamespace + * + * @param namespace 命名空间 + * @return BizNamespace Namespace 业务类 + */ + @Override + public BizNamespace get(String namespace) { + if (StringUtils.isEmpty(namespace)) { + return new BizNamespace().baseErrorBadRequest(); + } + return BizConvertUtils.toBizNamespace(client.namespaces().withName(namespace).get()); + } + + /** + * 查询所有的BizNamespace + * + * @return List Namespace 业务类集合 + */ + @Override + public List listAll() { + NamespaceList namespaceList = client.namespaces().list(); + if (namespaceList == null || CollectionUtils.isEmpty(namespaceList.getItems())) { + return Collections.emptyList(); + } + return namespaceList.getItems().parallelStream().map(obj -> BizConvertUtils.toBizNamespace(obj)).collect(Collectors.toList()); + } + + /** + * 根据label标签查询所有的BizNamespace + * + * @param labelKey 标签的键 + * @return List Namespace 业务类集合 + */ + @Override + public List list(String labelKey) { + if (StringUtils.isEmpty(labelKey)) { + return Collections.EMPTY_LIST; + } + NamespaceList namespaceList = client.namespaces().withLabel(labelKey, null).list(); + if (namespaceList == null || CollectionUtils.isEmpty(namespaceList.getItems())) { + return Collections.EMPTY_LIST; + } + return namespaceList.getItems().parallelStream().map(obj -> BizConvertUtils.toBizNamespace(obj)).collect(Collectors.toList()); + } + + /** + * 根据label标签集合查询所有的BizNamespace数据 + * + * @param labels 标签键的集合 + * @return List Namespace业务类集合 + */ + @Override + public List list(Set labels) { + if (CollectionUtils.isEmpty(labels)) { + return Collections.EMPTY_LIST; + } + Map map = new HashMap<>(); + Iterator it = labels.iterator(); + while (it.hasNext()) { + //根据label的key查询,无需关系value值 + map.put(it.next(), null); + } + NamespaceList namespaceList = client.namespaces().withLabels(map).list(); + if (namespaceList == null || CollectionUtils.isEmpty(namespaceList.getItems())) { + return Collections.EMPTY_LIST; + } + return namespaceList.getItems().parallelStream().map(obj -> BizConvertUtils.toBizNamespace(obj)).collect(Collectors.toList()); + } + + /** + * 删除命名空间 + * + * @param namespace 命名空间 + * @return PtBaseResult 基础结果类 + */ + @Override + public PtBaseResult delete(String namespace) { + LogUtil.info(LogEnum.BIZ_K8S, "Param of delete namespace {}", namespace); + if (StringUtils.isEmpty(namespace)) { + return new PtBaseResult().baseErrorBadRequest(); + } + try { + if (client.namespaces().withName(namespace).delete()) { + return new PtBaseResult(); + } else { + return K8sResponseEnum.REPEAT.toPtBaseResult(); + } + } catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "NamespaceApiImpl.delete error, param:[namespace]={}, error:{}", namespace, e); + return new PtBaseResult(String.valueOf(e.getCode()), e.getMessage()); + } + } + + /** + * 删除命名空间的标签 + * + * @param namespace 命名空间 + * @param labelKey 标签的键 + * @return PtBaseResult 基础结果类 + */ + @Override + public PtBaseResult removeLabel(String namespace, String labelKey) { + if (StringUtils.isEmpty(namespace) || StringUtils.isEmpty(labelKey)) { + return new PtBaseResult().baseErrorBadRequest(); + } + try { + client.namespaces().withName(namespace) + .edit() + .editMetadata() + .removeFromLabels(labelKey) + .endMetadata() + .done(); + return new PtBaseResult(); + } catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "NamespaceApiImpl.removeLabel error, param:[namespace]={}, [labelKey]={}, error:{}", namespace, labelKey, e); + return new PtBaseResult(String.valueOf(e.getCode()), e.getMessage()); + } + } + + /** + * 删除命名空间下的多个标签 + * + * @param namespace 命名空间 + * @param labels 标签键的集合 + * @return PtBaseResult 基础结果类 + */ + @Override + public PtBaseResult removeLabels(String namespace, Set labels) { + if (StringUtils.isEmpty(namespace) || CollectionUtils.isEmpty(labels)) { + return new PtBaseResult().baseErrorBadRequest(); + } + try { + Map map = new HashMap<>(); + Iterator it = labels.iterator(); + while (it.hasNext()) { + //根据label的key查询,无需关系value值 + map.put(it.next(), null); + } + client.namespaces().withName(namespace) + .edit() + .editMetadata() + .removeFromLabels(map) + .endMetadata() + .done(); + return new PtBaseResult(); + } catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "NamespaceApiImpl.removeLabel error, param:[namespace]={}, [labels]={},error:{}", namespace, labels, e); + return new PtBaseResult(String.valueOf(e.getCode()), e.getMessage()); + } + } + + /** + * 将labelKey和labelValue添加到指定的命名空间 + * + * @param namespace 命名空间 + * @param labelKey 标签的键 + * @param labelValue 标签的值 + * @return PtBaseResult 基础结果类 + */ + @Override + public PtBaseResult addLabel(String namespace, String labelKey, String labelValue) { + if (StringUtils.isEmpty(namespace) || StringUtils.isEmpty(labelKey)) { + return new PtBaseResult().baseErrorBadRequest(); + } + try { + client.namespaces().withName(namespace).edit().editMetadata().addToLabels(labelKey, labelValue).endMetadata().done(); + return new PtBaseResult(); + } catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "NamespaceApiImpl.addLabel error, param:[namespace]={}, [labelKey]={}, [labelValue]={}, error:{}", namespace, labelKey, labelValue, e); + return new PtBaseResult(String.valueOf(e.getCode()), e.getMessage()); + } + } + + /** + * 将多个label标签添加到指定的命名空间 + * + * @param namespace 命名空间 + * @param labels 标签 + * @return PtBaseResult 基础结果类 + */ + @Override + public PtBaseResult addLabels(String namespace, Map labels) { + if (StringUtils.isEmpty(namespace) || CollectionUtils.isEmpty(labels)) { + return new PtBaseResult().baseErrorBadRequest(); + } + try { + client.namespaces().withName(namespace).edit().editMetadata().addToLabels(labels).endMetadata().done(); + return new PtBaseResult(); + } catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "NamespaceApiImpl.addLabels error, param:[namespace]={}, [labels]={},error:{}",namespace, JSON.toJSONString(labels), e); + return new PtBaseResult(String.valueOf(e.getCode()), e.getMessage()); + } + } + + + /** + * 命名空间的资源限制 + * + * @param namespace 命名空间 + * @param quota 资源限制参数类 + * @return ResourceQuota 资源限制参数类 + */ + @Override + public ResourceQuota addResourceQuota(String namespace, ResourceQuota quota) { + return client.resourceQuotas().inNamespace(namespace).create(quota); + } + + /** + * 获得命名空间下的所有的资源限制 + * + * @param namespace 命名空间 + * @return List 资源限制参数类 + */ + @Override + public List listResourceQuotas(String namespace) { + return client.resourceQuotas().inNamespace(namespace).list().getItems(); + } + + /** + * 解除对命名空间的资源限制 + * + * @param namespace 命名空间 + * @param quota 资源限制参数类 + * @return boolean true成功 false失败 + */ + @Override + public boolean removeResourceQuota(String namespace, ResourceQuota quota) { + return client.resourceQuotas().inNamespace(namespace).delete(quota); + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/impl/NativeResourceApiImpl.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/impl/NativeResourceApiImpl.java new file mode 100644 index 0000000..68aa076 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/impl/NativeResourceApiImpl.java @@ -0,0 +1,72 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.api.impl; + +import io.fabric8.kubernetes.api.model.HasMetadata; +import io.fabric8.kubernetes.client.KubernetesClient; +import io.fabric8.kubernetes.client.KubernetesClientException; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.k8s.api.NativeResourceApi; +import org.dubhe.k8s.utils.K8sUtils; +import org.dubhe.biz.log.utils.LogUtil; + +import java.io.ByteArrayInputStream; +import java.util.ArrayList; +import java.util.List; + +/** + * @description 本地资源实现类 + * @date 2020-08-28 + */ +public class NativeResourceApiImpl implements NativeResourceApi { + private KubernetesClient client; + public NativeResourceApiImpl(K8sUtils k8sUtils) { + this.client = k8sUtils.getClient(); + } + + /** + * + * @param crYaml cr定义yaml脚本 + * @return List HasMetadata资源集合 + */ + @Override + public List create(String crYaml) { + LogUtil.info(LogEnum.BIZ_K8S, "Param of create crYaml {}", crYaml); + try { + return client.load(new ByteArrayInputStream(crYaml.getBytes())).deletingExisting().createOrReplace(); + }catch (KubernetesClientException e){ + LogUtil.error(LogEnum.BIZ_K8S, "Create NativeResource error:{} ,yml:{}", e,crYaml); + return new ArrayList<>(); + } + } + + /** + * + * @param crYaml cr定义yaml脚本 + * @return boolean true删除成功 false删除失败 + */ + @Override + public boolean delete(String crYaml) { + LogUtil.info(LogEnum.BIZ_K8S, "Param of delete crYaml {}", crYaml); + try { + return client.load(new ByteArrayInputStream(crYaml.getBytes())).delete(); + }catch (KubernetesClientException e){ + LogUtil.error(LogEnum.BIZ_K8S, "Delete NativeResource error:{} ,yml:{}", e,crYaml); + return false; + } + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/impl/NodeApiImpl.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/impl/NodeApiImpl.java new file mode 100644 index 0000000..f362822 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/impl/NodeApiImpl.java @@ -0,0 +1,723 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.api.impl; + +import cn.hutool.core.collection.CollectionUtil; +import cn.hutool.core.util.StrUtil; +import com.alibaba.fastjson.JSON; +import io.fabric8.kubernetes.api.model.Node; +import io.fabric8.kubernetes.api.model.NodeList; +import io.fabric8.kubernetes.api.model.Pod; +import io.fabric8.kubernetes.api.model.PodList; +import io.fabric8.kubernetes.api.model.Taint; +import io.fabric8.kubernetes.api.model.Toleration; +import io.fabric8.kubernetes.client.KubernetesClient; +import io.fabric8.kubernetes.client.KubernetesClientException; +import org.dubhe.biz.base.constant.MagicNumConstant; +import org.dubhe.biz.base.constant.NumberConstant; +import org.dubhe.biz.base.service.UserContextService; +import org.dubhe.biz.base.utils.SpringContextHolder; +import org.dubhe.biz.base.utils.StringUtils; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.dubhe.k8s.api.MetricsApi; +import org.dubhe.k8s.api.NodeApi; +import org.dubhe.k8s.constant.K8sLabelConstants; +import org.dubhe.k8s.constant.K8sParamConstants; +import org.dubhe.k8s.domain.PtBaseResult; +import org.dubhe.k8s.domain.resource.BizNode; +import org.dubhe.k8s.domain.resource.BizTaint; +import org.dubhe.k8s.domain.vo.PtNodeMetricsVO; +import org.dubhe.k8s.enums.K8sResponseEnum; +import org.dubhe.k8s.enums.K8sTolerationEffectEnum; +import org.dubhe.k8s.enums.LackOfResourcesEnum; +import org.dubhe.k8s.enums.PodPhaseEnum; +import org.dubhe.k8s.utils.BizConvertUtils; +import org.dubhe.k8s.utils.K8sUtils; +import org.dubhe.k8s.utils.ResourceBuildUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.util.CollectionUtils; + +import java.util.*; +import java.util.stream.Collectors; + +/** + * @description NodeApi实现类 + * @date 2020-04-21 + */ +public class NodeApiImpl implements NodeApi { + + @Autowired + private MetricsApi metricsApi; + + private KubernetesClient client; + + @Autowired + private UserContextService userContextService; + + public NodeApiImpl(K8sUtils k8sUtils) { + this.client = k8sUtils.getClient(); + } + + /** + * 根据节点名称查询节点信息 + * + * @param nodeName 节点名称 + * @return BizNode Node 业务类 + */ + @Override + public BizNode get(String nodeName) { + try { + LogUtil.info(LogEnum.BIZ_K8S, "Input nodeName={}", nodeName); + if (StringUtils.isEmpty(nodeName)) { + return null; + } + Node node = client.nodes().withName(nodeName).get(); + BizNode bizNode = BizConvertUtils.toBizNode(node); + LogUtil.info(LogEnum.BIZ_K8S, "Output {}", bizNode); + return bizNode; + } catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "NodeApiImpl.get error, param:[nodeName]={}, error:{}", nodeName, e); + return new BizNode().error(String.valueOf(e.getCode()), e.getMessage()); + } + } + + /** + * 查询所有节点信息 + * + * @return List Node 业务类集合 + */ + @Override + public List listAll() { + try { + NodeList nodes = client.nodes().list(); + if (nodes == null || CollectionUtils.isEmpty(nodes.getItems())) { + return Collections.EMPTY_LIST; + } + List bizNodeList = nodes.getItems().parallelStream().map(obj -> BizConvertUtils.toBizNode(obj).setReady()).collect(Collectors.toList()); + LogUtil.info(LogEnum.BIZ_K8S, "Output {}", bizNodeList); + return bizNodeList; + } catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "NodeApiImpl.listAll error:{}", e); + return Collections.EMPTY_LIST; + } + } + + /** + * 给节点添加单个标签 + * + * @param nodeName 节点名称 + * @param labelKey 标签的键 + * @param labelValue 标签的值 + * @return PtBaseResult 基础结果类 + */ + @Override + public PtBaseResult addLabel(String nodeName, String labelKey, String labelValue) { + try { + LogUtil.info(LogEnum.BIZ_K8S, "Input nodeName={};labelKey={};labelValue={}", nodeName, labelKey, labelValue); + if (StringUtils.isEmpty(nodeName) || StringUtils.isEmpty(labelKey)) { + return new PtBaseResult().baseErrorBadRequest(); + } + client.nodes().withName(nodeName).edit().editMetadata().addToLabels(labelKey, labelValue).endMetadata().done(); + return new PtBaseResult(); + } catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "NodeApiImpl.addLabel error, param:[nodeName]={}, [labelKey]={}, [labelValue]={}, error:{}", nodeName, labelKey, labelValue, e); + return new PtBaseResult(String.valueOf(e.getCode()), e.getMessage()); + } + } + + /** + * 给节点添加多个标签 + * + * @param nodeName 节点名称 + * @param labels 标签Map + * @return PtBaseResult 基础结果类 + */ + @Override + public PtBaseResult addLabels(String nodeName, Map labels) { + try { + LogUtil.info(LogEnum.BIZ_K8S, "Input nodeName={};labels={}", nodeName, labels); + if (StringUtils.isEmpty(nodeName) || CollectionUtils.isEmpty(labels)) { + return new PtBaseResult().baseErrorBadRequest(); + } + client.nodes().withName(nodeName).edit().editMetadata().addToLabels(labels).endMetadata().done(); + return new PtBaseResult(); + } catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "NodeApiImpl.addLabels error, param:[nodeName]={}, [labels]={},error:{}",nodeName, JSON.toJSONString(labels), e); + return new PtBaseResult(String.valueOf(e.getCode()), e.getMessage()); + } + } + + /** + * 删除节点单个标签 + * + * @param nodeName 节点名称 + * @param labelKey 标签的键 + * @return PtBaseResult 基础结果类 + */ + @Override + public PtBaseResult deleteLabel(String nodeName, String labelKey) { + try { + LogUtil.info(LogEnum.BIZ_K8S, "Input nodeName={};labelKey={}", nodeName, labelKey); + if (StringUtils.isEmpty(nodeName) || StringUtils.isEmpty(labelKey)) { + return new PtBaseResult().baseErrorBadRequest(); + } + client.nodes().withName(nodeName).edit().editMetadata().removeFromLabels(labelKey).endMetadata().done(); + return new PtBaseResult(); + } catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "NodeApiImpl.deleteLabel error, param:[nodeName]={}, [labelKey]={},error:{}",nodeName, labelKey, e); + return new PtBaseResult(String.valueOf(e.getCode()), e.getMessage()); + } + } + + /** + * 删除节点的多个标签 + * + * @param nodeName 节点名称 + * @param labels 标签键集合 + * @return PtBaseResult 基础结果类 + */ + @Override + public PtBaseResult deleteLabels(String nodeName, Set labels) { + try { + LogUtil.info(LogEnum.BIZ_K8S, "Input nodeName={};labels={}", nodeName, labels); + if (StringUtils.isEmpty(nodeName) || CollectionUtils.isEmpty(labels)) { + return new PtBaseResult().baseErrorBadRequest(); + } + Map map = new HashMap<>(); + Iterator it = labels.iterator(); + while (it.hasNext()) { + map.put(it.next(), null); + } + client.nodes().withName(nodeName).edit().editMetadata().removeFromLabels(map).endMetadata().done(); + return new PtBaseResult(); + } catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "NodeApiImpl.deleteLabelS error, param:[nodeName]={}, [labels]={},error:{}", nodeName, JSON.toJSONString(labels), e); + return new PtBaseResult(String.valueOf(e.getCode()), e.getMessage()); + } + } + + /** + * 根据标签查询节点 + * + * @param key 标签key + * @param value 标签value + * @return List + */ + @Override + public List getWithLabel(String key, String value) { + try { + List bizNodes = new ArrayList<>(); + if (StringUtils.isEmpty(key) || StringUtils.isEmpty(value)){ + return bizNodes; + } + NodeList nodeList = client.nodes().withLabel(key,value).list(); + if (nodeList != null && !CollectionUtils.isEmpty(nodeList.getItems())){ + return BizConvertUtils.toBizNodes(nodeList.getItems()); + } + return bizNodes; + } catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "NodeApiImpl.getWithLabels error, param:[key]={} [value]={},error:{}", key,value, e); + return new ArrayList<>(); + } + } + + /** + * 根据标签查询节点 + * + * @param labels 标签 + * @return List + */ + @Override + public List getWithLabels(Map labels) { + try { + List bizNodes = new ArrayList<>(); + if (CollectionUtils.isEmpty(labels)){ + return bizNodes; + } + NodeList nodeList = client.nodes().withLabels(labels).list(); + if (nodeList != null && !CollectionUtils.isEmpty(nodeList.getItems())){ + return BizConvertUtils.toBizNodes(nodeList.getItems()); + } + return bizNodes; + } catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "NodeApiImpl.getWithLabels error, param:[labels]={},error:{}", JSON.toJSONString(labels), e); + return new ArrayList<>(); + } + } + + /** + * 设置节点是否可调度 + * + * @param nodeName 节点名称 + * @param schedulable 参数true或false + * @return PtBaseResult 基础结果类 + */ + @Override + public PtBaseResult schedulable(String nodeName, boolean schedulable) { + LogUtil.info(LogEnum.BIZ_K8S, "Input nodeName={};schedulable={}", nodeName, schedulable); + if (StringUtils.isEmpty(nodeName)) { + return new PtBaseResult().baseErrorBadRequest(); + } + try { + Node node = client.nodes().withName(nodeName).get(); + if (node == null) { + return K8sResponseEnum.NOT_FOUND.toPtBaseResult(); + } + node.getSpec().setUnschedulable(schedulable); + client.nodes().withName(nodeName).replace(node); + return new PtBaseResult(); + } catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "NodeApiImpl.schedulable error:{}", e); + return new PtBaseResult(String.valueOf(e.getCode()), e.getMessage()); + } + } + + /** + * 查询集群资源是否充足 + * + * @param nodeSelector 节点选择标签 + * @param taints 该资源所能容忍的污点 + * @param cpuNum 单位为m 1核等于1000m + * @param memNum 单位为Mi 1Mi等于1024Ki + * @param gpuNum 单位为显卡,即"1"表示1张显卡 + * @return LackOfResourcesEnum 资源缺乏枚举类 + */ + @Override + public LackOfResourcesEnum isAllocatable(Map nodeSelector, List taints, Integer cpuNum, Integer memNum, Integer gpuNum) { + LogUtil.info(LogEnum.BIZ_K8S, "Input nodeSelector={};taints={};cpuNum={};memNum={};gpuNum={}", JSON.toJSONString(nodeSelector), JSON.toJSONString(taints), cpuNum, memNum, gpuNum); + NodeList list; + try { + list = client.nodes().list(); + }catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "NodeApiImpl.isAllocatable error:{}", e); + return LackOfResourcesEnum.LACK_OF_NODE; + } + + List nodeItems = list.getItems(); + //根据nodeSelector筛选节点 + if (CollectionUtil.isNotEmpty(nodeSelector) && nodeSelector.size() > NumberConstant.NUMBER_1){ + return LackOfResourcesEnum.LACK_OF_NODE; + } else if (CollectionUtil.isNotEmpty(nodeSelector) && nodeSelector.size() == NumberConstant.NUMBER_1){ + for (String nodeSelectorKey : nodeSelector.keySet()) { + String nodeSelectorValue = nodeSelector.get(nodeSelectorKey); + nodeItems = nodeItems.stream().filter(nodeItem -> nodeSelectorValue.equals(nodeItem.getMetadata().getLabels().get(nodeSelectorKey))) + .collect(Collectors.toList()); + } + } + //根据可容忍的污点筛选节点 + if (CollectionUtil.isEmpty(taints)){ + nodeItems = nodeItems.stream().filter(nodeItem -> CollectionUtils.isEmpty(nodeItem.getSpec().getTaints())).collect(Collectors.toList()); + } else { + List taintNodes = new ArrayList<>(); + for (BizTaint taint : taints) { + taintNodes.addAll( nodeItems.stream().filter(nodeItem -> doesTaintExit(nodeItem, taint)).collect(Collectors.toList())); + } + nodeItems = taintNodes; + } + + if (CollectionUtils.isEmpty(nodeItems)) { + return LackOfResourcesEnum.LACK_OF_NODE; + } + if (cpuNum != null && cpuNum >= MagicNumConstant.ZERO) { + nodeItems = isCpuAllocatable(cpuNum, nodeItems); + if (CollectionUtils.isEmpty(nodeItems)) { + return LackOfResourcesEnum.LACK_OF_CPU; + } + } + + if (memNum != null && memNum >= MagicNumConstant.ZERO) { + nodeItems = isMemAllocatable(memNum, nodeItems); + if (CollectionUtils.isEmpty(nodeItems)) { + return LackOfResourcesEnum.LACK_OF_MEM; + } + } + + if (gpuNum != null && gpuNum >= MagicNumConstant.ZERO) { + nodeItems = isGpuAllocatable(gpuNum, nodeItems); + if (CollectionUtils.isEmpty(nodeItems)) { + return LackOfResourcesEnum.LACK_OF_GPU; + } + } + + return LackOfResourcesEnum.ADEQUATE; + } + + /** + * 查询集群资源是否充足 + * + * @param cpuNum 单位为m 1核等于1000m + * @param memNum 单位为Mi 1Mi等于1024Ki + * @param gpuNum 单位为显卡,即"1"表示1张显卡 + * @return LackOfResourcesEnum 资源缺乏枚举类 + */ + @Override + public LackOfResourcesEnum isAllocatable(Integer cpuNum, Integer memNum, Integer gpuNum) { + Toleration toleration = getNodeIsolationToleration(); + if (toleration == null){ + return isAllocatable(null,null,cpuNum,memNum,gpuNum); + }else { + return isAllocatable(getNodeIsolationNodeSelector(), geBizTaintListByUserId(),cpuNum,memNum,gpuNum); + } + } + + /** + * 判断是否超出总可分配gpu数 + * @param gpuNum + * @return LackOfResourcesEnum 资源缺乏枚举类 + */ + @Override + public LackOfResourcesEnum isOutOfTotalAllocatableGpu(Integer gpuNum){ + Integer remainingGpuNum = getTotalGpuNum() - getAllocatedGpuNum(); + if (gpuNum > remainingGpuNum){ + return LackOfResourcesEnum.LACK_OF_GPU; + }else { + return LackOfResourcesEnum.ADEQUATE; + } + } + + /** + * 添加污点 + * + * @param nodeName 节点名称 + * @param bizTaintList 污点 + * @return BizNode + */ + @Override + public BizNode taint(String nodeName, List bizTaintList) { + try { + if (StringUtils.isEmpty(nodeName) || org.springframework.util.CollectionUtils.isEmpty(bizTaintList)){ + return new BizNode().errorBadRequest(); + } + Node nodeInfo = client.nodes().withName(nodeName).get(); + if (nodeInfo == null){ + return new BizNode().error(K8sResponseEnum.NOT_FOUND.getCode(), "节点["+nodeName+"]不存在"); + } + List oldTaints = nodeInfo.getSpec().getTaints(); + for (Taint taint : oldTaints){ + if (K8sLabelConstants.PLATFORM_TAG_ISOLATION_KEY.equals(taint.getKey())){ + return new BizNode().error(K8sResponseEnum.EXISTS.getCode(),"节点已被占用"); + } + } + + Node node = client.nodes().withName(nodeName).edit().editSpec().addAllToTaints(BizConvertUtils.toTaints(bizTaintList)).endSpec().done(); + return BizConvertUtils.toBizNode(node); + }catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "NodeApiImpl.schedulable error:{}", e); + return new BizNode().error(String.valueOf(e.getCode()), e.getMessage()); + } + } + + /** + * 删除污点 + * + * @param nodeName 节点名称 + * @param bizTaintList 污点 + * @return BizNode + */ + @Override + public BizNode delTaint(String nodeName, List bizTaintList) { + try { + if (StringUtils.isEmpty(nodeName) || org.springframework.util.CollectionUtils.isEmpty(bizTaintList)){ + return new BizNode().errorBadRequest(); + } + Node nodeInfo = client.nodes().withName(nodeName).get(); + if (nodeInfo == null){ + return new BizNode().error(K8sResponseEnum.NOT_FOUND.getCode(), "节点["+nodeName+"]不存在"); + } + Node node = client.nodes().withName(nodeName).edit().editSpec().removeAllFromTaints(BizConvertUtils.toTaints(bizTaintList)).endSpec().done(); + return BizConvertUtils.toBizNode(node); + }catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "NodeApiImpl.delTaint error:{}", e); + return new BizNode().error(String.valueOf(e.getCode()), e.getMessage()); + } + } + + /** + * 删除污点 + * + * @param nodeName 节点名称 + * @return BizNode + */ + @Override + public BizNode delTaint(String nodeName) { + try { + if (StringUtils.isEmpty(nodeName)){ + return new BizNode().errorBadRequest(); + } + Node nodeInfo = client.nodes().withName(nodeName).get(); + if (nodeInfo == null){ + return new BizNode().error(K8sResponseEnum.NOT_FOUND.getCode(), "节点["+nodeName+"]不存在"); + } + + List taints = nodeInfo.getSpec().getTaints(); + Taint taint = new Taint(); + for (Taint obj : taints){ + if (K8sLabelConstants.PLATFORM_TAG_ISOLATION_KEY.equals(obj.getKey())){ + taint = obj; + } + } + + Node node = client.nodes().withName(nodeName) + .edit() + .editSpec() + .removeFromTaints(taint) + .endSpec() + .done(); + return BizConvertUtils.toBizNode(node); + }catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "NodeApiImpl.delTaint error:{}", e); + return new BizNode().error(String.valueOf(e.getCode()), e.getMessage()); + } + } + + + /** + * 根据id获取 node资源隔离 标志 + * + * @param isolationId + * @return node资源隔离 标志 + */ + @Override + public String getNodeIsolationValue(Long isolationId){ + return StrUtil.format(K8sLabelConstants.PLATFORM_TAG_ISOLATION_VALUE, SpringContextHolder.getActiveProfile(),isolationId); + } + + /** + * 获取当前用户 + * + * @return node资源隔离 标志 + */ + @Override + public String getNodeIsolationValue() { + return StrUtil.format(K8sLabelConstants.PLATFORM_TAG_ISOLATION_VALUE, SpringContextHolder.getActiveProfile(),userContextService.getCurUserId()); + } + + /** + * 获取当前用户资源隔离 Toleration + * + * @return Toleration + */ + @Override + public Toleration getNodeIsolationToleration() { + List nodes = getWithLabel(K8sLabelConstants.PLATFORM_TAG_ISOLATION_KEY,getNodeIsolationValue()); + if (CollectionUtils.isEmpty(nodes)){ + return null; + } + return ResourceBuildUtils.buildNoScheduleEqualToleration(K8sLabelConstants.PLATFORM_TAG_ISOLATION_KEY,getNodeIsolationValue()); + } + + /** + * 获取当前用户 资源隔离 NodeSelector + * @return Map + */ + @Override + public Map getNodeIsolationNodeSelector() { + Map nodeSelector = new HashMap<>(MagicNumConstant.TWO); + nodeSelector.put(K8sLabelConstants.PLATFORM_TAG_ISOLATION_KEY,getNodeIsolationValue()); + return nodeSelector; + } + + /** + * 根据userid 生成 BizTaint 列表 + * + * @param userId + * @return + */ + @Override + public List geBizTaintListByUserId(Long userId) { + List bizTaintList = new ArrayList<>(); + BizTaint bizTaint = new BizTaint(); + bizTaint.setEffect(K8sTolerationEffectEnum.NOSCHEDULE.getEffect()); + bizTaint.setKey(K8sLabelConstants.PLATFORM_TAG_ISOLATION_KEY); + bizTaint.setValue(getNodeIsolationValue(userId)); + bizTaintList.add(bizTaint); + return bizTaintList; + } + + /** + * 根据当前用户 生成 BizTaint 列表 + * + * @return + */ + @Override + public List geBizTaintListByUserId() { + return geBizTaintListByUserId(userContextService.getCurUserId()); + } + + + /** + * 查询节点内存资源是否可分配 + * + * @param memNum 单位为Mi 1Mi等于1024Ki + * @param nodeItems Node集合 + * @return List Node集合 + */ + private List isMemAllocatable(int memNum, List nodeItems) { + List nodeItemResults = new ArrayList<>(); + List nodeNameList = new ArrayList<>(); + List nodeMetrics = metricsApi.getNodeMetrics(); + + nodeItems.forEach(nodeItem -> { + String nodeName = nodeItem.getMetadata().getName(); + List collect = nodeMetrics.stream().filter(nodeMetric -> nodeMetric.getNodeName().equals(nodeName)).collect(Collectors.toList()); + if (!CollectionUtils.isEmpty(collect)){ + String memAmount = collect.get(0).getMemoryUsageAmount(); + int memCapacity = Integer.parseInt(nodeItem.getStatus().getCapacity().get(K8sParamConstants.QUANTITY_MEMORY_KEY).getAmount()) / MagicNumConstant.ONE_THOUSAND; + int memAmountInt = Integer.parseInt(memAmount) / MagicNumConstant.BINARY_TEN_EXP; + if (memCapacity - memAmountInt > memNum) { + nodeNameList.add(nodeName); + } + } + + }); + + nodeNameList.forEach(nodeName -> { + List collect = nodeItems.stream().filter(nodeItem -> nodeItem.getMetadata().getName().equals(nodeName)).collect(Collectors.toList()); + nodeItemResults.addAll(collect); + }); + + return nodeItemResults; + } + + + /** + * 查询节点Cpu资源是否可分配 + * + * @param cpuNum 单位为m 1核等于1000m + * @param nodeItems Node集合 + * @return List Node集合 + */ + private List isCpuAllocatable(int cpuNum, List nodeItems) { + + List nodeItemResults = new ArrayList<>(); + List nodeNameList = new ArrayList<>(); + List nodeMetrics = metricsApi.getNodeMetrics(); + + nodeItems.forEach(nodeItem -> { + String nodeName = nodeItem.getMetadata().getName(); + List collect = nodeMetrics.stream().filter(nodeMetric -> nodeMetric.getNodeName().equals(nodeName)).collect(Collectors.toList()); + if (!CollectionUtils.isEmpty(collect)){ + String cpuAmount = collect.get(0).getCpuUsageAmount(); + int cpuCapacity = Integer.parseInt(nodeItem.getStatus().getCapacity().get(K8sParamConstants.QUANTITY_CPU_KEY).getAmount()) * MagicNumConstant.ONE_THOUSAND; + int cpuAmountInt = (int) (Long.parseLong(cpuAmount) / MagicNumConstant.ONE_THOUSAND / MagicNumConstant.ONE_THOUSAND); + if (cpuCapacity - cpuAmountInt >= cpuNum) { + nodeNameList.add(nodeName); + } + } + }); + + nodeNameList.forEach(nodeName -> { + List collect = nodeItems.stream().filter(nodeItem -> nodeItem.getMetadata().getName().equals(nodeName)).collect(Collectors.toList()); + nodeItemResults.addAll(collect); + }); + + return nodeItemResults; + } + + + /** + * 查询节点Gpu资源是否可分配 + * + * @param gpuNum 单位为显卡,即"1"表示1张显卡 + * @param nodeItems Node集合 + * @return List Node集合 + */ + private List isGpuAllocatable(int gpuNum, List nodeItems) { + List nodeItemResults = new ArrayList<>(); + List nodeNameList = new ArrayList<>(); + nodeItems = nodeItems.stream().filter(node -> node.getStatus().getCapacity().containsKey(K8sParamConstants.GPU_RESOURCE_KEY)).collect(Collectors.toList()); + + List podItems = filterRequestGpuPod(); + Map allocatableGpu = new HashMap(); + + for (Node nodeItem : nodeItems) { + int totalGpuAmount = 0; + int totalGpu = Integer.parseInt(nodeItem.getStatus().getCapacity().get(K8sParamConstants.GPU_RESOURCE_KEY).getAmount()); + String nodeName = nodeItem.getMetadata().getName(); + List nodePodItems = podItems.stream().filter(pod -> pod.getSpec().getNodeName().equals(nodeName)).collect(Collectors.toList()); + for (Pod pod : nodePodItems) { + String gpuAmount = pod.getSpec().getContainers().get(0).getResources().getLimits().get(K8sParamConstants.GPU_RESOURCE_KEY).getAmount(); + totalGpuAmount = totalGpuAmount + Integer.parseInt(gpuAmount); + } + allocatableGpu.put(nodeName, totalGpu - totalGpuAmount); + + } + Set keySet = allocatableGpu.keySet(); + + keySet.forEach(key -> { + if (allocatableGpu.get(key) >= gpuNum) { + nodeNameList.add(key); + } + }); + + for (String nodeName : nodeNameList) { + List collect = nodeItems.stream().filter(nodeItem -> nodeItem.getMetadata().getName().equals(nodeName)).collect(Collectors.toList()); + nodeItemResults.addAll(collect); + } + return nodeItemResults; + } + + /** + * 获取申请了gpu的pod列表 + * @return + */ + private List filterRequestGpuPod(){ + PodList podList = client.pods().list(); + if (CollectionUtil.isNotEmpty(podList.getItems())){ + return podList.getItems().stream().filter(pod -> + pod.getSpec().getContainers().get(0).getResources().getLimits() != null && + pod.getSpec().getContainers().get(0).getResources().getLimits().containsKey(K8sParamConstants.GPU_RESOURCE_KEY) && + pod.getStatus().getPhase().equals(PodPhaseEnum.RUNNING.getPhase())).collect(Collectors.toList()); + } + return new ArrayList<>(); + } + + /** + * 查询集群已分配gpu数量 + * @return + */ + private Integer getAllocatedGpuNum(){ + return filterRequestGpuPod().stream().mapToInt(pod-> + pod.getSpec().getContainers().stream().mapToInt(container -> + Integer.valueOf(String.valueOf(container.getResources().getLimits().get(K8sParamConstants.GPU_RESOURCE_KEY).getAmount()))).sum()) + .sum(); + } + + /** + * 查询集群总gpu数量 + * @return + */ + private Integer getTotalGpuNum(){ + return listAll().stream() + .filter(node -> !node.isUnschedulable() && node.getCapacity().containsKey(K8sParamConstants.GPU_RESOURCE_KEY) && CollectionUtils.isEmpty(node.getTaints())) + .mapToInt(node -> Integer.valueOf(String.valueOf(node.getCapacity().get(K8sParamConstants.GPU_RESOURCE_KEY).getAmount()))).sum(); + } + + /** + * 查询节点是否存在指定的污点 + * @return + */ + private boolean doesTaintExit(Node node, BizTaint bizTaint){ + List taints = node.getSpec().getTaints().stream().filter(taint -> + StringUtils.equalsAny(taint.getKey(), bizTaint.getKey()) + && StringUtils.equalsAny(taint.getValue(), bizTaint.getValue())) + .collect(Collectors.toList()); + return CollectionUtil.isNotEmpty(taints); + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/impl/PersistentVolumeClaimApiImpl.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/impl/PersistentVolumeClaimApiImpl.java new file mode 100644 index 0000000..f1046e4 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/impl/PersistentVolumeClaimApiImpl.java @@ -0,0 +1,369 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.api.impl; + +import io.fabric8.kubernetes.api.model.*; +import io.fabric8.kubernetes.api.model.storage.StorageClass; +import io.fabric8.kubernetes.api.model.storage.StorageClassBuilder; +import io.fabric8.kubernetes.client.KubernetesClient; +import io.fabric8.kubernetes.client.KubernetesClientException; +import org.dubhe.biz.base.constant.MagicNumConstant; +import org.dubhe.biz.base.utils.StringUtils; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.dubhe.k8s.api.PersistentVolumeClaimApi; +import org.dubhe.k8s.constant.K8sParamConstants; +import org.dubhe.k8s.domain.PtBaseResult; +import org.dubhe.k8s.domain.bo.PtPersistentVolumeClaimBO; +import org.dubhe.k8s.domain.resource.BizPersistentVolumeClaim; +import org.dubhe.k8s.enums.AccessModeEnum; +import org.dubhe.k8s.enums.K8sKindEnum; +import org.dubhe.k8s.enums.PvReclaimPolicyEnum; +import org.dubhe.k8s.utils.BizConvertUtils; +import org.dubhe.k8s.utils.K8sUtils; +import org.dubhe.k8s.utils.LabelUtils; +import org.dubhe.k8s.utils.YamlUtils; +import org.springframework.beans.factory.annotation.Value; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * @description pvc api + * @date 2020-04-23 + */ +public class PersistentVolumeClaimApiImpl implements PersistentVolumeClaimApi { + private K8sUtils k8sUtils; + private KubernetesClient client; + + private final static String STORAGE_CLASS_API_VERSION = "storage.k8s.io/v1"; + private final static String PV = "pv"; + private final static String PV_SUFFIX = "-pv"; + private final static String STORAGE = "storage"; + private final static String STORAGE_CLASS_SUFFIX = "-storageclass"; + private final static String HOSTPATH_RECYCLING_STRATEGY = "DirectoryOrCreate"; + private final static String PROVISIONER = "k8s.io/minikube-hostpath"; + + @Value("${k8s.nfs-storage-class-name}") + private String nfsStorageClassName; + + public PersistentVolumeClaimApiImpl(K8sUtils k8sUtils) { + this.k8sUtils = k8sUtils; + this.client = k8sUtils.getClient(); + } + + /** + * 创建PVC + * + * @param bo PVC BO + * @return BizPersistentVolumeClaim PVC业务类 + */ + @Override + public BizPersistentVolumeClaim create(PtPersistentVolumeClaimBO bo) { + if (bo == null || StringUtils.isEmpty(bo.getNamespace()) || StringUtils.isEmpty(bo.getPvcName()) || StringUtils.isEmpty(bo.getRequest())) { + return new BizPersistentVolumeClaim().errorBadRequest(); + } + try { + Map storageClassLabels = LabelUtils.getChildLabels(bo.getResourceName(), bo.getPvcName(), K8sKindEnum.PERSISTENTVOLUMECLAIM.getKind()); + + Map pvcLabels = LabelUtils.getChildLabels(bo.getResourceName(), bo.getNamespace(), K8sKindEnum.NAMESPACE.getKind()); + + //创建StorageClass + ObjectMeta metadata = new ObjectMeta(); + metadata.setName(getStorageClassName(bo.getPvcName())); + metadata.setNamespace(bo.getNamespace()); + metadata.setLabels(storageClassLabels); + StorageClass storageClass = new StorageClassBuilder().withApiVersion(STORAGE_CLASS_API_VERSION) + .withKind(K8sKindEnum.STORAGECLASS.getKind()) + .withMetadata(metadata) + .withParameters(bo.getParameters()) + .withProvisioner(bo.getProvisioner()==null?PROVISIONER:bo.getProvisioner()) + .build(); + storageClass = client.storage().storageClasses().inNamespace(bo.getNamespace()).createOrReplace(storageClass); + LogUtil.info(LogEnum.BIZ_K8S, YamlUtils.dumpAsYaml(storageClass)); + //创建pvc + PersistentVolumeClaim pvc = new PersistentVolumeClaimBuilder() + .withNewMetadata().withName(bo.getPvcName()).addToLabels(pvcLabels).addToLabels(bo.getLabels()).endMetadata() + .withNewSpec().addAllToAccessModes(bo.getAccessModes()) + .withNewResources().addToRequests(STORAGE, new Quantity(bo.getRequest())).endResources() + .withNewStorageClassName(getStorageClassName(bo.getPvcName())).endSpec().build(); + if (StringUtils.isNotEmpty(bo.getLimit())) { + pvc.getSpec().getResources().setLimits(new HashMap() {{ + put(STORAGE, new Quantity(bo.getLimit())); + }}); + } + LogUtil.info(LogEnum.BIZ_K8S, YamlUtils.dumpAsYaml(pvc)); + return BizConvertUtils.toBizPersistentVolumeClaim(client.persistentVolumeClaims().inNamespace(bo.getNamespace()).create(pvc)); + } catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "PersistentVolumeClaimApi.create error, param:{} error:{}", bo, e); + return new BizPersistentVolumeClaim().error(String.valueOf(e.getCode()), e.getMessage()); + } + } + + /** + * 创建挂载文件存储服务 PV + * + * @param bo PVC bo + * @return BizPersistentVolumeClaim PVC业务类 + */ + @Override + public BizPersistentVolumeClaim createWithFsPv(PtPersistentVolumeClaimBO bo) { + if (bo == null || StringUtils.isEmpty(bo.getNamespace()) || StringUtils.isEmpty(bo.getPvcName()) || StringUtils.isEmpty(bo.getRequest())) { + return new BizPersistentVolumeClaim().errorBadRequest(); + } + try { + Map pvLabels = LabelUtils.getChildLabels(bo.getResourceName(), bo.getPvcName(), K8sKindEnum.PERSISTENTVOLUMECLAIM.getKind()); + pvLabels.put(PV, bo.getPvcName() + PV_SUFFIX); + + if (client.persistentVolumes().withName(bo.getPvcName() + PV_SUFFIX).get() == null) { + //创建pv + PersistentVolume pv = new PersistentVolumeBuilder() + .withNewMetadata().addToLabels(pvLabels).withName(bo.getPvcName() + PV_SUFFIX).endMetadata() + .withNewSpec().addToCapacity(STORAGE, new Quantity(bo.getRequest())).addNewAccessMode(AccessModeEnum.READ_WRITE_ONCE.getType()).withNewPersistentVolumeReclaimPolicy(PvReclaimPolicyEnum.RECYCLE.getPolicy()) + .withNewHostPath().withNewPath(bo.getPath()).withType(K8sParamConstants.HOST_PATH_TYPE).endHostPath() + .endSpec() + .build(); + LogUtil.info(LogEnum.BIZ_K8S, YamlUtils.dumpAsYaml(pv)); + client.persistentVolumes().createOrReplace(pv); + } + + Map pvcLabels = LabelUtils.getChildLabels(bo.getResourceName(), bo.getNamespace(), K8sKindEnum.NAMESPACE.getKind()); + + PersistentVolumeClaim old = client.persistentVolumeClaims().inNamespace(bo.getNamespace()).withName(bo.getPvcName()).get(); + if (old == null) { + //创建pvc + PersistentVolumeClaim pvc = new PersistentVolumeClaimBuilder() + .withNewMetadata().withName(bo.getPvcName()).addToLabels(pvcLabels).addToLabels(bo.getLabels()).endMetadata() + .withNewSpec().addAllToAccessModes(bo.getAccessModes()) + .withNewSelector().addToMatchLabels(PV, bo.getPvcName() + PV_SUFFIX).endSelector() + .withNewResources().addToRequests(STORAGE, new Quantity(bo.getRequest())).endResources() + .endSpec().build(); + if (StringUtils.isNotEmpty(bo.getLimit())) { + pvc.getSpec().getResources().setLimits(new HashMap(MagicNumConstant.SIXTEEN) {{ + put(STORAGE, new Quantity(bo.getLimit())); + }}); + } + LogUtil.info(LogEnum.BIZ_K8S, YamlUtils.dumpAsYaml(pvc)); + pvc = client.persistentVolumeClaims().inNamespace(bo.getNamespace()).createOrReplace(pvc); + return BizConvertUtils.toBizPersistentVolumeClaim(pvc); + } else { + return BizConvertUtils.toBizPersistentVolumeClaim(old); + } + + } catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "PersistentVolumeClaimApiImpl.createWithFsPv error, param:{} error:{}", bo, e); + return new BizPersistentVolumeClaim().error(String.valueOf(e.getCode()), e.getMessage()); + } + } + + /** + * 创建挂载直接存储 PV + * + * @param bo PVC BO + * @return BizPersistentVolumeClaim PVC业务类 + */ + @Override + public BizPersistentVolumeClaim createWithDirectPv(PtPersistentVolumeClaimBO bo) { + if (bo == null || StringUtils.isEmpty(bo.getNamespace()) || StringUtils.isEmpty(bo.getPvcName()) || StringUtils.isEmpty(bo.getRequest())) { + return new BizPersistentVolumeClaim().errorBadRequest(); + } + try { + Map pvLabels = LabelUtils.getChildLabels(bo.getResourceName(), bo.getPvcName(), K8sKindEnum.PERSISTENTVOLUMECLAIM.getKind()); + pvLabels.put(PV, bo.getPvcName() + PV_SUFFIX); + + if (client.persistentVolumes().withName(bo.getPvcName() + PV_SUFFIX).get() == null) { + //创建pv + PersistentVolume pv = new PersistentVolumeBuilder() + .withNewMetadata().addToLabels(pvLabels).withName(bo.getPvcName() + PV_SUFFIX).endMetadata() + .withNewSpec().addToCapacity(STORAGE, new Quantity(bo.getRequest())).addNewAccessMode(AccessModeEnum.READ_WRITE_ONCE.getType()).withNewPersistentVolumeReclaimPolicy("Recycle") + .withNewHostPath(bo.getPath(),HOSTPATH_RECYCLING_STRATEGY) + .endSpec() + .build(); + LogUtil.info(LogEnum.BIZ_K8S, YamlUtils.dumpAsYaml(pv)); + client.persistentVolumes().createOrReplace(pv); + } + + Map pvcLabels = LabelUtils.getChildLabels(bo.getResourceName(), bo.getNamespace(), K8sKindEnum.NAMESPACE.getKind()); + + PersistentVolumeClaim old = client.persistentVolumeClaims().inNamespace(bo.getNamespace()).withName(bo.getPvcName()).get(); + if (old == null) { + //创建pvc + PersistentVolumeClaim pvc = new PersistentVolumeClaimBuilder() + .withNewMetadata().withName(bo.getPvcName()).addToLabels(pvcLabels).addToLabels(bo.getLabels()).endMetadata() + .withNewSpec().addAllToAccessModes(bo.getAccessModes()) + .withNewSelector().addToMatchLabels(PV, bo.getPvcName() + PV_SUFFIX).endSelector() + .withNewResources().addToRequests(STORAGE, new Quantity(bo.getRequest())).endResources() + .endSpec().build(); + if (StringUtils.isNotEmpty(bo.getLimit())) { + pvc.getSpec().getResources().setLimits(new HashMap(MagicNumConstant.SIXTEEN) {{ + put(STORAGE, new Quantity(bo.getLimit())); + }}); + } + LogUtil.info(LogEnum.BIZ_K8S, YamlUtils.dumpAsYaml(pvc)); + pvc = client.persistentVolumeClaims().inNamespace(bo.getNamespace()).createOrReplace(pvc); + return BizConvertUtils.toBizPersistentVolumeClaim(pvc); + } else { + return BizConvertUtils.toBizPersistentVolumeClaim(old); + } + + } catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "PersistentVolumeClaimApiImpl.createWithDirectPv error, param:{} error:{}", bo, e); + return new BizPersistentVolumeClaim().error(String.valueOf(e.getCode()), e.getMessage()); + } + } + + /** + * 创建创建自动挂载nfs动态存储的PVC + * + * @param bo PVC bo + * @return BizPersistentVolumeClaim PVC业务类 + */ + @Override + public BizPersistentVolumeClaim createDynamicNfs(PtPersistentVolumeClaimBO bo) { + if (bo == null || StringUtils.isEmpty(bo.getNamespace()) || StringUtils.isEmpty(bo.getPvcName()) || StringUtils.isEmpty(bo.getRequest())) { + return new BizPersistentVolumeClaim().errorBadRequest(); + } + try { + Map pvcLabels = LabelUtils.getChildLabels(bo.getResourceName(), bo.getNamespace(), K8sKindEnum.NAMESPACE.getKind()); + + PersistentVolumeClaim old = client.persistentVolumeClaims().inNamespace(bo.getNamespace()).withName(bo.getPvcName()).get(); + if (old == null) { + //创建pvc + PersistentVolumeClaim pvc = new PersistentVolumeClaimBuilder() + .withNewMetadata().withName(bo.getPvcName()).addToLabels(pvcLabels).addToLabels(bo.getLabels()).endMetadata() + .withNewSpec().addAllToAccessModes(bo.getAccessModes()) + .withNewStorageClassName(nfsStorageClassName) + .withNewResources().addToRequests(STORAGE, new Quantity(bo.getRequest())).endResources() + .endSpec().build(); + if (StringUtils.isNotEmpty(bo.getLimit())) { + pvc.getSpec().getResources().setLimits(new HashMap(MagicNumConstant.SIXTEEN) {{ + put(STORAGE, new Quantity(bo.getLimit())); + }}); + } + pvc = client.persistentVolumeClaims().inNamespace(bo.getNamespace()).createOrReplace(pvc); + LogUtil.info(LogEnum.BIZ_K8S, YamlUtils.dumpAsYaml(pvc)); + return BizConvertUtils.toBizPersistentVolumeClaim(pvc); + } else { + return BizConvertUtils.toBizPersistentVolumeClaim(old); + } + + } catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "PersistentVolumeClaimApiImpl.createDynamicNfs error, param:{} error:{}", bo, e); + return new BizPersistentVolumeClaim().error(String.valueOf(e.getCode()), e.getMessage()); + } + } + + /** + * 查询命名空间下所有 PVC + * + * @param namespace 命名空间 + * @return List PVC业务类集合 + */ + @Override + public List list(String namespace) { + if (StringUtils.isEmpty(namespace)) { + return Collections.EMPTY_LIST; + } + PersistentVolumeClaimList persistentVolumeClaimList = client.persistentVolumeClaims().inNamespace(namespace).list(); + return persistentVolumeClaimList.getItems().parallelStream().map(obj -> BizConvertUtils.toBizPersistentVolumeClaim(obj)).collect(Collectors.toList()); + } + + /** + * 删除具体的PVC + * + * @param namespace 命名空间 + * @param pvcName PVC名称 + * @return PtBaseResult 基础结果类 + */ + @Override + public PtBaseResult delete(String namespace, String pvcName) { + if (StringUtils.isEmpty(namespace) || StringUtils.isEmpty(pvcName)) { + return new PtBaseResult().baseErrorBadRequest(); + } + try { + client.storage().storageClasses().inNamespace(namespace).withName(getStorageClassName(pvcName)).delete(); + client.persistentVolumeClaims().inNamespace(namespace).withName(pvcName).delete(); + return new PtBaseResult(); + } catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "PersistentVolumeClaimApiImpl.delete error, param:[namespace]={}, error:{}", namespace, e); + return new PtBaseResult(String.valueOf(e.getCode()), e.getMessage()); + } + } + + /** + * 回收存储(recycle 的pv才能回收) + * + * @param namespace 命名空间 + * @param resourceName 资源名称 + * @return PtBaseResult 基础结果类 + */ + @Override + public PtBaseResult recycle(String namespace, String resourceName) { + if (StringUtils.isEmpty(namespace) || StringUtils.isEmpty(resourceName)) { + return new PtBaseResult().baseErrorBadRequest(); + } + try { + client.persistentVolumeClaims().inNamespace(namespace).withLabels(LabelUtils.withEnvResourceName(resourceName)).delete(); + client.persistentVolumes().withLabels(LabelUtils.withEnvResourceName(resourceName)).delete(); + return new PtBaseResult(); + } catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "PersistentVolumeClaimApiImpl.recycle error, param:[namespace]={}, [resourceName]={}, error:{}",namespace, resourceName, e); + return new PtBaseResult(String.valueOf(e.getCode()), e.getMessage()); + } + } + + /** + * 拼接storageClassName + * + * @param pvcName PVC名称 + * @return String 动态PVC的名称 + */ + @Override + public String getStorageClassName(String pvcName) { + if (StringUtils.isEmpty(pvcName)) { + return null; + } else { + return pvcName + STORAGE_CLASS_SUFFIX; + } + } + + /** + * 删除PV + * + * @param pvName PV名称 + * @return boolean true成功 false失败 + */ + @Override + public boolean deletePv(String pvName) { + return client.persistentVolumes().withName(pvName).delete(); + } + + /** + * 查询PV + * + * @param pvName PV名称 + * @return PersistentVolume PV实体类 + */ + @Override + public PersistentVolume getPv(String pvName) { + return client.persistentVolumes().withName(pvName).get(); + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/impl/PodApiImpl.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/impl/PodApiImpl.java new file mode 100644 index 0000000..643ff26 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/impl/PodApiImpl.java @@ -0,0 +1,446 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.api.impl; + +import cn.hutool.core.collection.CollectionUtil; +import cn.hutool.core.io.IORuntimeException; +import cn.hutool.core.util.StrUtil; +import cn.hutool.http.HttpRequest; +import cn.hutool.http.HttpResponse; +import cn.hutool.http.HttpStatus; +import io.fabric8.kubernetes.api.model.Pod; +import io.fabric8.kubernetes.api.model.PodList; +import io.fabric8.kubernetes.client.KubernetesClient; +import io.fabric8.kubernetes.client.KubernetesClientException; +import org.dubhe.biz.base.constant.SymbolConstant; +import org.dubhe.biz.base.utils.RegexUtil; +import org.dubhe.biz.base.utils.StringUtils; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.dubhe.k8s.api.JupyterResourceApi; +import org.dubhe.k8s.api.MetricsApi; +import org.dubhe.k8s.api.PodApi; +import org.dubhe.k8s.constant.K8sParamConstants; +import org.dubhe.k8s.domain.bo.LabelBO; +import org.dubhe.k8s.domain.resource.BizPod; +import org.dubhe.k8s.domain.vo.PtJupyterDeployVO; +import org.dubhe.k8s.domain.vo.PtPodsVO; +import org.dubhe.k8s.enums.K8sResponseEnum; +import org.dubhe.k8s.enums.PodPhaseEnum; +import org.dubhe.k8s.utils.BizConvertUtils; +import org.dubhe.k8s.utils.K8sUtils; +import org.dubhe.k8s.utils.LabelUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.util.CollectionUtils; + +import java.util.*; +import java.util.stream.Collectors; + +/** + * @description PodApi实现类 + * @date 2020-04-15 + */ +public class PodApiImpl implements PodApi { + + private static final String TOKEN_REGEX = "token=[\\d|a-z]*"; + private static final String POD_URL = "http://{}:{}?{}"; + + private K8sUtils k8sUtils; + private KubernetesClient client; + + @Autowired + private JupyterResourceApi jupyterResourceApi; + @Autowired + private MetricsApi metricsApi; + + public PodApiImpl(K8sUtils k8sUtils) { + this.k8sUtils = k8sUtils; + this.client = k8sUtils.getClient(); + } + + /** + * 根据Pod名称和命名空间查询Pod + * + * @param namespace 命名空间 + * @param podName Pod名称 + * @return BizPod Pod业务类 + */ + @Override + public BizPod get(String namespace, String podName) { + try{ + LogUtil.info(LogEnum.BIZ_K8S,"Input namespace={};podName={}", namespace,podName); + if (StringUtils.isEmpty(namespace)) { + return new BizPod().baseErrorBadRequest(); + } + Pod pod = client.pods().inNamespace(namespace).withName(podName).get(); + BizPod bizPod = BizConvertUtils.toBizPod(pod); + LogUtil.info(LogEnum.BIZ_K8S,"Output {}", bizPod); + return bizPod; + }catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "PodApiImpl.get error, param:[namespace]={}, [podName]={}, error:{}",namespace, podName, e); + return new BizPod().error(String.valueOf(e.getCode()),e.getMessage()); + } + } + + /** + * 根据Pod名称列表和命名空间查询Pod列表 + * + * @param namespace 命名空间 + * @param podNames Pod名称 + * @return List Pod业务类列表 + */ + @Override + public List get(String namespace, List podNames) { + try{ + List bizPodList = new ArrayList<>(); + LogUtil.info(LogEnum.BIZ_K8S,"Input namespace={};podNames={}", namespace,podNames); + if (StringUtils.isEmpty(namespace)) { + return bizPodList; + } + PodList podList = client.pods().inNamespace(namespace).list(); + if (podList == null || CollectionUtils.isEmpty(podList.getItems())){ + return bizPodList; + } + for (Pod pod : podList.getItems()){ + if (podNames.contains(pod.getMetadata().getName())){ + bizPodList.add(BizConvertUtils.toBizPod(pod)); + } + } + return bizPodList; + }catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "PodApiImpl.get error, param:[namespace]={}, [podNames]={}, error:{}",namespace, podNames, e); + return new ArrayList<>(); + } + } + + /** + * 根据命名空间和资源名查询Pod + * + * @param namespace 命名空间 + * @param resourceName 资源名称 + * @return BizPod Pod业务类 + */ + @Override + public BizPod getWithResourceName(String namespace, String resourceName) { + try { + LogUtil.info(LogEnum.BIZ_K8S,"Input namespace={};resourceName={}", namespace,resourceName); + if (StringUtils.isEmpty(namespace)) { + return new BizPod().baseErrorBadRequest(); + } + PodList podList = client.pods().inNamespace(namespace).withLabels(LabelUtils.withEnvResourceName(resourceName)).list(); + if (CollectionUtil.isEmpty(podList.getItems())) { + return new BizPod().error(K8sResponseEnum.NOT_FOUND.getCode(), K8sResponseEnum.NOT_FOUND.getMessage()); + } + Pod pod = podList.getItems().get(0); + BizPod bizPod = BizConvertUtils.toBizPod(pod); + LogUtil.info(LogEnum.BIZ_K8S,"Output {}", bizPod); + return bizPod; + }catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "PodApiImpl.getWithResourceName error, param:[namespace]={}, [resourceName]={}, error:{}",namespace, resourceName, e); + return new BizPod().error(String.valueOf(e.getCode()),e.getMessage()); + } + } + + /** + * 根据命名空间和资源名查询Pod集合 + * + * @param namespace 命名空间 + * @param resourceName 资源名称 + * @return List Pod业务类集合 + */ + @Override + public List getListByResourceName(String namespace, String resourceName) { + try{ + LogUtil.info(LogEnum.BIZ_K8S,"Input namespace={};resourceName={}", namespace,resourceName); + if (StringUtils.isEmpty(namespace)) { + return Collections.EMPTY_LIST; + } + PodList podList = client.pods().inNamespace(namespace).withLabels(LabelUtils.withEnvResourceName(resourceName)).list(); + if (CollectionUtil.isEmpty(podList.getItems())) { + return Collections.EMPTY_LIST; + } + List bizPodList = BizConvertUtils.toBizPodList(podList.getItems()); + LogUtil.info(LogEnum.BIZ_K8S,"Output {}", bizPodList); + return bizPodList; + }catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "PodApiImpl.getWithResourceName error, param:[namespace]={}, [resourceName]={}, error:{}",namespace, resourceName, e); + return Collections.EMPTY_LIST; + } + } + + /** + * 查询命名空间下所有Pod + * + * @param namespace 命名空间 + * @return List Pod业务类集合 + */ + @Override + public List getWithNamespace(String namespace) { + try{ + List bizPodList = new ArrayList<>(); + PodList podList = client.pods().inNamespace(namespace).list(); + if (CollectionUtil.isEmpty(podList.getItems())) { + return bizPodList; + } + bizPodList = BizConvertUtils.toBizPodList(podList.getItems()); + LogUtil.info(LogEnum.BIZ_K8S,"Output {}", bizPodList); + return bizPodList; + }catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "PodApiImpl.getWithNamespace error, param:[namespace]={}, error:{}",namespace, e); + return Collections.EMPTY_LIST; + } + + } + + /** + * 查询集群所有Pod + * + * @return List Pod业务类集合 + */ + @Override + public List listAll() { + try{ + List bizPodList = client.pods().inAnyNamespace().list().getItems().parallelStream().map(obj -> BizConvertUtils.toBizPod(obj)).collect(Collectors.toList()); + LogUtil.info(LogEnum.BIZ_K8S,"Output {}", bizPodList); + return bizPodList; + }catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "PodApiImpl.listAll error:", e); + return Collections.EMPTY_LIST; + } + } + + /** + *根据dtname查询pod信息 + * + * @param dtname 自定义dt的名称 + * @return List pod业务类集合 + */ + @Override + public List findByDtName(String dtname) { + List items = client.pods().list().getItems(); + LogUtil.info(LogEnum.BIZ_K8S,"Output {}",items); + List bizPods = new ArrayList<>(); + if (!(CollectionUtil.isEmpty(items))) { + items.stream().forEach(pod -> { + Map labels = pod.getMetadata().getLabels(); + if (labels != null) { + String dtName = labels.get("dt-name"); + if (dtName != null) { + if (dtName.equals(dtname)) { + bizPods.add(BizConvertUtils.toBizPod(pod)); + } + } + } + }); + } + return bizPods; + } + + /** + * 根据Node分组获得所有运行中的Pod + * + * @return Map> 键为Node名称,值为Pod业务类集合 + */ + @Override + public Map> listAllRuningPodGroupByNodeName() { + try{ + List bizPodList = client.pods().inAnyNamespace().list().getItems().parallelStream().map(obj -> BizConvertUtils.toBizPod(obj)).collect(Collectors.toList()); + Map> map = bizPodList.parallelStream().filter(pod -> PodPhaseEnum.RUNNING.getPhase().equals(pod.getPhase())).collect(Collectors.groupingBy(BizPod::getNodeName)); + LogUtil.info(LogEnum.BIZ_K8S,"Output {}", map); + return map; + }catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "PodApiImpl.listAllRunningPodGroupByNodeName error:{}", e); + return Collections.EMPTY_MAP; + } + } + + + /** + * 根据Node分组获取Pod信息 + * + * @return Map> 键为Node名称,值为Pod结果类集合 + */ + @Override + public Map> getPods(){ + try{ + Map> map = metricsApi.getPodsMetricsRealTime().stream().collect(Collectors.groupingBy(PtPodsVO::getNodeName)); + LogUtil.info(LogEnum.BIZ_K8S,"Output {}", map); + return map; + }catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "PodApiImpl.getPods error:{}", e); + return Collections.EMPTY_MAP; + } + } + + + /** + * 根据label查询Pod集合 + * + * @param labelBO k8s label资源 bo + * @return List Pod 实体类集合 + */ + @Override + public List list(LabelBO labelBO) { + return client.pods().inAnyNamespace().withLabels(LabelUtils.withEnvLabel(labelBO.getKey(), labelBO.getValue())).list().getItems(); + } + + /** + * 根据多个label查询Pod集合 + * + * @param labelBos label资源 bo 的集合 + * @return List Pod 实体类集合 + */ + @Override + public List list(Set labelBos) { + Map labelMap = labelBos.stream().collect(Collectors.toMap(LabelBO::getKey, LabelBO::getValue)); + return client.pods().inAnyNamespace().withLabels(labelMap).list().getItems(); + } + + /** + * 根据命名空间查询Pod集合 + * + * @param namespace 命名空间 + * @return List Pod 实体类集合 + */ + @Override + public List list(String namespace) { + return client.pods().inNamespace(namespace).list().getItems(); + } + + /** + * 根据命名空间和label查询Pod集合 + * + * @param namespace 命名空间 + * @param labelBO label资源 bo + * @return List Pod 实体类集合 + */ + @Override + public List list(String namespace, LabelBO labelBO) { + return client.pods().inNamespace(namespace).withLabels(LabelUtils.withEnvLabel(labelBO.getKey(), labelBO.getValue())).list().getItems(); + } + + /** + * 根据命名空间和多个label查询Pod集合 + * + * @param namespace 命名空间 + * @param labelBos label资源 bo 的集合 + * @return List Pod 实体类集合 + */ + @Override + public List list(String namespace, Set labelBos) { + Map labelMap = labelBos.stream().collect(Collectors.toMap(LabelBO::getKey, LabelBO::getValue)); + return client.pods().inNamespace(namespace).withLabels(labelMap).list().getItems(); + } + + + + /** + * 根据命名空间和Pod名称查询Token信息 + * + * @param namespace 命名空间 + * @param podName Pod名称 + * @return String token + */ + @Override + public String getToken(String namespace, String podName) { + try { + String podLog = client.pods().inNamespace(namespace).withName(podName).getLog(); + return RegexUtil.getMatcher(podLog, TOKEN_REGEX); + } catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "PodApiImpl.getToken error params:[namespace]={}, [podName]={}, error:{}",namespace, podName, e); + } + return ""; + } + + /** + * 根据命名空间和资源名获得Token信息 + * + * @param namespace 命名空间 + * @param resourceName 资源名称 + * @return String token + */ + @Override + public String getTokenByResourceName(String namespace, String resourceName) { + try { + PodList podList = client.pods().inNamespace(namespace).withLabels(LabelUtils.withEnvResourceName(resourceName)).list(); + if (podList != null && CollectionUtil.isNotEmpty(podList.getItems())) { + String podLog = client.pods().inNamespace(namespace).withName(podList.getItems().get(0).getMetadata().getName()).getLog(); + return RegexUtil.getMatcher(podLog, TOKEN_REGEX); + } + return ""; + } catch (Exception e) { + LogUtil.error(LogEnum.BIZ_K8S, "PodApiImpl.getTokenByResourceName error, params:[namespace]={}, [resourceName]={}, error:{}",namespace, resourceName, e); + } + return ""; + } + + /** + * 根据命名空间和资源名查询Notebook url + * + * @param namespace 命名空间 + * @param resourceName 资源名称 + * @return String validateJupyterUrl + */ + @Override + public String getUrlByResourceName(String namespace, String resourceName) { + LogUtil.info(LogEnum.BIZ_K8S,"Start GetUrlByResourceName {} {}",namespace,resourceName); + PtJupyterDeployVO info = jupyterResourceApi.get(namespace, resourceName); + if (info != null && info.getIngressInfo() != null && CollectionUtil.isNotEmpty(info.getIngressInfo().getRules())) { + String token = getTokenByResourceName(namespace, resourceName); + if (StringUtils.isBlank(token)) { + LogUtil.info(LogEnum.BIZ_K8S, "GetUrlByResourceName Jupyter Notebook token not generated,[namespace]={}, [resourceName]={}", namespace, resourceName); + return ""; + } + String url = StrUtil.format(POD_URL, info.getIngressInfo().getRules().get(0).getHost(), k8sUtils.getPort(), token); + return validateJupyterUrl(url); + } + LogUtil.info(LogEnum.BIZ_K8S, "GetUrlByResourceName Jupyter statefulset not created,[namespace]={}, [resourceName]={}",namespace,resourceName); + return ""; + } + + /** + * 验证访问Notebook的url + * + * @param jupyterUrl 访问Notebook的url + * @return String jupyterUrl jupyter路径 + */ + private String validateJupyterUrl(String jupyterUrl) { + if (StringUtils.isBlank(jupyterUrl) || !jupyterUrl.contains(SymbolConstant.QUESTION+ K8sParamConstants.TOKEN)){ + return ""; + } + try { + HttpRequest httpRequest = HttpRequest.get(jupyterUrl); + HttpResponse httpResponse = httpRequest.execute(); + if (httpResponse == null){ + LogUtil.info(LogEnum.BIZ_K8S, "ValidateJupyterUrl failed URL[{}] HttpResponse is null",jupyterUrl); + return ""; + } + int status = httpResponse.getStatus(); + if (HttpStatus.HTTP_OK != status && HttpStatus.HTTP_MOVED_TEMP != status){ + LogUtil.info(LogEnum.BIZ_K8S, "ValidateJupyterUrl failed URL[{}] status[{}]",jupyterUrl,status); + }else { + LogUtil.info(LogEnum.BIZ_K8S, "ValidateJupyterUrl success URL[{}] status[{}]",jupyterUrl,status); + return jupyterUrl; + } + }catch (IORuntimeException e){ + LogUtil.info(LogEnum.BIZ_K8S, "ValidateJupyterUrl failed URL[{}], error message[{}]",jupyterUrl, e.getMessage()); + } + return ""; + } + +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/impl/ResourceIisolationApiImpl.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/impl/ResourceIisolationApiImpl.java new file mode 100644 index 0000000..280729d --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/impl/ResourceIisolationApiImpl.java @@ -0,0 +1,124 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.api.impl; + +import io.fabric8.kubernetes.api.model.Toleration; +import io.fabric8.kubernetes.api.model.apps.Deployment; +import io.fabric8.kubernetes.api.model.apps.StatefulSet; +import io.fabric8.kubernetes.api.model.batch.Job; +import org.dubhe.k8s.api.NodeApi; +import org.dubhe.k8s.api.ResourceIisolationApi; +import org.dubhe.k8s.domain.cr.DistributeTrain; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.Arrays; + +/** + * @description + * @date 2021-05-20 + */ +@Service +public class ResourceIisolationApiImpl implements ResourceIisolationApi { + @Autowired + private NodeApi nodeApi; + + /** + * 添加 node资源隔离信息 Toleration 和 node Selector + * + * @param job + */ + @Override + public void addIisolationInfo(Job job) { + Toleration toleration = nodeApi.getNodeIsolationToleration(); + if (toleration == null){ + return; + } + if (null == job.getSpec().getTemplate().getSpec().getNodeSelector()){ + job.getSpec().getTemplate().getSpec().setNodeSelector(nodeApi.getNodeIsolationNodeSelector()); + }else { + job.getSpec().getTemplate().getSpec().getNodeSelector().putAll(nodeApi.getNodeIsolationNodeSelector()); + } + if (null == job.getSpec().getTemplate().getSpec().getTolerations()){ + job.getSpec().getTemplate().getSpec().setTolerations(Arrays.asList(toleration)); + }else { + job.getSpec().getTemplate().getSpec().getTolerations().addAll(Arrays.asList(toleration)); + } + } + + /** + * 添加 node资源隔离信息 Toleration 和 node Selector + * + * @param deployment + */ + @Override + public void addIisolationInfo(Deployment deployment) { + Toleration toleration = nodeApi.getNodeIsolationToleration(); + if (toleration == null){ + return; + } + if (null == deployment.getSpec().getTemplate().getSpec().getNodeSelector()){ + deployment.getSpec().getTemplate().getSpec().setNodeSelector(nodeApi.getNodeIsolationNodeSelector()); + }else { + deployment.getSpec().getTemplate().getSpec().getNodeSelector().putAll(nodeApi.getNodeIsolationNodeSelector()); + } + if (null == deployment.getSpec().getTemplate().getSpec().getTolerations()){ + deployment.getSpec().getTemplate().getSpec().setTolerations(Arrays.asList(toleration)); + }else { + deployment.getSpec().getTemplate().getSpec().getTolerations().addAll(Arrays.asList(toleration)); + } + } + + /** + * 添加 node资源隔离信息 Toleration 和 node Selector + * + * @param statefulSet + */ + @Override + public void addIisolationInfo(StatefulSet statefulSet) { + Toleration toleration = nodeApi.getNodeIsolationToleration(); + if (toleration == null){ + return; + } + if (null == statefulSet.getSpec().getTemplate().getSpec().getNodeSelector()){ + statefulSet.getSpec().getTemplate().getSpec().setNodeSelector(nodeApi.getNodeIsolationNodeSelector()); + }else { + statefulSet.getSpec().getTemplate().getSpec().getNodeSelector().putAll(nodeApi.getNodeIsolationNodeSelector()); + } + if (null == statefulSet.getSpec().getTemplate().getSpec().getTolerations()){ + statefulSet.getSpec().getTemplate().getSpec().setTolerations(Arrays.asList(toleration)); + }else { + statefulSet.getSpec().getTemplate().getSpec().getTolerations().addAll(Arrays.asList(toleration)); + } + } + + /** + * 添加 node资源隔离信息 Toleration 和 node Selector + * + * @param distributeTrain + */ + @Override + public void addIisolationInfo(DistributeTrain distributeTrain) { + Toleration toleration = nodeApi.getNodeIsolationToleration(); + if (toleration == null){ + return; + } + distributeTrain.getSpec().addNodeSelector(nodeApi.getNodeIsolationNodeSelector()); + distributeTrain.getSpec().addTolerations(Arrays.asList(toleration)); + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/impl/ResourceQuotaApiImpl.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/impl/ResourceQuotaApiImpl.java new file mode 100644 index 0000000..4d6289c --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/impl/ResourceQuotaApiImpl.java @@ -0,0 +1,236 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.api.impl; + +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; +import io.fabric8.kubernetes.api.model.Quantity; +import io.fabric8.kubernetes.api.model.ResourceQuota; +import io.fabric8.kubernetes.api.model.ResourceQuotaBuilder; +import io.fabric8.kubernetes.api.model.ResourceQuotaList; +import io.fabric8.kubernetes.api.model.ScopeSelector; +import io.fabric8.kubernetes.api.model.ScopeSelectorBuilder; +import io.fabric8.kubernetes.api.model.ScopedResourceSelectorRequirement; +import io.fabric8.kubernetes.client.KubernetesClient; +import io.fabric8.kubernetes.client.KubernetesClientException; +import org.dubhe.biz.base.constant.MagicNumConstant; +import org.dubhe.biz.base.constant.SymbolConstant; +import org.dubhe.biz.base.utils.StringUtils; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.dubhe.k8s.api.ResourceQuotaApi; +import org.dubhe.k8s.constant.K8sParamConstants; +import org.dubhe.k8s.domain.PtBaseResult; +import org.dubhe.k8s.domain.bo.PtResourceQuotaBO; +import org.dubhe.k8s.domain.resource.BizQuantity; +import org.dubhe.k8s.domain.resource.BizResourceQuota; +import org.dubhe.k8s.enums.K8sResponseEnum; +import org.dubhe.k8s.enums.LimitsOfResourcesEnum; +import org.dubhe.k8s.utils.BizConvertUtils; +import org.dubhe.k8s.utils.K8sUtils; +import org.dubhe.k8s.utils.UnitConvertUtils; +import org.springframework.util.CollectionUtils; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * @description 资源配额 接口实现 + * @date 2020-04-23 + */ +public class ResourceQuotaApiImpl implements ResourceQuotaApi { + private KubernetesClient client; + + public ResourceQuotaApiImpl(K8sUtils k8sUtils) { + this.client = k8sUtils.getClient(); + } + + /** + * 创建 ResourceQuota + * + * @param bo ResourceQuota BO + * @return BizResourceQuota ResourceQuota 业务类 + */ + @Override + public BizResourceQuota create(PtResourceQuotaBO bo) { + try { + LogUtil.info(LogEnum.BIZ_K8S,"Input bo={}", bo); + Gson gson = new Gson(); + List scopeSelector = gson.fromJson(gson.toJson(bo.getScopeSelector()), new TypeToken>() { + }.getType()); + Map hard = new HashMap<>(); + for (Map.Entry obj : bo.getHard().entrySet()) { + hard.put(obj.getKey(), new Quantity(obj.getValue().getAmount(), obj.getValue().getFormat())); + } + ResourceQuota resourceQuota = null; + if (scopeSelector != null){ + ScopeSelector item = new ScopeSelectorBuilder().addAllToMatchExpressions(scopeSelector).build(); + resourceQuota = new ResourceQuotaBuilder().withNewMetadata().withName(bo.getName()).endMetadata() + .withNewSpec().withHard(hard).withNewScopeSelectorLike(item).endScopeSelector().endSpec().build(); + + }else { + resourceQuota = new ResourceQuotaBuilder().withNewMetadata().withName(bo.getName()).endMetadata() + .withNewSpec().withHard(hard).endSpec().build(); + } + BizResourceQuota bizResourceQuota = BizConvertUtils.toBizResourceQuota(client.resourceQuotas().inNamespace(bo.getNamespace()).create(resourceQuota)); + LogUtil.info(LogEnum.BIZ_K8S,"Output {}", bizResourceQuota); + return bizResourceQuota; + } catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "ResourceQuotaApiImpl.create error, param:{} error:{}", bo, e); + return new BizResourceQuota().error(String.valueOf(e.getCode()),e.getMessage()); + } + } + + /** + * 创建 ResourceQuota + * @param namespace 命名空间 + * @param name ResourceQuota 名称 + * @param cpu cpu限制 单位核 0表示不限制 + * @param memory 内存限制 单位Gi 0表示不限制 + * @param gpu gpu限制 单位张 0表示不限制 + * @return + */ + @Override + public BizResourceQuota create(String namespace, String name, Integer cpu, Integer memory, Integer gpu) { + try { + LogUtil.info(LogEnum.BIZ_K8S,"Input namespace={},name={},cpu={},mem={},gpu={}", namespace,name,cpu,memory,gpu); + if (StringUtils.isEmpty(namespace)){ + return new BizResourceQuota().error(K8sResponseEnum.BAD_REQUEST.getCode(), "namespace is empty"); + } + if (cpu == null && memory == null && gpu == null){ + return new BizResourceQuota().error(K8sResponseEnum.BAD_REQUEST.getCode(), "cpu mem gpu is empty"); + } + PtResourceQuotaBO bo = new PtResourceQuotaBO(); + bo.setNamespace(namespace); + bo.setName(StringUtils.isEmpty(name)?namespace:namespace); + if (cpu != null && cpu > 0){ + bo.addCpuLimitsHard(String.valueOf(cpu), SymbolConstant.BLANK); + } + if (memory > 0){ + bo.addMemoryLimitsHard(String.valueOf(memory), K8sParamConstants.MEM_UNIT_GI); + } + if (gpu > 0){ + bo.addGpuLimitsHard(String.valueOf(gpu)); + } + return create(bo); + } catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "ResourceQuotaApiImpl.create error, param:{} error:{}", e); + return new BizResourceQuota().error(String.valueOf(e.getCode()),e.getMessage()); + } + } + + /** + * 根据命名空间查询ResourceQuota集合 + * + * @param namespace 命名空间 + * @return List ResourceQuota 业务类集合 + */ + @Override + public List list(String namespace) { + try { + LogUtil.info(LogEnum.BIZ_K8S,"Input namespace={}", namespace); + if (StringUtils.isEmpty(namespace)) { + ResourceQuotaList resourceQuotaList = client.resourceQuotas().inAnyNamespace().list(); + return resourceQuotaList.getItems().parallelStream().map(obj -> BizConvertUtils.toBizResourceQuota(obj)).collect(Collectors.toList()); + } else { + ResourceQuotaList resourceQuotaList = client.resourceQuotas().inNamespace(namespace).list(); + List bizResourceQuotaList = resourceQuotaList.getItems().parallelStream().map(obj -> BizConvertUtils.toBizResourceQuota(obj)).collect(Collectors.toList()); + LogUtil.info(LogEnum.BIZ_K8S,"Output {}", bizResourceQuotaList); + return bizResourceQuotaList; + } + }catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "ResourceQuotaApiImpl.list error, param:[namespace]={},error:{}", namespace,e); + return Collections.EMPTY_LIST; + } + } + + /** + * 删除ResourceQuota + * + * @param namespace 命名空间 + * @param name ResourceQuota 名称 + * @return PtBaseResult 基础结果类 + */ + @Override + public PtBaseResult delete(String namespace, String name) { + LogUtil.info(LogEnum.BIZ_K8S,"Input namespace={};name={}", namespace,name); + if (StringUtils.isEmpty(namespace) || StringUtils.isEmpty(name)) { + return new PtBaseResult().baseErrorBadRequest(); + } + try { + if (client.resourceQuotas().inNamespace(namespace).withName(name).delete()){ + return new PtBaseResult(); + }else { + return K8sResponseEnum.REPEAT.toPtBaseResult(); + } + } catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "ResourceQuotaApiImpl.delete error, param:[namespace]={}, [name]={}, error:{}",namespace, name, e); + return new PtBaseResult(String.valueOf(e.getCode()),e.getMessage()); + } + } + + /** + * 判断资源是否达到限制 + * + * @param cpuNum 单位为m 1核等于1000m + * @param memNum 单位为Mi 1Mi等于1024Ki + * @param gpuNum 单位为显卡,即"1"表示1张显卡 + * @return LimitsOfResourcesEnum 资源超限枚举类 + */ + @Override + public LimitsOfResourcesEnum reachLimitsOfResources(String namespace,Integer cpuNum, Integer memNum, Integer gpuNum) { + if (StringUtils.isEmpty(namespace)){ + return LimitsOfResourcesEnum.ADEQUATE; + } + List bizResourceQuotas = list(namespace); + if (CollectionUtils.isEmpty(bizResourceQuotas)){ + return LimitsOfResourcesEnum.ADEQUATE; + } + for (BizResourceQuota bizResourceQuota : bizResourceQuotas){ + if (!CollectionUtils.isEmpty(bizResourceQuota.getMatchExpressions())){ + continue; + } + Map remainder = bizResourceQuota.getRemainder(); + BizQuantity cpuRemainder = remainder.get(K8sParamConstants.RESOURCE_QUOTA_CPU_LIMITS_KEY); + if (cpuRemainder != null && cpuNum != null){ + if (UnitConvertUtils.cpuFormatToN(cpuRemainder.getAmount(),cpuRemainder.getFormat()) < cpuNum * MagicNumConstant.MILLION_LONG){ + return LimitsOfResourcesEnum.LIMITS_OF_CPU; + } + } + + BizQuantity memRemainder = remainder.get(K8sParamConstants.RESOURCE_QUOTA_MEMORY_LIMITS_KEY); + if (memRemainder != null && memRemainder != null){ + if (UnitConvertUtils.memFormatToMi(memRemainder.getAmount(),memRemainder.getFormat()) < memNum){ + return LimitsOfResourcesEnum.LIMITS_OF_MEM; + } + } + + BizQuantity gpuRemainder = remainder.get(K8sParamConstants.RESOURCE_QUOTA_GPU_LIMITS_KEY); + if (gpuRemainder != null && gpuNum != null){ + if (Integer.valueOf(gpuRemainder.getAmount()) < gpuNum){ + return LimitsOfResourcesEnum.LIMITS_OF_GPU; + } + } + } + + return LimitsOfResourcesEnum.ADEQUATE; + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/impl/TrainJobApiImpl.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/impl/TrainJobApiImpl.java new file mode 100644 index 0000000..009f5cd --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/impl/TrainJobApiImpl.java @@ -0,0 +1,485 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.api.impl; + +import cn.hutool.core.collection.CollectionUtil; +import cn.hutool.core.util.RandomUtil; +import cn.hutool.core.util.StrUtil; +import com.alibaba.fastjson.JSON; +import com.google.common.collect.Maps; +import io.fabric8.kubernetes.api.model.Container; +import io.fabric8.kubernetes.api.model.EnvVar; +import io.fabric8.kubernetes.api.model.EnvVarBuilder; +import io.fabric8.kubernetes.api.model.Quantity; +import io.fabric8.kubernetes.api.model.ResourceRequirementsBuilder; +import io.fabric8.kubernetes.api.model.Volume; +import io.fabric8.kubernetes.api.model.VolumeBuilder; +import io.fabric8.kubernetes.api.model.VolumeMount; +import io.fabric8.kubernetes.api.model.VolumeMountBuilder; +import io.fabric8.kubernetes.api.model.batch.Job; +import io.fabric8.kubernetes.api.model.batch.JobBuilder; +import io.fabric8.kubernetes.api.model.batch.JobList; +import io.fabric8.kubernetes.client.KubernetesClient; +import io.fabric8.kubernetes.client.KubernetesClientException; +import org.dubhe.biz.base.constant.MagicNumConstant; +import org.dubhe.biz.base.constant.SymbolConstant; +import org.dubhe.biz.base.utils.StringUtils; +import org.dubhe.biz.file.api.FileStoreApi; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.dubhe.k8s.api.LogMonitoringApi; +import org.dubhe.k8s.api.NodeApi; +import org.dubhe.k8s.api.PersistentVolumeClaimApi; +import org.dubhe.k8s.api.PodApi; +import org.dubhe.k8s.api.ResourceIisolationApi; +import org.dubhe.k8s.api.ResourceQuotaApi; +import org.dubhe.k8s.api.TrainJobApi; +import org.dubhe.k8s.cache.ResourceCache; +import org.dubhe.k8s.constant.K8sLabelConstants; +import org.dubhe.k8s.constant.K8sParamConstants; +import org.dubhe.k8s.domain.bo.PtJupyterJobBO; +import org.dubhe.k8s.domain.bo.PtMountDirBO; +import org.dubhe.k8s.domain.bo.PtPersistentVolumeClaimBO; +import org.dubhe.k8s.domain.bo.TaskYamlBO; +import org.dubhe.k8s.domain.entity.K8sTask; +import org.dubhe.k8s.domain.resource.BizJob; +import org.dubhe.k8s.domain.resource.BizPersistentVolumeClaim; +import org.dubhe.k8s.domain.vo.PtJupyterJobVO; +import org.dubhe.k8s.enums.ImagePullPolicyEnum; +import org.dubhe.k8s.enums.K8sKindEnum; +import org.dubhe.k8s.enums.K8sResponseEnum; +import org.dubhe.k8s.enums.LackOfResourcesEnum; +import org.dubhe.k8s.enums.LimitsOfResourcesEnum; +import org.dubhe.k8s.enums.RestartPolicyEnum; +import org.dubhe.k8s.enums.ShellCommandEnum; +import org.dubhe.k8s.service.K8sTaskService; +import org.dubhe.k8s.utils.BizConvertUtils; +import org.dubhe.k8s.utils.K8sUtils; +import org.dubhe.k8s.utils.LabelUtils; +import org.springframework.beans.factory.annotation.Autowired; + +import javax.annotation.Resource; +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; + +/** + * @description TrainJobApi实现类 + * @date 2020-04-22 + */ +public class TrainJobApiImpl implements TrainJobApi { + + private K8sUtils k8sUtils; + private KubernetesClient client; + + @Resource(name = "hostFileStoreApiImpl") + private FileStoreApi fileStoreApi; + + @Autowired + private PersistentVolumeClaimApi persistentVolumeClaimApi; + @Autowired + private NodeApi nodeApi; + @Autowired + private PodApi podApi; + @Autowired + private LogMonitoringApi logMonitoringApi; + @Autowired + private K8sTaskService k8sTaskService; + @Autowired + private ResourceCache resourceCache; + @Autowired + private ResourceQuotaApi resourceQuotaApi; + @Autowired + private ResourceIisolationApi resourceIisolationApi; + + public TrainJobApiImpl(K8sUtils k8sUtils) { + this.k8sUtils = k8sUtils; + this.client = k8sUtils.getClient(); + } + + /** + * 创建训练任务 Job + * + * @param bo 训练任务 Job BO + * @return PtJupyterJobVO 训练任务 Job 结果类 + */ + @Override + public PtJupyterJobVO create(PtJupyterJobBO bo) { + try{ + LimitsOfResourcesEnum limitsOfResources = resourceQuotaApi.reachLimitsOfResources(bo.getNamespace(),bo.getCpuNum(), bo.getMemNum(), bo.getGpuNum()); + if (!LimitsOfResourcesEnum.ADEQUATE.equals(limitsOfResources)){ + return new PtJupyterJobVO().error(K8sResponseEnum.LACK_OF_RESOURCES.getCode(), limitsOfResources.getMessage()); + } + LackOfResourcesEnum lack = nodeApi.isAllocatable(bo.getCpuNum(),bo.getMemNum(),bo.getGpuNum()); + if (!LackOfResourcesEnum.ADEQUATE.equals(lack)){ + return new PtJupyterJobVO().error(K8sResponseEnum.LACK_OF_RESOURCES.getCode(),lack.getMessage()); + } + LogUtil.info(LogEnum.BIZ_K8S, "Params of creating Job--create:{}", bo); + if (!fileStoreApi.createDirs(bo.getDirList().toArray(new String[MagicNumConstant.ZERO]))) { + return new PtJupyterJobVO().error(K8sResponseEnum.INTERNAL_SERVER_ERROR.getCode(), K8sResponseEnum.INTERNAL_SERVER_ERROR.getMessage()); + } + resourceCache.deletePodCacheByResourceName(bo.getNamespace(),bo.getName()); + PtJupyterJobVO result = new JupyterDeployer(bo).buildVolumes().deploy(); + LogUtil.info(LogEnum.BIZ_K8S,"Return value of creating Job--create:{}", result); + return result; + }catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S,"TrainJobApiImpl.create error, param:{} error:{}", bo, e); + return new PtJupyterJobVO().error(String.valueOf(e.getCode()),e.getMessage()); + } + } + + /** + * 根据命名空间和资源名删除Job + * + * @param namespace 命名空间 + * @param resourceName 资源名称 + * @return Boolean true成功 false失败 + */ + @Override + public Boolean delete(String namespace, String resourceName){ + try { + LogUtil.info(LogEnum.BIZ_K8S,"Params of delete Job--namespace:{}, resourceName:{}",namespace, resourceName); + k8sTaskService.deleteByNamespaceAndResourceName(namespace,resourceName); + JobList jobList = client.batch().jobs().inNamespace(namespace).withLabels(LabelUtils.withEnvResourceName(resourceName)).list(); + if (jobList == null || jobList.getItems().size() == 0){ + return true; + } + return client.batch().jobs().inNamespace(namespace).withLabels(LabelUtils.withEnvResourceName(resourceName)).delete(); + }catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "TrainJobApiImpl.delete error, param:[namespace]={}, [resourceName]={}, error:{}",namespace, resourceName,e); + return false; + } + } + + /** + * 根据命名空间查询Job + * + * @param namespace 命名空间 + * @return List Job业务类集合 + */ + @Override + public List list(String namespace){ + JobList list = client.batch().jobs().inNamespace(namespace).withLabels(LabelUtils.withEnvResourceName()).list(); + if(CollectionUtil.isEmpty(list.getItems())){ + return null; + } + return list.getItems().stream().map(item -> BizConvertUtils.toBizJob(item)).collect(Collectors.toList()); + } + + /** + * 根据命名空间和资源名查询Job + * + * @param namespace 命名空间 + * @param resourceName 资源名称 + * @return BizJob Job业务类 + */ + @Override + public BizJob get(String namespace, String resourceName){ + try { + JobList list = client.batch().jobs().inNamespace(namespace).withLabels(LabelUtils.withEnvResourceName(resourceName)).list(); + if(CollectionUtil.isEmpty(list.getItems())){ + return null; + } + Job job = list.getItems().get(0); + return BizConvertUtils.toBizJob(job); + }catch (KubernetesClientException e) { + LogUtil.error(LogEnum.BIZ_K8S, "TrainJobApiImpl.get error, param:[namespace]={}, [resourceName]={}, error:{}",namespace, resourceName,e); + return new BizJob().error(String.valueOf(e.getCode()),e.getMessage()); + } + } + + private class JupyterDeployer{ + private String baseName; + private String jobName; + + private String namespace; + private String image; + private Boolean useGpu; + private List cmdLines; + private Map fsMounts; + + private Map resourcesLimitsMap; + private Map baseLabels; + + private List volumeMounts; + private List volumes; + private String businessLabel; + private Integer delayCreate; + private Integer delayDelete; + private TaskYamlBO taskYamlBO; + private String errCode; + private String errMessage; + + private JupyterDeployer(PtJupyterJobBO bo){ + this.baseName = bo.getName(); + this.jobName = StrUtil.format(K8sParamConstants.RESOURCE_NAME_TEMPLATE, baseName, RandomUtil.randomString(K8sParamConstants.RESOURCE_NAME_SUFFIX_LENGTH)); + this.namespace = bo.getNamespace(); + this.image = bo.getImage(); + this.cmdLines = new ArrayList(); + Optional.ofNullable(bo.getCmdLines()).ifPresent(v -> cmdLines = v); + this.useGpu = bo.getUseGpu()==null?false:bo.getUseGpu(); + if (bo.getUseGpu() != null && bo.getUseGpu() && null == bo.getGpuNum()){ + bo.setGpuNum(MagicNumConstant.ZERO); + } + + this.resourcesLimitsMap = Maps.newHashMap(); + Optional.ofNullable(bo.getCpuNum()).ifPresent(v -> resourcesLimitsMap.put(K8sParamConstants.QUANTITY_CPU_KEY, new Quantity(v.toString(), K8sParamConstants.CPU_UNIT))); + Optional.ofNullable(bo.getGpuNum()).ifPresent(v -> resourcesLimitsMap.put(K8sParamConstants.GPU_RESOURCE_KEY, new Quantity(v.toString()))); + Optional.ofNullable(bo.getMemNum()).ifPresent(v -> resourcesLimitsMap.put(K8sParamConstants.QUANTITY_MEMORY_KEY, new Quantity(v.toString(), K8sParamConstants.MEM_UNIT))); + + this.fsMounts = bo.getFsMounts(); + businessLabel = bo.getBusinessLabel(); + this.baseLabels = LabelUtils.getBaseLabels(baseName,bo.getBusinessLabel()); + + this.volumeMounts = new ArrayList<>(); + this.volumes = new ArrayList<>(); + this.delayCreate = bo.getDelayCreateTime(); + this.delayDelete = bo.getDelayDeleteTime(); + this.taskYamlBO = new TaskYamlBO(); + this.errCode = K8sResponseEnum.SUCCESS.getCode(); + this.errMessage = SymbolConstant.BLANK; + } + + /** + * 部署Job + * + * @return PtJupyterJobVO 训练任务 Job 结果类 + */ + public PtJupyterJobVO deploy() { + delayCreate = delayCreate == null || delayCreate <= 0 ? MagicNumConstant.ZERO : delayCreate; + delayDelete = delayDelete == null || delayDelete <= 0 ? MagicNumConstant.ZERO : delayDelete; + if (!K8sResponseEnum.SUCCESS.getCode().equals(errCode)){ + return new PtJupyterJobVO().error(errCode,errMessage); + } + //部署job + Job job = deployJob(delayCreate, delayDelete); + if (CollectionUtil.isNotEmpty(taskYamlBO.getYamlList()) && (delayCreate > MagicNumConstant.ZERO || delayDelete > MagicNumConstant.ZERO)){ + long applyUnixTime = System.currentTimeMillis()/MagicNumConstant.THOUSAND_LONG + delayCreate*MagicNumConstant.SIXTY_LONG; + Timestamp applyDisplayTime = new Timestamp(applyUnixTime * MagicNumConstant.THOUSAND_LONG); + long stopUnixTime = applyUnixTime + delayDelete* MagicNumConstant.SIXTY_LONG; + Timestamp stopDisplayTime = new Timestamp(stopUnixTime * MagicNumConstant.THOUSAND_LONG); + K8sTask k8sTask = new K8sTask(){{ + setNamespace(namespace); + setResourceName(baseName); + setTaskYaml(JSON.toJSONString(taskYamlBO)); + setBusiness(businessLabel); + setApplyUnixTime(applyUnixTime); + setApplyDisplayTime(applyDisplayTime); + setApplyStatus(delayCreate == MagicNumConstant.ZERO ? MagicNumConstant.ZERO : MagicNumConstant.ONE); + }}; + if (delayDelete > MagicNumConstant.ZERO){ + k8sTask.setStopUnixTime(stopUnixTime); + k8sTask.setStopDisplayTime(stopDisplayTime); + k8sTask.setStopStatus(MagicNumConstant.ONE); + } + k8sTaskService.createOrUpdateTask(k8sTask); + } + + return PtJupyterJobVO.getInstance(job); + } + + /** + * 挂载存储 + * + * @return JupyterDeployer Jupyter Job 部署类 + */ + private JupyterDeployer buildVolumes(){ + + // 针对于共享内存挂载存储 + buildSharedMemoryVolume(); + + if (CollectionUtil.isNotEmpty(fsMounts)){ + int i = MagicNumConstant.ZERO; + for (Map.Entry mount : fsMounts.entrySet()) { + boolean availableMount = (mount != null && StringUtils.isNotEmpty(mount.getKey()) && mount.getValue() != null && StringUtils.isNotEmpty(mount.getValue().getDir())); + if (availableMount){ + boolean success = mount.getValue().isRecycle()?buildFsPvcVolumes(mount.getKey(),mount.getValue(),i):buildFsVolumes(mount.getKey(),mount.getValue(),i); + if (!success){ + break; + } + i++; + } + } + } + return this; + } + + /** + * 针对于共享内存挂载存储 + * + */ + private void buildSharedMemoryVolume(){ + volumeMounts.add(new VolumeMountBuilder() + .withName(K8sParamConstants.SHM_NAME) + .withMountPath(K8sParamConstants.SHM_MOUNTPATH) + .build()); + volumes.add(new VolumeBuilder() + .withName(K8sParamConstants.SHM_NAME) + .withNewEmptyDir() + .withMedium(K8sParamConstants.SHM_MEDIUM) + .endEmptyDir() + .build()); + } + + /** + * 挂载存储 + * + * @param mountPath 挂载路径 + * @param dirBO 挂载路径参数 + * @param num 名称序号 + * @return boolean true成功 false失败 + */ + private boolean buildFsVolumes(String mountPath,PtMountDirBO dirBO,int num){ + volumeMounts.add(new VolumeMountBuilder() + .withName(K8sParamConstants.VOLUME_PREFIX+num) + .withMountPath(mountPath) + .withReadOnly(dirBO.isReadOnly()) + .build()); + volumes.add(new VolumeBuilder() + .withName(K8sParamConstants.VOLUME_PREFIX+num) + .withNewHostPath() + .withPath(dirBO.getDir()) + .withType(K8sParamConstants.HOST_PATH_TYPE) + .endHostPath() + .build()); + return true; + } + + /** + * 按照存储资源声明挂载存储 + * + * @param mountPath 挂载路径 + * @param dirBO 挂载路径参数 + * @param i 名称序号 + * @return boolean true成功 false失败 + */ + private boolean buildFsPvcVolumes(String mountPath,PtMountDirBO dirBO,int i){ + BizPersistentVolumeClaim bizPersistentVolumeClaim = persistentVolumeClaimApi.createWithFsPv(new PtPersistentVolumeClaimBO(namespace,baseName,dirBO)); + if (bizPersistentVolumeClaim.isSuccess()){ + volumeMounts.add(new VolumeMountBuilder() + .withName(K8sParamConstants.VOLUME_PREFIX+i) + .withMountPath(mountPath) + .withReadOnly(dirBO.isReadOnly()) + .build()); + volumes.add(new VolumeBuilder() + .withName(K8sParamConstants.VOLUME_PREFIX+i) + .withNewPersistentVolumeClaim(bizPersistentVolumeClaim.getName(), dirBO.isReadOnly()) + .build()); + return true; + }else { + this.errCode = bizPersistentVolumeClaim.getCode(); + this.errMessage = bizPersistentVolumeClaim.getMessage(); + } + return false; + } + + /** + * 部署Job + * + * @param delayCreate 创建 + * @param delayDelete 删除 + * @return Job job类 + */ + private Job deployJob(Integer delayCreate, Integer delayDelete) { + + Job job = null; + JobList list = client.batch().jobs().inNamespace(namespace).withLabels(LabelUtils.withEnvResourceName(baseName)).list(); + if(CollectionUtil.isNotEmpty(list.getItems())){ + job = list.getItems().get(0); + jobName = job.getMetadata().getName(); + boolean succeedOrFailed = (job.getStatus().getSucceeded() != null && job.getStatus().getSucceeded() > 0) || (job.getStatus().getFailed() != null && job.getStatus().getFailed() > 0); + if(succeedOrFailed){ + LogUtil.info(LogEnum.BIZ_K8S, "Delete existing job {}", jobName); + client.resource(job).delete(); + }else{ + LogUtil.info(LogEnum.BIZ_K8S, "Skip creating job, {} already exists", jobName); + return job; + } + } + //容器 + Container container = new Container(); + + //环境变量 + List env = new ArrayList(); + env.add(new EnvVarBuilder().withName(K8sParamConstants.PYTHONUNBUFFERED).withValue(SymbolConstant.ZERO).build()); + container.setEnv(env); + + //镜像 + container.setName(jobName); + container.setImage(image); + container.setImagePullPolicy(ImagePullPolicyEnum.IFNOTPRESENT.getPolicy()); + container.setVolumeMounts(volumeMounts); + //启动命令 + container.setCommand(Collections.singletonList(ShellCommandEnum.BIN_BANSH.getShell())); + container.setArgs(cmdLines); + + //资源限制 + container.setResources(new ResourceRequirementsBuilder() + .addToLimits(resourcesLimitsMap) + .build()); + + Map gpuLabel = new HashMap(1); + if (useGpu){ + gpuLabel.put(K8sLabelConstants.NODE_GPU_LABEL_KEY,K8sLabelConstants.NODE_GPU_LABEL_VALUE); + } + + job = new JobBuilder() + .withNewMetadata() + .withName(jobName) + .addToLabels(baseLabels) + .withNamespace(namespace) + .endMetadata() + .withNewSpec() + .withParallelism(1) + .withCompletions(1) + .withBackoffLimit(0) + .withNewTemplate() + .withNewMetadata() + .withName(jobName) + .addToLabels(LabelUtils.getChildLabels(baseName, jobName, K8sKindEnum.JOB.getKind(),businessLabel)) + .withNamespace(namespace) + .endMetadata() + .withNewSpec() + .withTerminationGracePeriodSeconds(MagicNumConstant.ZERO_LONG) + .addToNodeSelector(gpuLabel) + .addToContainers(container) + .addToVolumes(volumes.toArray(new Volume[0])) + .withRestartPolicy(RestartPolicyEnum.NEVER.getRestartPolicy()) + .endSpec() + .endTemplate() + .endSpec() + .build(); + if (delayCreate == null || delayCreate == MagicNumConstant.ZERO){ + resourceIisolationApi.addIisolationInfo(job); + LogUtil.info(LogEnum.BIZ_K8S, "Ready to deploy {}", jobName); + job = client.batch().jobs().create(job); + LogUtil.info(LogEnum.BIZ_K8S, "{} deployed successfully", jobName); + } + if (delayCreate > MagicNumConstant.ZERO || delayDelete > MagicNumConstant.ZERO){ + taskYamlBO.append(job); + } + + return job; + } + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/impl/VolumeApiImpl.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/impl/VolumeApiImpl.java new file mode 100644 index 0000000..003bbbb --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/api/impl/VolumeApiImpl.java @@ -0,0 +1,128 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.api.impl; + +import cn.hutool.core.collection.CollectionUtil; +import io.fabric8.kubernetes.api.model.VolumeBuilder; +import io.fabric8.kubernetes.api.model.VolumeMountBuilder; +import org.dubhe.biz.base.constant.MagicNumConstant; +import org.dubhe.k8s.api.PersistentVolumeClaimApi; +import org.dubhe.k8s.api.VolumeApi; +import org.dubhe.k8s.constant.K8sParamConstants; +import org.dubhe.k8s.domain.bo.BuildFsVolumeBO; +import org.dubhe.k8s.domain.bo.PtMountDirBO; +import org.dubhe.k8s.domain.bo.PtPersistentVolumeClaimBO; +import org.dubhe.k8s.domain.resource.BizPersistentVolumeClaim; +import org.dubhe.k8s.domain.vo.VolumeVO; +import org.dubhe.biz.base.utils.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.Map; + +/** + * @description Kubernetes Volume api implements + * @date 2020-09-10 + */ +@Service +public class VolumeApiImpl implements VolumeApi { + @Autowired + private PersistentVolumeClaimApi persistentVolumeClaimApi; + + /** + * 构建文件存储服务存储卷 + * + * @param bo 文件存储服务存储卷参数 + * @return + */ + @Override + public VolumeVO buildFsVolumes(BuildFsVolumeBO bo) { + if (bo == null){ + return new VolumeVO().errorBadRequest(); + } + VolumeVO volumeVO = new VolumeVO(); + if (CollectionUtil.isNotEmpty(bo.getFsMounts())){ + int i = MagicNumConstant.ZERO; + for (Map.Entry mount : bo.getFsMounts().entrySet()) { + boolean availableMount = (mount != null && StringUtils.isNotEmpty(mount.getKey()) && mount.getValue() != null && StringUtils.isNotEmpty(mount.getValue().getDir())); + if (availableMount){ + boolean success = mount.getValue().isRecycle()?buildFsPvcVolumes(bo,volumeVO,mount.getKey(),mount.getValue(),i):buildFsVolumes(volumeVO,mount.getKey(),mount.getValue(),i); + if (!success){ + break; + } + i++; + } + } + } + return volumeVO; + } + + /** + * 构建存储卷 + * + * @param mountPath 挂载路径 + * @param dirBO 挂载路径参数 + * @param num 名称序号 + * @return boolean + */ + private boolean buildFsVolumes(VolumeVO volumeVO, String mountPath, PtMountDirBO dirBO, int num){ + if (volumeVO == null || StringUtils.isEmpty(mountPath) || dirBO == null){ + return false; + } + volumeVO.addVolumeMount(new VolumeMountBuilder() + .withName(K8sParamConstants.VOLUME_PREFIX+num) + .withMountPath(mountPath) + .withReadOnly(dirBO.isReadOnly()) + .build()); + volumeVO.addVolume(new VolumeBuilder() + .withName(K8sParamConstants.VOLUME_PREFIX+num) + .withNewHostPath() + .withPath(dirBO.getDir()) + .withType(K8sParamConstants.HOST_PATH_TYPE) + .endHostPath() + .build()); + return true; + } + + /** + * 按照存储资源声明挂载存储 + * + * @param mountPath 挂载路径 + * @param dirBO 挂载路径参数 + * @param i 名称序号 + * @return boolean + */ + private boolean buildFsPvcVolumes(BuildFsVolumeBO bo, VolumeVO volumeVO, String mountPath, PtMountDirBO dirBO, int i){ + BizPersistentVolumeClaim bizPersistentVolumeClaim = persistentVolumeClaimApi.createWithFsPv(new PtPersistentVolumeClaimBO(bo.getNamespace(),bo.getResourceName(),dirBO)); + if (bizPersistentVolumeClaim.isSuccess()){ + volumeVO.addVolumeMount(new VolumeMountBuilder() + .withName(K8sParamConstants.VOLUME_PREFIX+i) + .withMountPath(mountPath) + .withReadOnly(dirBO.isReadOnly()) + .build()); + volumeVO.addVolume(new VolumeBuilder() + .withName(K8sParamConstants.VOLUME_PREFIX+i) + .withNewPersistentVolumeClaim(bizPersistentVolumeClaim.getName(), dirBO.isReadOnly()) + .build()); + return true; + }else { + volumeVO.error(bizPersistentVolumeClaim.getCode(),bizPersistentVolumeClaim.getMessage()); + } + return false; + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/aspect/ValidationAspect.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/aspect/ValidationAspect.java new file mode 100644 index 0000000..f296eea --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/aspect/ValidationAspect.java @@ -0,0 +1,166 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.aspect; + +import cn.hutool.core.util.ArrayUtil; +import com.alibaba.fastjson.JSON; +import lombok.Data; +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.annotation.Around; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.reflect.MethodSignature; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.k8s.annotation.K8sValidation; +import org.dubhe.k8s.domain.PtBaseResult; +import org.dubhe.k8s.enums.ValidationTypeEnum; +import org.dubhe.k8s.utils.ValidationUtils; +import org.dubhe.biz.log.utils.LogUtil; +import org.springframework.core.annotation.Order; +import org.springframework.stereotype.Component; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Field; + +/** + * @description 参数校验 + * AOP org.dubhe.k8s.api.impl下的所有方法加了@K8sValidation(ValidationTypeEnum.K8S_RESOURCE_NAME) 的参数和参数内的一级字段会被校验 + * @date 2020-06-04 + */ +@Component +@Aspect +public class ValidationAspect { + @Order(1) + @Around("execution(* org.dubhe.k8s.api.impl.*.*(..)))") + public Object k8sResourceNameValidation(JoinPoint point) throws Throwable { + /**获取参数注解**/ + MethodSignature methodSignature = (MethodSignature) point.getSignature(); + Annotation[][] parameterAnnotations = methodSignature.getMethod().getParameterAnnotations(); + /**参数**/ + Object[] args = point.getArgs(); + if (ArrayUtil.isNotEmpty(args)) { + for (int i = 0; i < parameterAnnotations.length; i++) { + if (null == args[i]) { + continue; + } + /**基本类型不做校验**/ + if (args[i].getClass().isPrimitive()) { + continue; + } + if (args[i] instanceof String) { + /**对String类型做校验**/ + for (Annotation annotation : parameterAnnotations[i]) { + if (annotation instanceof K8sValidation && ValidationTypeEnum.K8S_RESOURCE_NAME.equals(((K8sValidation) annotation).value())) { + ValidateResourceNameResult validateResult = validateResourceName((String) args[i]); + if (!validateResult.isSuccess()) { + return getValidationResourceNameErrorReturn(methodSignature.getReturnType(), validateResult.getField()); + } + } + } + } else { + /**对非String类型做其字段校验**/ + ValidateResourceNameResult validateResult = validateArgResourceName(args[i], args[i].getClass()); + if (!validateResult.isSuccess()) { + return getValidationResourceNameErrorReturn(methodSignature.getReturnType(), validateResult.getField()); + } + } + } + } + return ((ProceedingJoinPoint) point).proceed(); + } + + /** + * 校验k8s资源对象名称是否合法 + * + * @param resourceName 资源名称 + * @return ValidateResourceNameResult 校验资源名称结果类 + */ + private ValidateResourceNameResult validateResourceName(String resourceName) { + return new ValidateResourceNameResult(ValidationUtils.validateResourceName(resourceName), resourceName); + } + + /** + * 对参数内部字段做k8s资源对象名称是否合法校验 + * + * @param arg 任意对象 + * @param argClass Class类对象 + * @return ValidateResourceNameResult 校验资源名称结果类 + */ + private ValidateResourceNameResult validateArgResourceName(Object arg, Class argClass) { + Field[] fields = argClass.getDeclaredFields(); + for (int i = 0; i < fields.length; i++) { + Field field = fields[i]; + K8sValidation k8sValidation = field.getDeclaredAnnotation(K8sValidation.class); + if (k8sValidation == null) { + continue; + } + if (ValidationTypeEnum.K8S_RESOURCE_NAME.equals(k8sValidation.value()) && field.getType().equals(String.class)) { + field.setAccessible(true); + try { + String resourceName = (String) field.get(arg); + if (!validateResourceName(resourceName).isSuccess()) { + return new ValidateResourceNameResult(false, resourceName); + } + } catch (IllegalAccessException e) { + LogUtil.error(LogEnum.BIZ_K8S, "ValidationAspect.validateArgResourceName exception, param:[arg]={}, [argClass]={}, exception:{}", JSON.toJSONString(arg), JSON.toJSONString(argClass), e); + } + } + } + /**递归校验父类属性**/ + if (argClass.getSuperclass() != Object.class) { + return validateArgResourceName(arg, argClass.getSuperclass()); + } + return new ValidateResourceNameResult(true, null); + } + + /** + * 校验不通过获取返回值 + * + * @param returnType Class类对象 + * @param fieldName 字段名称 + * @return Object 任意对象 + */ + private Object getValidationResourceNameErrorReturn(Class returnType, String fieldName) { + /**获取返回值类型**/ + try { + if (PtBaseResult.class.isAssignableFrom(returnType)) { + PtBaseResult validationReturn = (PtBaseResult) returnType.newInstance(); + return validationReturn.validationErrorRequest(fieldName); + } + } catch (InstantiationException e) { + LogUtil.error(LogEnum.BIZ_K8S, "ValidationAspect.getValidationResourceNameErrorReturn exception, param:[returnType]={}, [fieldName]={}", JSON.toJSONString(returnType), fieldName, e); + } catch (IllegalAccessException e) { + LogUtil.error(LogEnum.BIZ_K8S, "ValidationAspect.getValidationResourceNameErrorReturn exception, param:[returnType]={}, [fieldName]={}", JSON.toJSONString(returnType), fieldName, e); + } + return null; + } + + /** + * 校验结果 + */ + @Data + private class ValidateResourceNameResult { + private boolean success; + private String field; + + public ValidateResourceNameResult(boolean success, String field) { + this.success = success; + this.field = field; + } + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/cache/ResourceCache.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/cache/ResourceCache.java new file mode 100644 index 0000000..577b59a --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/cache/ResourceCache.java @@ -0,0 +1,238 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.cache; + +import cn.hutool.core.collection.CollectionUtil; +import org.dubhe.biz.base.constant.MagicNumConstant; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.redis.utils.RedisUtils; +import org.dubhe.k8s.api.PodApi; +import org.dubhe.k8s.constant.K8sLabelConstants; +import org.dubhe.k8s.domain.entity.K8sResource; +import org.dubhe.k8s.domain.resource.BizPod; +import org.dubhe.k8s.enums.K8sKindEnum; +import org.dubhe.k8s.service.K8sResourceService; +import org.dubhe.biz.log.utils.LogUtil; +import org.dubhe.biz.base.utils.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.util.CollectionUtils; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.ThreadLocalRandom; + +/** + * @description k8s资源缓存 + * @date 2020-05-20 + */ +public class ResourceCache { + @Autowired + private RedisUtils redisUtils; + @Autowired + private PodApi podApi; + @Autowired + private K8sResourceService k8sResourceService; + + /**podNmae/resourceName缓存失效时间 单位秒**/ + private static final Long TIME_OUT = 7*24*3600L; + /**缓存击穿前缀**/ + @Value("K8sClient:Pod:"+"${spring.profiles.active}_cache_breakdown_") + private String cacheBreakdownPrefix; + /**缓存穿透标记过期时间**/ + private static final Integer CACHE_BREAKDOWN = 30; + + @Value("K8sClient:Pod:"+"${spring.profiles.active}_k8s_pod_resourcename_") + private String resourceNamePrefix; + + @Value("K8sClient:Pod:"+"${spring.profiles.active}_k8s_pod_name_") + private String podNamePrefix; + + /** + * 设置资源名称到 pod名称的缓存 + * + * @param resourceName 资源名称 + * @param podName Pod名称 + * @return boolean true 缓存 false 不缓存 + */ + public boolean cachePod(String resourceName,String podName){ + try{ + Boolean success = redisUtils.zSet(resourceNamePrefix +resourceName,TIME_OUT+ThreadLocalRandom.current().nextLong(MagicNumConstant.ZERO,MagicNumConstant.ONE_HUNDRED),podName); + if (success){ + return redisUtils.set(podNamePrefix +podName,resourceName,TIME_OUT+ThreadLocalRandom.current().nextLong(MagicNumConstant.ZERO,MagicNumConstant.ONE_HUNDRED)); + } + return false; + }catch (Exception e){ + LogUtil.error(LogEnum.BIZ_K8S,"Cache exception, resourceName: {}, podName: {}, exception information: {}",resourceName,podName,e); + return false; + } + } + + /** + * 设置资源名称到 pod名称的缓存 + * + * @param namespace 命名空间 + * @param resourceName 资源名称 + * @return boolean true 缓存 false 不缓存 + */ + public boolean cachePods(String namespace,String resourceName){ + try{ + List podList = podApi.getListByResourceName(namespace,resourceName); + if (CollectionUtil.isNotEmpty(podList)){ + podList.forEach(pod->{ + cachePod(resourceName,pod.getName()); + k8sResourceService.create(pod); + }); + } + return true; + }catch (Exception e){ + LogUtil.error(LogEnum.BIZ_K8S,"Cache exception, namespace: {}, resourceName: {}, exception information: {}",namespace,resourceName,e); + return false; + } + } + + /** + * 从缓存中取 resourceName对应的podName + * + * @param namespace 命名空间 + * @param resourceName 资源名称 + * @return Set podName的集合 + */ + public Set getPodNameByResourceName(String namespace,String resourceName){ + try{ + /**缓存穿透**/ + if (redisUtils.get(cacheBreakdownPrefix +resourceName) != null){ + return null; + } + Set set = (Set) redisUtils.zGet(resourceNamePrefix +resourceName); + if (CollectionUtil.isEmpty(set) && StringUtils.isNotEmpty(namespace)){ + List bizPods = podApi.getListByResourceName(namespace,resourceName); + Set finalSet = new HashSet<>(MagicNumConstant.ONE); + if(CollectionUtil.isNotEmpty(bizPods)){ + bizPods.forEach(obj-> { + finalSet.add(obj.getName()); + cachePod(resourceName,obj.getName()); + }); + }else { + List k8sResourceList = k8sResourceService.selectByResourceName(K8sKindEnum.POD.getKind(),namespace,resourceName); + if (CollectionUtil.isNotEmpty(k8sResourceList)){ + k8sResourceList.forEach(obj->{ + finalSet.add(obj.getName()); + cachePod(resourceName,obj.getName()); + }); + }else { + /**设置缓存穿透标记**/ + redisUtils.set(cacheBreakdownPrefix +resourceName, cacheBreakdownPrefix +resourceName,CACHE_BREAKDOWN); + } + } + return finalSet; + } + return set; + }catch (Exception e){ + LogUtil.error(LogEnum.BIZ_K8S,"Query cache exception, namespace: {}, resourceName: {}, exception information: {}",namespace,resourceName,e); + return new HashSet<>(); + } + } + + /** + * 从缓存中取 podName对应的resourceName + * + * @param namespace 命名空间 + * @param podName Pod的名称 + * @return String resourceName的名称 + */ + public String getResourceNameByPodName(String namespace,String podName){ + try{ + /**缓存穿透**/ + if (redisUtils.get(cacheBreakdownPrefix +podName) != null){ + return null; + } + String resourceName = (String) redisUtils.get(podNamePrefix +podName); + if (StringUtils.isEmpty(resourceName) && StringUtils.isNotEmpty(namespace)){ + BizPod pod = podApi.get(namespace,podName); + if (pod != null){ + resourceName = pod.getLabels().get(K8sLabelConstants.BASE_TAG_SOURCE); + cachePod(resourceName,podName); + return resourceName; + }else { + List k8sResourceList = k8sResourceService.selectByName(K8sKindEnum.POD.getKind(),namespace,podName); + if (CollectionUtil.isNotEmpty(k8sResourceList)){ + resourceName = k8sResourceList.get(0).getResourceName(); + cachePod(resourceName,podName); + }else { + redisUtils.set(cacheBreakdownPrefix +podName, cacheBreakdownPrefix +podName,CACHE_BREAKDOWN); + } + return resourceName; + } + } + return resourceName; + }catch (Exception e){ + LogUtil.error(LogEnum.BIZ_K8S,"Query cache exception, namespace: {}, podName: {}, exception information: {}",namespace,podName,e); + return null; + } + } + + /** + * 删除pod名称缓存 + * + * @param namespace 命名空间 + * @param resourceName 资源名称 + * @return boolean true 删除成功 false 删除失败 + */ + public boolean deletePodCacheByResourceName(String namespace, String resourceName){ + try{ + if (StringUtils.isNotEmpty(namespace) && StringUtils.isNotEmpty(resourceName)){ + Set podNameSet = (Set) redisUtils.zGet(resourceNamePrefix +resourceName); + redisUtils.del(resourceNamePrefix +resourceName); + if (!CollectionUtils.isEmpty(podNameSet)){ + podNameSet.forEach(podName-> redisUtils.del(podNamePrefix +podName)); + } + k8sResourceService.deleteByResourceName(K8sKindEnum.POD.getKind(),namespace,resourceName); + } + return true; + }catch (Exception e){ + LogUtil.error(LogEnum.BIZ_K8S,"Delete cache exception, namespace: {}, resourceName: {}, exception information: {}",namespace,resourceName,e); + return false; + } + } + + /** + * 删除pod名称缓存 + * + * @param namespace 命名空间 + * @param podName Pod名称 + * @return boolean true 删除成功 false删除失败 + */ + public boolean deletePodCacheByPodName(String namespace, String podName){ + try { + if (StringUtils.isNotEmpty(namespace) && StringUtils.isNotEmpty(podName)){ + String resourceName = (String) redisUtils.get(podNamePrefix +podName); + redisUtils.del(podNamePrefix + podName); + if (StringUtils.isNotEmpty(resourceName)){ + redisUtils.del(resourceNamePrefix +resourceName); + } + k8sResourceService.deleteByName(K8sKindEnum.POD.getKind(),namespace,podName); + } + return true; + }catch (Exception e){ + LogUtil.error(LogEnum.BIZ_K8S,"Delete cache exception, namespace: {}, podName: {}, exception information: {}",namespace,podName,e); + return false; + } + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/config/K8sCallbackMvcConfig.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/config/K8sCallbackMvcConfig.java new file mode 100644 index 0000000..8bf53ea --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/config/K8sCallbackMvcConfig.java @@ -0,0 +1,50 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.config; + + +import org.dubhe.k8s.interceptor.K8sCallBackPodInterceptor; +import org.dubhe.k8s.utils.K8sCallBackTool; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.InterceptorRegistration; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +import javax.annotation.Resource; + +/** + * @description Web Mvc Config + * @date 2020-05-28 + */ +@Configuration +public class K8sCallbackMvcConfig implements WebMvcConfigurer { + + @Resource + private K8sCallBackPodInterceptor k8sCallBackPodInterceptor; + + @Override + public void addInterceptors(InterceptorRegistry registry) { + InterceptorRegistration registration = registry.addInterceptor(k8sCallBackPodInterceptor); + // 拦截配置 + registration.addPathPatterns(K8sCallBackTool.getK8sCallbackPaths()); + + } + + + +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/config/K8sConfig.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/config/K8sConfig.java new file mode 100644 index 0000000..e01b988 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/config/K8sConfig.java @@ -0,0 +1,178 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.config; + +import cn.hutool.core.util.StrUtil; +import com.alibaba.fastjson.JSONObject; +import org.apache.http.HttpHost; +import org.apache.http.client.config.RequestConfig; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.dubhe.k8s.api.*; +import org.dubhe.k8s.api.impl.*; +import org.dubhe.k8s.cache.ResourceCache; +import org.dubhe.k8s.properties.ClusterProperties; +import org.dubhe.k8s.utils.K8sUtils; +import org.elasticsearch.client.RestClient; +import org.elasticsearch.client.RestClientBuilder; +import org.elasticsearch.client.RestHighLevelClient; +import org.mybatis.spring.annotation.MapperScan; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import java.io.IOException; + +import static org.apache.http.HttpVersion.HTTP; +import static org.dubhe.biz.base.constant.MagicNumConstant.TEN_THOUSAND; +import static org.dubhe.biz.base.constant.MagicNumConstant.ZERO; +import static org.dubhe.biz.base.constant.SymbolConstant.COLON; +import static org.dubhe.biz.base.constant.SymbolConstant.COMMA; + +/** + * @description load kubeconfig + * @date 2020-04-09 + */ +@Configuration +@EnableConfigurationProperties(ClusterProperties.class) +@MapperScan("org.dubhe.k8s.dao") +public class K8sConfig { + + @Autowired + private ClusterProperties clusterProperties; + + @Value("${k8s.elasticsearch.hostlist}") + private String hostlist; + + @Bean + public K8sUtils k8sUtils() throws IOException { + LogUtil.debug(LogEnum.BIZ_K8S, "ClusterProperties======{}", JSONObject.toJSONString(clusterProperties)); + if (clusterProperties == null) { + return null; + } + final String kubeconfig = clusterProperties.getKubeconfig(); + LogUtil.debug(LogEnum.BIZ_K8S, "ClusterProperties.getKubeconfig()======{}", clusterProperties.getKubeconfig()); + final String url = clusterProperties.getUrl(); + LogUtil.debug(LogEnum.BIZ_K8S, "ClusterProperties.getUrl()======{}", clusterProperties.getKubeconfig()); + if (StrUtil.isEmpty(url) && StrUtil.isEmpty(kubeconfig)) { + return null; + } + return new K8sUtils(clusterProperties); + } + + @Bean + public JupyterResourceApi jupyterResourceApi(K8sUtils k8sUtils) { + return new JupyterResourceApiImpl(k8sUtils); + } + + @Bean + public TrainJobApi jupyterJobApi(K8sUtils k8sUtils) { + return new TrainJobApiImpl(k8sUtils); + } + + @Bean + public PodApi podApi(K8sUtils k8sUtils) { + return new PodApiImpl(k8sUtils); + } + + @Bean + public NamespaceApi namespaceApi(K8sUtils k8sUtils) { + return new NamespaceApiImpl(k8sUtils); + } + + @Bean + public NodeApi nodeApi(K8sUtils k8sUtils) { + return new NodeApiImpl(k8sUtils); + } + + @Bean + public LimitRangeApi limitRangeApi(K8sUtils k8sUtils) { + return new LimitRangeApiImpl(k8sUtils); + } + + @Bean + public ResourceQuotaApi resourceQuotaApi(K8sUtils k8sUtils) { + return new ResourceQuotaApiImpl(k8sUtils); + } + + @Bean + public PersistentVolumeClaimApi persistentVolumeClaimApi(K8sUtils k8sUtils) { + return new PersistentVolumeClaimApiImpl(k8sUtils); + } + + @Bean + public LogMonitoringApi logMonitoringApi(K8sUtils k8sUtils) { + return new LogMonitoringApiImpl(k8sUtils); + } + + @Bean + public ResourceCache resourceCache() { + return new ResourceCache(); + } + + @Bean + public MetricsApi metricsApi(K8sUtils k8sUtils) { + return new MetricsApiImpl(k8sUtils); + } + + @Bean + public NativeResourceApi nativeResourceApi(K8sUtils k8sUtils) { + return new NativeResourceApiImpl(k8sUtils); + } + + @Bean + public DubheDeploymentApi dubheDeploymentApi(K8sUtils k8sUtils) { + return new DubheDeploymentApiImpl(k8sUtils); + } + + @Bean + public ModelOptJobApi jobApi(K8sUtils k8sUtils) { + return new ModelOptJobApiImpl(k8sUtils); + } + + @Bean + public DistributeTrainApi distributeTrainApi(K8sUtils k8sUtils) { + return new DistributeTrainApiImpl(k8sUtils); + } + + @Bean + public RestHighLevelClient restHighLevelClient(){ + + String[] hosts = hostlist.split(COMMA); + HttpHost[] httpHostArray = new HttpHost[hosts.length]; + for(int i=ZERO;i { +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/dao/K8sTaskMapper.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/dao/K8sTaskMapper.java new file mode 100644 index 0000000..55f2024 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/dao/K8sTaskMapper.java @@ -0,0 +1,58 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Update; +import org.dubhe.k8s.domain.bo.K8sTaskBO; +import org.dubhe.k8s.domain.entity.K8sTask; + +import java.util.List; + +/** + * @description k8s任务mapper接口 + * @date 2020-8-31 + */ +public interface K8sTaskMapper extends BaseMapper { + + /** + * 保存任务 + * + * @param k8sTask k8s任务类 + */ + int insertOrUpdate(K8sTask k8sTask); + + /** + * 查询待执行任务 + * + * @param k8sTaskBO k8s任务查询类 + * @return List k8s任务集合类 + */ + List selectUnexecutedTask(K8sTaskBO k8sTaskBO); + + /** + * 根据namespace 和 resourceName 删除 + * + * @param namespace 命名空间 + * @param resourceName 资源名称 + * @return boolean + */ + @Update("update k8s_task set deleted = #{deleteFlag} where namespace = #{namespace} and resource_name = #{resourceName}") + int deleteByNamespaceAndResourceName(@Param("namespace") String namespace,@Param("resourceName") String resourceName, @Param("deleteFlag") boolean deleteFlag); +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/PtBaseResult.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/PtBaseResult.java new file mode 100644 index 0000000..701bde3 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/PtBaseResult.java @@ -0,0 +1,80 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain; + +import cn.hutool.core.util.StrUtil; +import lombok.Data; +import lombok.experimental.Accessors; +import org.dubhe.k8s.constant.K8sParamConstants; +import org.dubhe.k8s.enums.K8sResponseEnum; + +import java.io.Serializable; + +/** + * @description base result + * @date 2020-04-23 + */ +@Data +@Accessors(chain = true) +public class PtBaseResult implements Serializable { + private static final long serialVersionUID = 1L; + /** + * 错误码 符合kubernertes错误码 + **/ + private String code = "200"; + /** + * 错误信息 + **/ + private String message; + + public PtBaseResult() { + } + + public PtBaseResult(String code, String message) { + this.code = code; + this.message = message; + } + + public T error(String code, String message) { + this.code = code; + this.message = message; + return (T) this; + } + + public T errorBadRequest() { + this.code = K8sResponseEnum.BAD_REQUEST.getCode(); + this.message = K8sResponseEnum.BAD_REQUEST.getMessage(); + return (T) this; + } + + public T validationErrorRequest(String fieldName) { + this.code = K8sResponseEnum.PRECONDITION_FAILED.getCode(); + this.message = StrUtil.format("{} 字段校验失败,k8s资源命名规则必须符合 {},且长度不超过 {}", fieldName, K8sParamConstants.K8S_RESOURCE_NAME_REGEX, K8sParamConstants.RESOURCE_NAME_LENGTH); + return (T) this; + } + + public T baseErrorBadRequest() { + this.code = K8sResponseEnum.BAD_REQUEST.getCode(); + this.message = K8sResponseEnum.BAD_REQUEST.getMessage(); + return (T) this; + } + + public boolean isSuccess() { + return K8sResponseEnum.SUCCESS.getCode().equals(code); + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/BuildFsVolumeBO.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/BuildFsVolumeBO.java new file mode 100644 index 0000000..63d0efd --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/BuildFsVolumeBO.java @@ -0,0 +1,39 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.bo; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +import java.util.Map; + +/** + * @description nfs存储卷 参数 + * @date 2020-09-10 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@Accessors(chain = true) +public class BuildFsVolumeBO { + private String namespace; + private String resourceName; + private Map fsMounts; +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/BuildIngressBO.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/BuildIngressBO.java new file mode 100644 index 0000000..259ea8b --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/BuildIngressBO.java @@ -0,0 +1,121 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.bo; + +import io.fabric8.kubernetes.api.model.extensions.IngressRule; +import io.fabric8.kubernetes.api.model.extensions.IngressTLS; +import lombok.Data; +import lombok.experimental.Accessors; +import org.dubhe.biz.base.constant.SymbolConstant; +import org.dubhe.biz.base.utils.StringUtils; +import org.dubhe.k8s.constant.K8sParamConstants; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * @description 构建 Ingress + * @date 2020-09-11 + */ +@Data +@Accessors(chain = true) +public class BuildIngressBO { + /** + * 命名空间 + **/ + private String namespace; + /** + * 名称 + */ + private String name; + /** + * 标签 + */ + private Map labels; + /** + * 上传限制 + */ + private String maxUploadSize; + /** + * 根路径 + */ + private String path; + /** + * A list of host rules used to configure the Ingress + **/ + private List ingressRules; + /** + * TLS configuration + **/ + private List ingressTLSs; + + private Map annotations; + + public BuildIngressBO(String namespace, String name, Map labels){ + this.namespace = namespace; + this.name = name; + this.labels = labels; + this.maxUploadSize = K8sParamConstants.INGRESS_MAX_UPLOAD_SIZE; + this.path = SymbolConstant.SLASH; + } + + /** + * 添加ingress 规则 + * @param ingressRule + */ + public void addIngressRule(IngressRule ingressRule){ + if (null == ingressRule){ + return; + } + if (ingressRules == null){ + ingressRules = new ArrayList<>(); + } + ingressRules.add(ingressRule); + } + + /** + * 添加 ingress tls + * @param ingressTLS + */ + public void addIngressTLS(IngressTLS ingressTLS){ + if (null == ingressTLS){ + return; + } + if (ingressTLSs == null){ + ingressTLSs = new ArrayList<>(); + } + ingressTLSs.add(ingressTLS); + } + + /** + * 设置 annotation + * @param key + * @param value + */ + public void putAnnotation(String key,String value){ + if (StringUtils.isEmpty(key) || StringUtils.isEmpty(value)){ + return; + } + if (annotations == null){ + annotations = new HashMap<>(); + } + annotations.put(key,value); + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/BuildServiceBO.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/BuildServiceBO.java new file mode 100644 index 0000000..b37e8f2 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/BuildServiceBO.java @@ -0,0 +1,58 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.bo; + +import io.fabric8.kubernetes.api.model.ServicePort; +import lombok.Data; +import lombok.experimental.Accessors; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +/** + * @description 构建 Service + * @date 2020-09-11 + */ +@Data +@Accessors(chain = true) +public class BuildServiceBO { + private String namespace; + private String name; + private Map labels; + private Map selector; + private List ports; + + public BuildServiceBO(String namespace, String name, Map labels, Map selector){ + this.namespace = namespace; + this.name = name; + this.labels = labels; + this.selector = selector; + } + + /** + * 添加端口 + * @param port + */ + public void addPort(ServicePort port){ + if (ports == null){ + ports = new ArrayList<>(); + } + ports.add(port); + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/DistributeTrainBO.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/DistributeTrainBO.java new file mode 100644 index 0000000..c8565bd --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/DistributeTrainBO.java @@ -0,0 +1,142 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.bo; + +import cn.hutool.core.collection.CollectionUtil; +import lombok.Data; +import lombok.experimental.Accessors; +import org.dubhe.biz.base.constant.MagicNumConstant; +import org.dubhe.k8s.annotation.K8sValidation; +import org.dubhe.k8s.enums.ValidationTypeEnum; +import org.dubhe.biz.base.utils.StringUtils; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * @description DistributeTrainBO + * @date 2020-07-08 + */ +@Data +@Accessors(chain = true) +public class DistributeTrainBO { + /** + * 命名空间 + **/ + @K8sValidation(ValidationTypeEnum.K8S_RESOURCE_NAME) + private String namespace; + /** + * 资源名称 + **/ + @K8sValidation(ValidationTypeEnum.K8S_RESOURCE_NAME) + private String name; + /** + * 多机启动实例数 + **/ + private Integer size; + /** + * 镜像名称 + **/ + private String image; + /** + * master机器运行时执行命令 + **/ + private String masterCmd; + /** + * 每个节点运行使用内存,单位Mi + **/ + private Integer memNum; + /** + * 每个节点运行使用CPU数量,1000代表占用一核心 + **/ + private Integer cpuNum; + /** + * 每个节点运行使用GPU数量 + **/ + private Integer gpuNum; + /** + * slave机器运行时执行命令 + **/ + private String slaveCmd; + /** + * 运行环境变量 + **/ + private Map env; + /** + * 业务标签,用于标识业务模块 + **/ + private String businessLabel; + /** + * 延时创建时间,单位:分钟 + ***/ + private Integer delayCreateTime; + /** + * 定时删除时间,相对于实际创建时间,单位:分钟 + **/ + private Integer delayDeleteTime; + /** + * 文件存储服务挂载 key:pod内挂载路径 value:文件存储路径及配置 + **/ + private Map fsMounts; + + /** + * 设置文件存储挂载 + * @param mountPath pod内挂载路径 + * @param dir 文件存储服务路径 + * @return + */ + public DistributeTrainBO putFsMounts(String mountPath,String dir){ + if (StringUtils.isNotEmpty(mountPath) && StringUtils.isNotEmpty(dir)){ + if (fsMounts == null){ + fsMounts = new HashMap<>(MagicNumConstant.EIGHT); + } + fsMounts.put(mountPath,new PtMountDirBO(dir)); + } + return this; + } + + /** + * 设置文件存储挂载 + * @param mountPath pod内挂载路径 + * @param dir 文件存储服务路径及配置 + * @return + */ + public DistributeTrainBO putFsMounts(String mountPath,PtMountDirBO dir){ + if (StringUtils.isNotEmpty(mountPath) && dir != null){ + if (fsMounts == null){ + fsMounts = new HashMap<>(MagicNumConstant.EIGHT); + } + fsMounts.put(mountPath,dir); + } + return this; + } + + /** + * 获取 文件存储服务路径列表 + * @return + */ + public List getDirList(){ + if (CollectionUtil.isNotEmpty(fsMounts)){ + return fsMounts.values().stream().map(PtMountDirBO::getDir).collect(Collectors.toList()); + } + return new ArrayList<>(); + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/K8sTaskBO.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/K8sTaskBO.java new file mode 100644 index 0000000..02859a4 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/K8sTaskBO.java @@ -0,0 +1,40 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.bo; + +import lombok.Data; +import lombok.NoArgsConstructor; +import org.dubhe.k8s.domain.entity.K8sTask; + +/** + * @description K8sTaskBO k8s任务参数 + * @date 2020-09-01 + */ +@Data +@NoArgsConstructor +public class K8sTaskBO extends K8sTask { + /** + * 最大创建时间 + */ + private Long maxApplyUnixTime; + /** + * 最大停止时间 + */ + private Long maxStopUnixTime; + +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/LabelBO.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/LabelBO.java new file mode 100644 index 0000000..2dc7168 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/LabelBO.java @@ -0,0 +1,61 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.bo; + +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.util.Map; + +/** + * @description k8s resource的label + * @date 2020-04-14 + */ +@Data +@EqualsAndHashCode +public class LabelBO implements Map.Entry { + + private String key; + private String value; + + public LabelBO(String key, String value) { + this.key = key; + this.value = value; + } + + public static LabelBO of(String key, String value) { + return new LabelBO(key, value); + } + + @Override + public String getKey() { + return key; + } + + @Override + public String getValue() { + return value; + } + + @Override + public String setValue(String value) { + String old = this.value; + this.value = value; + return old; + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/LogMonitoringBO.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/LogMonitoringBO.java new file mode 100644 index 0000000..832261a --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/LogMonitoringBO.java @@ -0,0 +1,74 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.bo; +import lombok.Data; +import lombok.experimental.Accessors; +import org.dubhe.k8s.domain.dto.PodLogQueryDTO; + +import java.util.Set; +/** + * @description LogMonitoringBO实体类 + * @date 2020-05-12 + */ +@Data +@Accessors(chain = true) +public class LogMonitoringBO { + /** + * 命名空间 + **/ + private String namespace; + /** + * 资源名称 + **/ + private String resourceName; + /** + * pod名称 + **/ + private String podName; + /** + * pod名称,一个resourceName可能对应多个podName + **/ + private Set podNames; + /** + * 日志查询条件:关键字 + **/ + private String logKeyword; + /** + * 日志查询时间范围:开始时间 + **/ + private Long beginTimeMillis; + /** + * 日志查询时间范围:结束时间 + **/ + private Long endTimeMillis; + + public LogMonitoringBO(String namespace,String podName){ + this.namespace = namespace; + this.podName = podName; + } + + public LogMonitoringBO(String namespace, PodLogQueryDTO podLogQueryDTO){ + this.namespace = namespace; + this.podName = podLogQueryDTO.getPodName(); + this.logKeyword = podLogQueryDTO.getLogKeyword(); + this.beginTimeMillis = podLogQueryDTO.getBeginTimeMillis(); + this.endTimeMillis = podLogQueryDTO.getEndTimeMillis(); + } + + public LogMonitoringBO(){ + } +} \ No newline at end of file diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/ModelServingBO.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/ModelServingBO.java new file mode 100644 index 0000000..dbbaa4c --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/ModelServingBO.java @@ -0,0 +1,135 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.bo; + +import cn.hutool.core.collection.CollectionUtil; +import lombok.Data; +import lombok.experimental.Accessors; +import org.dubhe.biz.base.constant.MagicNumConstant; +import org.dubhe.biz.base.utils.StringUtils; +import org.dubhe.k8s.annotation.K8sValidation; +import org.dubhe.k8s.enums.ValidationTypeEnum; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * @description 模型部署 BO + * @date 2020-09-10 + */ +@Data +@Accessors(chain = true) +public class ModelServingBO { + /** + * 命名空间 + **/ + @K8sValidation(ValidationTypeEnum.K8S_RESOURCE_NAME) + private String namespace; + /** + * 资源名称 + **/ + @K8sValidation(ValidationTypeEnum.K8S_RESOURCE_NAME) + private String resourceName; + /** + * Number of desired pods + */ + private Integer replicas; + /** + * GPU数量 + **/ + private Integer gpuNum; + /** + * 内存数量 单位Mi Gi + **/ + private Integer memNum; + /** + * CPU数量 + **/ + private Integer cpuNum; + /** + * 镜像名称 + **/ + private String image; + /** + * 执行命令 + **/ + private List cmdLines; + /** + * 文件存储服务挂载 key:pod内挂载路径 value:文件存储路径及配置 + **/ + private Map fsMounts; + /** + * 业务标签,用于标识业务模块 + **/ + @K8sValidation(ValidationTypeEnum.K8S_RESOURCE_NAME) + private String businessLabel; + /** + * http服务端口,null则不开放http服务 + */ + private Integer httpPort; + /** + * grpc服务端口,null则不开放grpc服务 + */ + private Integer grpcPort; + + /** + * 获取nfs路径 + * @return + */ + public List getDirList(){ + if (CollectionUtil.isNotEmpty(fsMounts)){ + return fsMounts.values().stream().map(PtMountDirBO::getDir).collect(Collectors.toList()); + } + return new ArrayList<>(); + } + + /** + * 设置nfs挂载 + * @param mountPath 容器内路径 + * @param dir nfs路径 + * @return + */ + public ModelServingBO putNfsMounts(String mountPath, String dir){ + if (StringUtils.isNotEmpty(mountPath) && StringUtils.isNotEmpty(dir)){ + if (fsMounts == null){ + fsMounts = new HashMap<>(MagicNumConstant.TWO); + } + fsMounts.put(mountPath,new PtMountDirBO(dir)); + } + return this; + } + + /** + * 设置nfs挂载 + * @param mountPath 容器内路径 + * @param dir nfs路径及配置 + * @return + */ + public ModelServingBO putNfsMounts(String mountPath, PtMountDirBO dir){ + if (StringUtils.isNotEmpty(mountPath) && dir != null){ + if (fsMounts == null){ + fsMounts = new HashMap<>(MagicNumConstant.TWO); + } + fsMounts.put(mountPath,dir); + } + return this; + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/PrometheusMetricBO.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/PrometheusMetricBO.java new file mode 100644 index 0000000..5be6584 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/PrometheusMetricBO.java @@ -0,0 +1,120 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.bo; + +import lombok.Data; +import org.dubhe.biz.base.functional.StringFormat; +import org.dubhe.k8s.domain.vo.GpuUsageVO; +import org.dubhe.k8s.domain.vo.MetricsDataResultVO; +import org.dubhe.k8s.domain.vo.MetricsDataResultValueVO; +import org.springframework.util.CollectionUtils; + +import java.util.ArrayList; +import java.util.List; + +/** + * @description Gpu 指标 BO + * @date 2020-10-13 + */ +@Data +public class PrometheusMetricBO { + private String status; + private MetricData data; + + /** + * 获取Gpu 使用率 + * @return List gpu使用列表 + */ + public List getGpuUsage(){ + List gpuUsageVOList = new ArrayList<>(); + if (data == null || CollectionUtils.isEmpty(data.getResult())){ + return gpuUsageVOList; + } + for (MetricResult result : data.getResult()){ + gpuUsageVOList.add(new GpuUsageVO(result.getMetric().getAcc_id(),Float.valueOf(result.getValue().get(1).toString()))); + } + return gpuUsageVOList; + } + + /** + * 获取value 列表 + * @return List 监控指标列表 + */ + public List getValues(StringFormat stringFormat){ + List list = new ArrayList<>(); + if (data == null || CollectionUtils.isEmpty(data.getResult())){ + return list; + } + for (MetricResult result : data.getResult()){ + result.getValues().forEach(obj->{ + list.add(new MetricsDataResultValueVO(obj.get(0).toString(),stringFormat.format(obj.get(1).toString()))); + }); + } + return list; + } + + /** + * 获取value 列表 + * @return List 监控指标列表 + */ + public List getValues(MetricResult metricResult){ + List list = new ArrayList<>(); + if (metricResult == null || CollectionUtils.isEmpty(metricResult.getValues())){ + return list; + } + metricResult.getValues().forEach(obj->{ + list.add(new MetricsDataResultValueVO(obj.get(0).toString(),obj.get(1).toString())); + }); + return list; + } + + /** + * 获取 result列表 + * @return List 监控指标列表 + */ + public List getResults(){ + List list = new ArrayList<>(); + if (data == null || CollectionUtils.isEmpty(data.getResult())){ + return list; + } + for (MetricResult result : data.getResult()){ + list.add(new MetricsDataResultVO(result.getMetric().getAcc_id(),getValues(result))); + } + return list; + } +} + +@Data +class MetricData { + private String resultType; + private List result; +} + +@Data +class MetricResult { + private Metric metric; + List value; + List> values; +} + +@Data +class Metric { + private String acc_id; + private String pod; +} + diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/PtDeploymentBO.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/PtDeploymentBO.java new file mode 100644 index 0000000..6805534 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/PtDeploymentBO.java @@ -0,0 +1,60 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.bo; + +import lombok.Data; +import org.dubhe.k8s.annotation.K8sValidation; +import org.dubhe.k8s.enums.ValidationTypeEnum; + +/** + * @description deployment bo + * @date 2020-05-26 + */ +@Data +public class PtDeploymentBO { + /** + * 命名空间 + **/ + @K8sValidation(ValidationTypeEnum.K8S_RESOURCE_NAME) + private String namespace; + /** + * 资源名称 + **/ + @K8sValidation(ValidationTypeEnum.K8S_RESOURCE_NAME) + private String name; + /** + * GPU数量,0表示共享显卡,null表示不使用显卡 + **/ + private Integer gpuNum; + /** + * 内存数量单位 Mi + **/ + private Integer memNum; + /** + * CPU数量 1000代表占用一个核心 + **/ + private Integer cpuNum; + /** + * 镜像名称 + **/ + private String image; + /** + * 业务标签,用于标识业务模块 + **/ + private String businessLabel; +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/PtJobBO.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/PtJobBO.java new file mode 100644 index 0000000..e48dd7e --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/PtJobBO.java @@ -0,0 +1,60 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.bo; + +import lombok.Data; +import org.dubhe.k8s.annotation.K8sValidation; +import org.dubhe.k8s.enums.ValidationTypeEnum; + +/** + * @description job bo + * @date 2020-05-31 + */ +@Data +public class PtJobBO { + /** + * 命名空间 + **/ + @K8sValidation(ValidationTypeEnum.K8S_RESOURCE_NAME) + private String namespace; + /** + * 资源名称 + **/ + @K8sValidation(ValidationTypeEnum.K8S_RESOURCE_NAME) + private String name; + /** + * GPU数量,0表示共享显卡,null表示不使用显卡 + **/ + private Integer gpuNum; + /** + * 内存数量单位 Mi + **/ + private Integer memNum; + /** + * CPU数量 1000代表占用一个核心 + **/ + private Integer cpuNum; + /** + * 镜像名称 + **/ + private String image; + /** + * 业务标签,用于标识业务模块 + **/ + private String businessLabel; +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/PtJupyterJobBO.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/PtJupyterJobBO.java new file mode 100644 index 0000000..e22c499 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/PtJupyterJobBO.java @@ -0,0 +1,100 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.bo; + +import cn.hutool.core.collection.CollectionUtil; +import lombok.Data; +import lombok.experimental.Accessors; +import org.dubhe.biz.base.constant.MagicNumConstant; +import org.dubhe.k8s.annotation.K8sValidation; +import org.dubhe.k8s.enums.GraphicsCardTypeEnum; +import org.dubhe.k8s.enums.ValidationTypeEnum; +import org.dubhe.biz.base.utils.StringUtils; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * @description 训练任务 Job BO + * @date 2020-04-22 + */ +@Data +@Accessors(chain = true) +public class PtJupyterJobBO { + /**命名空间**/ + @K8sValidation(ValidationTypeEnum.K8S_RESOURCE_NAME) + private String namespace; + /**资源名称**/ + @K8sValidation(ValidationTypeEnum.K8S_RESOURCE_NAME) + private String name; + /**GPU数量,1代表使用一张显卡**/ + private Integer gpuNum; + /**是否使用gpu true:使用;false:不用**/ + private Boolean useGpu; + /**内存数量,单位Mi**/ + private Integer memNum; + /**cpu用量 单位:m 1个核心=1000m**/ + private Integer cpuNum; + /**镜像名称**/ + private String image; + /**执行命令**/ + private List cmdLines; + + /**文件存储服务挂载 key:pod内挂载路径 value:文件存储路径及配置**/ + private Map fsMounts; + + /**显卡类型**/ + private GraphicsCardTypeEnum graphicsCardType; + /**业务标签,用于标识业务模块**/ + private String businessLabel; + /**延时创建时间,单位:分钟**/ + private Integer delayCreateTime; + /**定时删除时间,相对于实际创建时间,单位:分钟**/ + private Integer delayDeleteTime; + + + public List getDirList(){ + if (CollectionUtil.isNotEmpty(fsMounts)){ + return fsMounts.values().stream().map(PtMountDirBO::getDir).collect(Collectors.toList()); + } + return new ArrayList<>(); + } + + public PtJupyterJobBO putFsMounts(String mountPath,String dir){ + if (StringUtils.isNotEmpty(mountPath) && StringUtils.isNotEmpty(dir)){ + if (fsMounts == null){ + fsMounts = new HashMap<>(MagicNumConstant.TWO); + } + fsMounts.put(mountPath,new PtMountDirBO(dir)); + } + return this; + } + + public PtJupyterJobBO putFsMounts(String mountPath,PtMountDirBO dir){ + if (StringUtils.isNotEmpty(mountPath) && dir != null){ + if (fsMounts == null){ + fsMounts = new HashMap<>(MagicNumConstant.TWO); + } + fsMounts.put(mountPath,dir); + } + return this; + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/PtJupyterResourceBO.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/PtJupyterResourceBO.java new file mode 100644 index 0000000..3779d1f --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/PtJupyterResourceBO.java @@ -0,0 +1,104 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.bo; + +import lombok.Data; +import lombok.experimental.Accessors; +import org.dubhe.k8s.annotation.K8sValidation; +import org.dubhe.k8s.enums.ValidationTypeEnum; + +/** + * @description Notebook BO + * @date 2020-04-17 + */ +@Data +@Accessors(chain = true) +public class PtJupyterResourceBO { + /** + * 命名空间 + **/ + @K8sValidation(ValidationTypeEnum.K8S_RESOURCE_NAME) + private String namespace; + /** + * 资源名称 + **/ + @K8sValidation(ValidationTypeEnum.K8S_RESOURCE_NAME) + private String name; + /** + * GPU数量 + **/ + private Integer gpuNum; + /** + * 是否使用gpu true:使用;false:不用 + **/ + private Boolean useGpu; + /** + * 内存数量 单位Mi Gi + **/ + private Integer memNum; + /** + * CPU数量 + **/ + private Integer cpuNum; + /** + * 镜像名称 + **/ + private String image; + + /** + * nfs存储路径,存在且能被挂载,此路径内容不能通过接口销毁,不传不会挂载 + **/ + private String datasetDir; + /** + * 本docker内的路径,挂载到datasetDir + **/ + private String datasetMountPath; + /** + * datasetDir是否只读 + **/ + private Boolean datasetReadOnly; + + /** + * nfs存储路径,存在且能被挂载,此路径内容在调用PersistentVolumeClaimApi.recycle后销毁,不传会生成默认的 + **/ + private String workspaceDir; + /** + * 本docker内的路径,挂载到datasetDir + **/ + private String workspaceMountPath; + /** + * workspaceDir的存储配额 必须 + **/ + private String workspaceRequest; + /** + * workspaceDir的存储限额 非必须 + **/ + private String workspaceLimit; + /** + * used in internal + **/ + private String workspacePvcName; + /** + * 业务标签,用于标识业务模块 + **/ + private String businessLabel; + /** + * 定时删除时间,单位:分钟 + **/ + private Integer delayDeleteTime; +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/PtLimitRangeBO.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/PtLimitRangeBO.java new file mode 100644 index 0000000..d7a1678 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/PtLimitRangeBO.java @@ -0,0 +1,40 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.bo; + +import org.dubhe.k8s.annotation.K8sValidation; +import org.dubhe.k8s.domain.resource.BizLimitRangeItem; +import lombok.Data; +import lombok.experimental.Accessors; +import org.dubhe.k8s.enums.ValidationTypeEnum; + +import java.util.List; + +/** + * @description LimitRange BO + * @date 2020-04-23 + */ +@Data +@Accessors(chain = true) +public class PtLimitRangeBO { + @K8sValidation(ValidationTypeEnum.K8S_RESOURCE_NAME) + private String namespace; + @K8sValidation(ValidationTypeEnum.K8S_RESOURCE_NAME) + private String name; + private List limits; +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/PtModelOptimizationDeploymentBO.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/PtModelOptimizationDeploymentBO.java new file mode 100644 index 0000000..3321116 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/PtModelOptimizationDeploymentBO.java @@ -0,0 +1,66 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.bo; + +import lombok.Data; + +import java.util.List; + +/** + * @description 模型压缩 Deployment BO + * 在继承中使用 @Accessors(chain = true) 在set父类方法后会返回父类对象,故不使用 + * @date 2020-05-26 + */ +@Data +public class PtModelOptimizationDeploymentBO extends PtDeploymentBO { + /** + * 挂载到dataset的数据集的路径 + **/ + private String datasetDir; + /** + * 本docker内的路径,挂载到datasetDir,默认值/dataset + **/ + private String datasetMountPath; + /** + * 数据集是否只读 + **/ + private Boolean datasetReadOnly; + /** + * 执行命令 + **/ + private List cmdLines; + + /** + * nfs存储路径,且能被挂载,不传会生成默认的 + **/ + private String workspaceDir; + /** + * 本docker内的路径,挂载到workspaceDir,默认值默认值/workspace + **/ + private String workspaceMountPath; + + /** + * nfs存储路径,且能被挂载,默认 + **/ + private String outputDir; + /** + * 本docker内的路径,挂载到outputDir,默认值默认值/output + **/ + private String outputMountPath; + +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/PtModelOptimizationJobBO.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/PtModelOptimizationJobBO.java new file mode 100644 index 0000000..8eb4610 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/PtModelOptimizationJobBO.java @@ -0,0 +1,71 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.bo; + +import cn.hutool.core.collection.CollectionUtil; +import lombok.Data; +import org.dubhe.biz.base.constant.MagicNumConstant; +import org.dubhe.biz.base.utils.StringUtils; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * @description 模型压缩 Job BO + * @date 2020-05-31 + */ +@Data +public class PtModelOptimizationJobBO extends PtJobBO { + /** + * 执行命令 + **/ + private List cmdLines; + + /**文件存储服务挂载 key:pod内挂载路径 value:文件存储路径及配置**/ + private Map fsMounts; + + public List getDirList(){ + if (CollectionUtil.isNotEmpty(fsMounts)){ + return fsMounts.values().stream().map(PtMountDirBO::getDir).collect(Collectors.toList()); + } + return new ArrayList<>(); + } + + public PtModelOptimizationJobBO putNfsMounts(String mountPath,String dir){ + if (StringUtils.isNotEmpty(mountPath) && StringUtils.isNotEmpty(dir)){ + if (fsMounts == null){ + fsMounts = new HashMap<>(MagicNumConstant.TWO); + } + fsMounts.put(mountPath,new PtMountDirBO(dir)); + } + return this; + } + + public PtModelOptimizationJobBO putNfsMounts(String mountPath,PtMountDirBO dir){ + if (StringUtils.isNotEmpty(mountPath) && dir != null){ + if (fsMounts == null){ + fsMounts = new HashMap<>(MagicNumConstant.TWO); + } + fsMounts.put(mountPath,dir); + } + return this; + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/PtMountDirBO.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/PtMountDirBO.java new file mode 100644 index 0000000..091fa8e --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/PtMountDirBO.java @@ -0,0 +1,51 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.bo; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.experimental.Accessors; + +/** + * @description 挂载路径参数 + * @date 2020-06-30 + */ +@Data +@AllArgsConstructor +@Accessors(chain = true) +public class PtMountDirBO { + /**挂载的路径,绝对路径**/ + private String dir; + /**是否只读 ture:是 false:否**/ + private boolean readOnly; + /**是否回收 true:创建pv、pvc进行挂载,删除时同时删除数据 false:直接挂载**/ + private boolean recycle; + /**存储配额 示例:500Mi 仅在pvc=true时生效**/ + private String request; + /**存储限额 示例:500Mi 仅在pvc=true时生效**/ + private String limit; + + public PtMountDirBO(String dir){ + this.dir = dir; + } + + public PtMountDirBO(String dir, String request){ + this.dir = dir; + this.request = request; + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/PtPersistentVolumeClaimBO.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/PtPersistentVolumeClaimBO.java new file mode 100644 index 0000000..534bafd --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/PtPersistentVolumeClaimBO.java @@ -0,0 +1,111 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.bo; + +import cn.hutool.core.util.RandomUtil; +import org.dubhe.biz.base.constant.MagicNumConstant; +import org.dubhe.k8s.domain.resource.BizQuantity; +import lombok.Data; +import lombok.experimental.Accessors; +import org.dubhe.k8s.enums.AccessModeEnum; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +/** + * @description PVC BO + * @date 2020-04-23 + */ +@Data +@Accessors(chain = true) +public class PtPersistentVolumeClaimBO { + private String namespace; + private String pvcName; + /** + * 指定StorageClass 的 provisioner + **/ + private String provisioner; + /** + * 指定StorageClass 的 volumeBindingMode + **/ + private String volumeBindingMode; + /** + * 资源配额 + **/ + private Map capacity; + /** + * PVC的accessModes ReadWriteOnce:单node的读写 ReadOnlyMany:多node的只读 ReadWriteMany:多node的读写 + **/ + private Set accessModes; + /** + * 标签 + **/ + private Map labels; + /** + * 用户填写的资源名称 + **/ + private String resourceName; + /** + * 关于provisioner的配置,目前用不到 + **/ + private Map parameters; + /** + * 存储限额 + **/ + private String limit; + /** + * 存储配额 + **/ + private String request; + /** + * pv挂载存储路径 + **/ + private String path; + + public PtPersistentVolumeClaimBO() { + + } + + public PtPersistentVolumeClaimBO(PtJupyterResourceBO bo) { + this.labels = new HashMap<>(); + this.namespace = bo.getNamespace(); + this.request = bo.getWorkspaceRequest(); + this.limit = bo.getWorkspaceLimit(); + this.path = bo.getWorkspaceDir(); + this.resourceName = bo.getName(); + this.accessModes = new HashSet() {{ + add(AccessModeEnum.READ_WRITE_ONCE.getType()); + }}; + this.setPvcName(bo.getName() + "-" + RandomUtil.randomString(MagicNumConstant.FIVE)); + } + + public PtPersistentVolumeClaimBO(String namespace,String resourceName,PtMountDirBO bo){ + this.labels = new HashMap<>(); + this.namespace = namespace; + this.request = bo.getRequest(); + this.limit = bo.getLimit(); + this.path = bo.getDir(); + this.resourceName = resourceName; + this.accessModes = new HashSet(){{ + add(AccessModeEnum.READ_WRITE_ONCE.getType()); + }}; + this.setPvcName(resourceName+"-"+RandomUtil.randomString(MagicNumConstant.FIVE)); + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/PtResourceQuotaBO.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/PtResourceQuotaBO.java new file mode 100644 index 0000000..e423f75 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/PtResourceQuotaBO.java @@ -0,0 +1,81 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.bo; + +import org.dubhe.biz.base.constant.SymbolConstant; +import org.dubhe.k8s.annotation.K8sValidation; +import org.dubhe.k8s.constant.K8sParamConstants; +import org.dubhe.k8s.domain.resource.BizQuantity; +import org.dubhe.k8s.domain.resource.BizScopedResourceSelectorRequirement; +import lombok.Data; +import lombok.experimental.Accessors; +import org.dubhe.k8s.enums.ValidationTypeEnum; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * @description ResourceQuota BO + * @date 2020-04-23 + */ +@Data +@Accessors(chain = true) +public class PtResourceQuotaBO { + @K8sValidation(ValidationTypeEnum.K8S_RESOURCE_NAME) + private String namespace; + @K8sValidation(ValidationTypeEnum.K8S_RESOURCE_NAME) + private String name; + private Map hard; + private List scopeSelector; + + /** + * 添加cpu 限制 + * @param amount 值 + * @param format 单位 + */ + public void addCpuLimitsHard(String amount,String format){ + if (hard == null){ + hard = new HashMap<>(); + } + hard.put(K8sParamConstants.RESOURCE_QUOTA_CPU_LIMITS_KEY,new BizQuantity(amount,format)); + } + + /** + * 添加cpu 限制 + * @param amount 值 + * @param format 单位 + */ + public void addMemoryLimitsHard(String amount,String format){ + if (hard == null){ + hard = new HashMap<>(); + } + hard.put(K8sParamConstants.RESOURCE_QUOTA_MEMORY_LIMITS_KEY,new BizQuantity(amount,format)); + } + + /** + * 添加gpu 限制 + * @param amount 值 + */ + public void addGpuLimitsHard(String amount){ + if (hard == null){ + hard = new HashMap<>(); + } + hard.put(K8sParamConstants.RESOURCE_QUOTA_GPU_LIMITS_KEY,new BizQuantity(amount, SymbolConstant.BLANK)); + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/ResourceYamlBO.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/ResourceYamlBO.java new file mode 100644 index 0000000..7e5f987 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/ResourceYamlBO.java @@ -0,0 +1,41 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.bo; + +import lombok.Data; + +/** + * @description K8s resource yaml description + * @date 2020-08-28 + */ +@Data +public class ResourceYamlBO { + /** + * K8s resource kind + */ + private String kind; + /** + * K8s resource yaml definition + */ + private String yaml; + + public ResourceYamlBO(String kind,String yaml){ + this.kind = kind; + this.yaml = yaml; + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/TaskYamlBO.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/TaskYamlBO.java new file mode 100644 index 0000000..c2c31ff --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/bo/TaskYamlBO.java @@ -0,0 +1,43 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.bo; + +import io.fabric8.kubernetes.api.model.HasMetadata; +import lombok.Data; +import org.dubhe.k8s.utils.YamlUtils; + +import java.util.LinkedList; +import java.util.List; + +/** + * @description 任务k8s资源列表 + * @date 2020-08-28 + */ +@Data +public class TaskYamlBO { + private List yamlList; + + public TaskYamlBO() { + yamlList = new LinkedList(); + } + + public void append(HasMetadata resource) { + String kind = resource.getKind(); + yamlList.add(new ResourceYamlBO(kind, YamlUtils.dumpAsYaml(resource))); + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/cr/DistributeTrain.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/cr/DistributeTrain.java new file mode 100644 index 0000000..651200e --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/cr/DistributeTrain.java @@ -0,0 +1,62 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.cr; + +import io.fabric8.kubernetes.api.model.Namespaced; +import io.fabric8.kubernetes.api.model.ObjectMeta; +import io.fabric8.kubernetes.client.CustomResource; + +/** + * @description 自定义资源 DistributeTrain + * @date 2020-07-07 + */ +public class DistributeTrain extends CustomResource implements Namespaced { + private String apiVersion = "onebrain.oneflow.org/v1alpha1"; + private String kind = "DistributeTrain"; + + private DistributeTrainSpec spec; + + @Override + public String toString() { + return "DistributeTrain{" + + "apiVersion='" + getApiVersion() + '\'' + + ", metadata=" + getMetadata() + + ", spec=" + spec + + '}'; + } + + public DistributeTrainSpec getSpec() { + return spec; + } + + public void setSpec(DistributeTrainSpec spec) { + this.spec = spec; + } + + @Override + public ObjectMeta getMetadata() { return super.getMetadata(); } + + @Override + public String getApiVersion() { + return apiVersion; + } + + @Override + public String getKind() { + return kind; + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/cr/DistributeTrainDoneable.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/cr/DistributeTrainDoneable.java new file mode 100644 index 0000000..4f0dcc1 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/cr/DistributeTrainDoneable.java @@ -0,0 +1,30 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.cr; + +import io.fabric8.kubernetes.api.builder.Function; +import io.fabric8.kubernetes.client.CustomResourceDoneable; + +/** + * @description 自定义资源的 DistributeTrainDoneable + * @date 2020-07-07 + */ +public class DistributeTrainDoneable extends CustomResourceDoneable { + public DistributeTrainDoneable(DistributeTrain resource, Function function) { + super(resource, function); + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/cr/DistributeTrainList.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/cr/DistributeTrainList.java new file mode 100644 index 0000000..0171c7a --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/cr/DistributeTrainList.java @@ -0,0 +1,26 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.cr; + +import io.fabric8.kubernetes.client.CustomResourceList; + +/** + * @description 自定义资源dt集合类 + * @date 2020-07-07 + */ +public class DistributeTrainList extends CustomResourceList { +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/cr/DistributeTrainSpec.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/cr/DistributeTrainSpec.java new file mode 100644 index 0000000..5bc6d3d --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/cr/DistributeTrainSpec.java @@ -0,0 +1,175 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.cr; + +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import io.fabric8.kubernetes.api.model.*; +import org.springframework.util.CollectionUtils; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * @description 自定义资源dt详情类 + * @date 2020-07-07 + */ +@JsonDeserialize( + using = JsonDeserializer.None.class +) +public class DistributeTrainSpec implements KubernetesResource { + private Integer size; + private String image; + private String imagePullPolicy; + private String masterCmd; + private ResourceRequirements masterResources; + private String slaveCmd; + private ResourceRequirements slaveResources; + private Map nodeSelector = new HashMap<>(); + private List env = new ArrayList<>(); + /** + * 内部映射 + */ + private List volumeMounts; + /** + * 外部挂载 + */ + private List volumes; + + /** + * 容忍度 + */ + private List tolerations = new ArrayList<>(); + + public Integer getSize() { + return size; + } + + public void setSize(Integer size) { + this.size = size; + } + + public String getImage() { + return image; + } + + public void setImage(String image) { + this.image = image; + } + + public String getImagePullPolicy() { + return imagePullPolicy; + } + + public void setImagePullPolicy(String imagePullPolicy) { + this.imagePullPolicy = imagePullPolicy; + } + + public String getMasterCmd() { + return masterCmd; + } + + public void setMasterCmd(String masterCmd) { + this.masterCmd = masterCmd; + } + + public ResourceRequirements getMasterResources() { + return masterResources; + } + + public void setMasterResources(ResourceRequirements masterResources) { + this.masterResources = masterResources; + } + + public String getSlaveCmd() { + return slaveCmd; + } + + public void setSlaveCmd(String slaveCmd) { + this.slaveCmd = slaveCmd; + } + + public ResourceRequirements getSlaveResources() { + return slaveResources; + } + + public void setSlaveResources(ResourceRequirements slaveResources) { + this.slaveResources = slaveResources; + } + + public Map getNodeSelector() { + return nodeSelector; + } + + public void setNodeSelector(Map nodeSelector) { + this.nodeSelector = nodeSelector; + } + + public void addNodeSelector(Map nodeSelector){ + if (CollectionUtils.isEmpty(nodeSelector)){ + return; + } + if (this.nodeSelector == null){ + this.nodeSelector = nodeSelector; + } + this.nodeSelector.putAll(nodeSelector); + } + + public List getEnv() { + return env; + } + + public void setEnv(List env) { + this.env = env; + } + + public List getVolumeMounts() { + return volumeMounts; + } + + public void setVolumeMounts(List volumeMounts) { + this.volumeMounts = volumeMounts; + } + + public List getVolumes() { + return volumes; + } + + public void setVolumes(List volumes) { + this.volumes = volumes; + } + + public List getTolerations() { + return tolerations; + } + + public void setTolerations(List tolerations) { + this.tolerations = tolerations; + } + + public void addTolerations(List tolerations){ + if (CollectionUtils.isEmpty(tolerations)){ + return ; + } + if (this.tolerations == null){ + this.tolerations = tolerations; + } + this.tolerations.addAll(tolerations); + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/dto/BaseK8sDeploymentCallbackCreateDTO.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/dto/BaseK8sDeploymentCallbackCreateDTO.java new file mode 100644 index 0000000..bc779c8 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/dto/BaseK8sDeploymentCallbackCreateDTO.java @@ -0,0 +1,82 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.dto; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; + +/** + * @descripton 统一通用参数实现与校验 + * @date 2020-11-26 + */ +@ApiModel(description = "k8s deployment异步回调基类") +@Data +public class BaseK8sDeploymentCallbackCreateDTO { + @ApiModelProperty(required = true, value = "k8s namespace") + @NotBlank(message = "namespace 不能为空!") + private String namespace; + + @ApiModelProperty(required = true, value = "k8s resource name") + @NotBlank(message = "resourceName 不能为空!") + private String resourceName; + + @ApiModelProperty(required = true, value = "k8s deployment name") + @NotBlank(message = "deployment 不能为空!") + private String deploymentName; + + /** + * deployment已 Running的pod数 + */ + @ApiModelProperty(required = true, value = "k8s deployment readyReplicas") + @NotNull(message = "readyReplicas 不能为空!") + private Integer readyReplicas; + + /** + * deployment总pod数 + */ + @ApiModelProperty(required = true, value = "k8s deployment replicas") + @NotNull(message = "replicas 不能为空!") + private Integer replicas; + + public BaseK8sDeploymentCallbackCreateDTO() { + + } + + public BaseK8sDeploymentCallbackCreateDTO(String namespace, String resourceName, String deploymentName, Integer readyReplicas, Integer replicas) { + this.namespace = namespace; + this.resourceName = resourceName; + this.deploymentName = deploymentName; + this.readyReplicas = readyReplicas; + this.replicas = replicas; + } + + @Override + public String toString() { + return "BaseK8sDeploymentCallbackCreateDTO{" + + "namespace='" + namespace + '\'' + + ", resourceName='" + resourceName + '\'' + + ", deploymentName='" + deploymentName + '\'' + + ", readyReplicas='" + readyReplicas + '\'' + + ", replicas='" + replicas + '\'' + + '}'; + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/dto/BaseK8sPodCallbackCreateDTO.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/dto/BaseK8sPodCallbackCreateDTO.java new file mode 100644 index 0000000..c283837 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/dto/BaseK8sPodCallbackCreateDTO.java @@ -0,0 +1,87 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.dto; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import javax.validation.constraints.NotEmpty; + +/** + * @descripton 统一通用参数实现与校验 + * @date 2020-05-28 + */ +@ApiModel(description = "k8s pod异步回调基类") +@Data +public class BaseK8sPodCallbackCreateDTO { + + @ApiModelProperty(required = true,value = "k8s namespace") + @NotEmpty(message = "namespace 不能为空!") + private String namespace; + + @ApiModelProperty(required = true,value = "k8s resource name") + @NotEmpty(message = "resourceName 不能为空!") + private String resourceName; + + @ApiModelProperty(required = true,value = "k8s pod name") + @NotEmpty(message = "podName 不能为空!") + private String podName; + + @ApiModelProperty(required = true,value = "k8s pod parent type") + @NotEmpty(message = "podParentType 不能为空!") + private String podParentType; + + @ApiModelProperty(required = true,value = "k8s pod parent name") + @NotEmpty(message = "podParentName 不能为空!") + private String podParentName; + + @ApiModelProperty(value = "k8s pod phase",notes = "对应PodPhaseEnum") + @NotEmpty(message = "phase 不能为空!") + private String phase; + + @ApiModelProperty(value = "k8s pod containerStatuses state") + private String messages; + + public BaseK8sPodCallbackCreateDTO(){ + + } + + public BaseK8sPodCallbackCreateDTO(String namespace, String resourceName, String podName, String podParentType, String podParentName, String phase, String messages){ + this.namespace = namespace; + this.resourceName = resourceName; + this.podName = podName; + this.podParentType = podParentType; + this.podParentName = podParentName; + this.phase = phase; + this.messages = messages; + } + + @Override + public String toString() { + return "BaseK8sPodCallbackReq{" + + "namespace='" + namespace + '\'' + + ", resourceName='" + resourceName + '\'' + + ", podName='" + podName + '\'' + + ", podParentType='" + podParentType + '\'' + + ", podParentName='" + podParentName + '\'' + + ", phase='" + phase + '\'' + + ", messages=" + messages + + '}'; + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/dto/NodeIsolationDTO.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/dto/NodeIsolationDTO.java new file mode 100644 index 0000000..d900724 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/dto/NodeIsolationDTO.java @@ -0,0 +1,40 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.dto; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import javax.validation.constraints.NotEmpty; +import java.util.List; + +/** + * @description k8s节点资源隔离DTO + * @date 2021-05-17 + */ +@Data +@Api("k8s节点资源隔离DTO") +public class NodeIsolationDTO { + @ApiModelProperty("节点名称列表") + @NotEmpty(message = "节点名称为空") + private List nodeNames; + + @ApiModelProperty("用户id") + private Long userId; +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/dto/PodLogDownloadQueryDTO.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/dto/PodLogDownloadQueryDTO.java new file mode 100644 index 0000000..cb2b895 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/dto/PodLogDownloadQueryDTO.java @@ -0,0 +1,47 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.dto; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import lombok.experimental.Accessors; +import org.dubhe.k8s.domain.vo.PodVO; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotEmpty; +import java.util.List; + +/** + * @description Pod日志 下载DTO + * @date 2020-08-21 + */ +@Data +@Accessors(chain = true) +@Api("Pod日志 下载DTO") +public class PodLogDownloadQueryDTO { + + @ApiModelProperty("k8s节点信息") + @NotEmpty(message = "k8s节点信息为空") + private List podVOList; + + @ApiModelProperty(value = "命名空间", required = true) + @NotBlank(message = "命名空间不能为空") + private String namespace; + +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/dto/PodLogQueryDTO.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/dto/PodLogQueryDTO.java new file mode 100644 index 0000000..52d8d2d --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/dto/PodLogQueryDTO.java @@ -0,0 +1,97 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.dto; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import lombok.experimental.Accessors; +import org.dubhe.biz.base.constant.MagicNumConstant; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; +import java.io.Serializable; + +/** + * @description Pod日志 查询DTO + * @date 2020-08-14 + */ +@Data +@Accessors(chain = true) +@Api("Pod日志 查询DTO") +public class PodLogQueryDTO implements Serializable { + + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "命名空间", required = true) + @NotBlank(message = "命名空间不能为空") + private String namespace; + + @ApiModelProperty("k8s实际pod名称") + @NotNull(message = "pod名称不能为空") + private String podName; + + @ApiModelProperty(value = "起始行") + private Integer startLine; + + @ApiModelProperty(value = "查询行数") + private Integer lines; + + @ApiModelProperty(value = "日志查询条件:关键字") + private String logKeyword; + + @ApiModelProperty(value = "日志查询时间范围:开始时间") + private Long beginTimeMillis; + + @ApiModelProperty(value = "日志查询时间范围:结束时间") + private Long endTimeMillis; + + public PodLogQueryDTO() { + + } + + public PodLogQueryDTO(String podName) { + this.podName = podName; + } + + /** + * 初始化获取起始行 + * @return + */ + @JsonIgnore + public int getQueryStart() { + if (startLine == null || startLine < MagicNumConstant.ONE) { + return MagicNumConstant.ONE; + } + return startLine; + } + + /** + * 初始化获取查询行数 + * @return + */ + @JsonIgnore + public int getQueryLines() { + if (lines == null || lines < MagicNumConstant.ONE || lines > MagicNumConstant.FOUR_THOUSAND) { + return MagicNumConstant.FOUR_THOUSAND; + } + return lines; + } + +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/dto/PodQueryDTO.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/dto/PodQueryDTO.java new file mode 100644 index 0000000..127fb6a --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/dto/PodQueryDTO.java @@ -0,0 +1,84 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.dto; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; +import org.dubhe.biz.base.constant.MagicNumConstant; + +import javax.validation.constraints.NotBlank; +import java.util.List; + +/** + * @description Pod基础信息查询入参 + * @date 2020-08-14 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@Accessors(chain = true) +@Api("Pod基础信息查询入参") +public class PodQueryDTO { + + @ApiModelProperty(value = "命名空间", required = true) + @NotBlank(message = "命名空间不能为空") + private String namespace; + + @ApiModelProperty(value = "资源名称", required = false) + private String resourceName; + + @ApiModelProperty(value = "pod名称列表", required = false) + private List podNames; + + @ApiModelProperty(value = "开始时间(unix时间戳/秒)", required = false) + private Long startTime; + + @ApiModelProperty(value = "结束时间(unix时间戳/秒)", required = false) + private Long endTime; + + @ApiModelProperty(value = "步长/秒", required = false) + private Integer step; + + /** + * 4小时秒数 + */ + private static final Long FOUR_HOUR_SECONDS = MagicNumConstant.SIXTY_LONG * MagicNumConstant.SIXTY_LONG * MagicNumConstant.FOUR; + + public PodQueryDTO(String namespace, String resourceName) { + this.namespace = namespace; + this.resourceName = resourceName; + } + + /** + * 未设置部分参数时生成默认参数 + */ + public void generateDefaultParam() { + if (startTime == null) { + startTime = System.currentTimeMillis() / MagicNumConstant.THOUSAND_LONG - FOUR_HOUR_SECONDS; + } + if (endTime == null) { + endTime = System.currentTimeMillis() / MagicNumConstant.THOUSAND_LONG; + } + if (step == null || step == 0) { + step = MagicNumConstant.TEN; + } + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/entity/K8sResource.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/entity/K8sResource.java new file mode 100644 index 0000000..4d70dbe --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/entity/K8sResource.java @@ -0,0 +1,65 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import org.dubhe.biz.db.entity.BaseEntity; + +/** + * @description k8s资源对象 + * @date 2020-07-10 + */ +@Data +@TableName("k8s_resource") +public class K8sResource extends BaseEntity { + @TableId(value = "id", type = IdType.AUTO) + @ApiModelProperty(hidden = true) + private Long id; + + @TableField(value = "kind") + private String kind; + + @TableField(value = "namespace") + private String namespace; + + @TableField(value = "name") + private String name; + + @TableField(value = "resource_name") + private String resourceName; + + @TableField(value = "env") + private String env; + + @TableField(value = "business") + private String business; + + public K8sResource(String kind,String namespace,String name,String resourceName,String env,String business){ + this.kind = kind; + this.namespace = namespace; + this.name = name; + this.resourceName = resourceName; + this.env = env; + this.business = business; + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/entity/K8sTask.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/entity/K8sTask.java new file mode 100644 index 0000000..e9d22ee --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/entity/K8sTask.java @@ -0,0 +1,110 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.entity; + +import com.alibaba.fastjson.JSON; +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.dubhe.biz.db.entity.BaseEntity; +import org.dubhe.k8s.domain.bo.TaskYamlBO; +import org.dubhe.k8s.enums.K8sTaskStatusEnum; +import org.dubhe.biz.base.utils.StringUtils; + +import java.sql.Timestamp; + +/** + * @description k8s任务对象 + * @date 2020-8-31 + */ +@Data +@AllArgsConstructor +@NoArgsConstructor +@TableName("k8s_task") +public class K8sTask extends BaseEntity{ + @TableId(value = "id", type = IdType.AUTO) + @ApiModelProperty(hidden = true) + private Long id; + + @TableField(value = "namespace") + private String namespace; + + @TableField(value = "resource_name") + private String resourceName; + + @TableField(value = "task_yaml") + private String taskYaml; + + @TableField(value = "business") + private String business; + + @TableField(value = "apply_unix_time") + private Long applyUnixTime; + + @TableField(value = "apply_display_time") + private Timestamp applyDisplayTime; + + @TableField(value = "apply_status") + private Integer applyStatus; + + @TableField(value = "stop_unix_time") + private Long stopUnixTime; + + @TableField(value = "stop_display_time") + private Timestamp stopDisplayTime; + + @TableField(value = "stop_status") + private Integer stopStatus; + + public TaskYamlBO getTaskYamlBO(){ + if (StringUtils.isEmpty(taskYaml)){ + return null; + } + return JSON.parseObject(taskYaml, TaskYamlBO.class); + } + + public void setTaskYamlBO(TaskYamlBO taskYamlBO){ + taskYaml = JSON.toJSONString(taskYamlBO); + } + + public boolean needCreate(Long time){ + boolean needCreate = applyUnixTime < time && K8sTaskStatusEnum.UNEXECUTED.getStatus().equals(applyStatus); + boolean needDelete = stopUnixTime < time && K8sTaskStatusEnum.UNEXECUTED.getStatus().equals(stopStatus); + return needCreate && (needCreate ^ needDelete); + } + + public boolean needDelete(Long time){ + boolean needCreate = applyUnixTime < time && K8sTaskStatusEnum.UNEXECUTED.getStatus().equals(applyStatus); + boolean needDelete = stopUnixTime < time && K8sTaskStatusEnum.UNEXECUTED.getStatus().equals(stopStatus); + return needDelete && (needCreate ^ needDelete); + } + + /** + * 判断任务是否已超时 + * @param time + * @return + */ + public boolean overtime(Long time){ + return applyUnixTime < time && K8sTaskStatusEnum.UNEXECUTED.getStatus().equals(applyStatus) && stopUnixTime < time && K8sTaskStatusEnum.UNEXECUTED.getStatus().equals(stopStatus); + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizContainer.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizContainer.java new file mode 100644 index 0000000..c7482ec --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizContainer.java @@ -0,0 +1,46 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.resource; + +import lombok.Data; +import lombok.experimental.Accessors; +import org.dubhe.k8s.annotation.K8sField; + +import java.util.List; +import java.util.Map; + +/** + * @description BizContainer对象 + * @date 2020-04-15 + */ +@Data +@Accessors(chain = true) +public class BizContainer { + @K8sField("image") + private String image; + @K8sField("imagePullPolicy") + private String imagePullPolicy; + @K8sField("name") + private String name; + @K8sField("volumeMounts") + private List volumeMounts; + @K8sField("resources:limits") + private Map limits; + @K8sField("resources:requests") + private Map requests; +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizContainerStateTerminated.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizContainerStateTerminated.java new file mode 100644 index 0000000..f3e6002 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizContainerStateTerminated.java @@ -0,0 +1,39 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.resource; + +import lombok.Data; +import lombok.experimental.Accessors; +import org.dubhe.k8s.annotation.K8sField; + +/** + * @description BizContainerStateTerminated实体类 + * @date 2020-06-02 + */ +@Data +@Accessors(chain = true) +public class BizContainerStateTerminated { + @K8sField("finishedAt") + private String finishedAt; + @K8sField("message") + private String message; + @K8sField("reason") + private String reason; + @K8sField("startedAt") + private String startedAt; +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizContainerStateWaiting.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizContainerStateWaiting.java new file mode 100644 index 0000000..347affd --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizContainerStateWaiting.java @@ -0,0 +1,35 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.resource; + +import lombok.Data; +import lombok.experimental.Accessors; +import org.dubhe.k8s.annotation.K8sField; + +/** + * @description BizContainerStateWaiting实体 + * @date 2020-06-02 + */ +@Data +@Accessors(chain = true) +public class BizContainerStateWaiting { + @K8sField("message") + private String message; + @K8sField("reason") + private String reason; +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizContainerStatus.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizContainerStatus.java new file mode 100644 index 0000000..8beaa63 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizContainerStatus.java @@ -0,0 +1,41 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.resource; + +import lombok.Data; +import lombok.experimental.Accessors; +import org.dubhe.k8s.annotation.K8sField; + +/** + * @description BizContainerStatus实体类 + * @date 2020-06-02 + */ +@Data +@Accessors(chain = true) +public class BizContainerStatus { + /** + * Details about a terminated container + */ + @K8sField("state:terminated") + private BizContainerStateTerminated terminated; + /** + * Details about a waiting container + */ + @K8sField("state:waiting") + private BizContainerStateWaiting waiting; +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizDeployment.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizDeployment.java new file mode 100644 index 0000000..d787aa1 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizDeployment.java @@ -0,0 +1,84 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.resource; + +import com.google.common.collect.Maps; +import lombok.Data; +import lombok.experimental.Accessors; +import org.dubhe.k8s.annotation.K8sField; +import org.dubhe.k8s.constant.K8sLabelConstants; +import org.dubhe.k8s.domain.PtBaseResult; + +import java.util.List; +import java.util.Map; + +/** + * @description Deployment 业务类 + * @date 2020-05-28 + */ +@Data +@Accessors(chain = true) +public class BizDeployment extends PtBaseResult { + @K8sField("apiVersion") + private String apiVersion; + @K8sField("kind") + private String kind; + + @K8sField("metadata:creationTimestamp") + private String creationTimestamp; + @K8sField("metadata:name") + private String name; + @K8sField("metadata:labels") + private Map labels = Maps.newHashMap(); + @K8sField("metadata:namespace") + private String namespace; + @K8sField("metadata:uid") + private String uid; + @K8sField("metadata:resourceVersion") + private String resourceVersion; + + @K8sField("spec:template:spec:containers") + private List containers; + + @K8sField("status:conditions") + private List conditions; + + @K8sField("status:replicas") + private Integer replicas; + + @K8sField("status:readyReplicas") + private Integer readyReplicas; + + /** + * 获取业务标签 + * @return + */ + public String getBusinessLabel() { + return labels.get(K8sLabelConstants.BASE_TAG_BUSINESS); + } + + /** + * 根据键获取label + * + * @param labelKey + * @return + */ + public String getLabel(String labelKey) { + return labels.get(labelKey); + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizDeploymentCondition.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizDeploymentCondition.java new file mode 100644 index 0000000..ecd320d --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizDeploymentCondition.java @@ -0,0 +1,41 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.resource; + +import lombok.Data; +import lombok.experimental.Accessors; +import org.dubhe.k8s.annotation.K8sField; + +/** + * @description BizDeploymentCondition实体类 + * @date 2020-05-28 + */ +@Data +@Accessors(chain = true) +public class BizDeploymentCondition { + @K8sField("lastTransitionTime") + private String lastTransitionTime; + @K8sField("message") + private java.lang.String message; + @K8sField("reason") + private java.lang.String reason; + @K8sField("status") + private String status; + @K8sField("type") + private String type; +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizDistributeTrain.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizDistributeTrain.java new file mode 100644 index 0000000..e3e6ca7 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizDistributeTrain.java @@ -0,0 +1,66 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.resource; + +import com.google.common.collect.Maps; +import io.fabric8.kubernetes.api.model.Volume; +import io.fabric8.kubernetes.api.model.VolumeMount; +import lombok.Data; +import lombok.experimental.Accessors; +import org.dubhe.k8s.annotation.K8sField; +import org.dubhe.k8s.domain.PtBaseResult; + +import java.util.List; +import java.util.Map; + +/** + * @description BizDistributeTrain实体类 + * @date 2020-07-08 + */ +@Data +@Accessors(chain = true) +public class BizDistributeTrain extends PtBaseResult { + @K8sField("apiVersion") + private String apiVersion; + @K8sField("kind") + private String kind; + @K8sField("metadata:name") + private String name; + @K8sField("metadata:labels") + private Map labels = Maps.newHashMap(); + @K8sField("metadata:namespace") + private String namespace; + @K8sField("spec:size") + private Integer size; + @K8sField("spec:image") + private String image; + @K8sField("spec:masterCmd") + private String masterCmd; + @K8sField("spec:masterResources") + private BizDistributeTrainResources masterResources; + @K8sField("spec:slaveCmd") + private String slaveCmd; + @K8sField("spec:slaveResources") + private BizDistributeTrainResources slaveResources; + @K8sField("spec:nodeSelector") + private Map nodeSelector = Maps.newHashMap(); + @K8sField("spec:volumeMounts") + private List volumeMounts; + @K8sField("spec:volumes") + private List volumes; +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizDistributeTrainContainer.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizDistributeTrainContainer.java new file mode 100644 index 0000000..6cef96f --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizDistributeTrainContainer.java @@ -0,0 +1,47 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.resource; + +import lombok.Data; +import lombok.experimental.Accessors; +import org.dubhe.k8s.annotation.K8sField; + +import java.util.ArrayList; +import java.util.List; + +/** + * @description BizDistributeTrainContainer实体类 + * @date 2020-07-08 + */ +@Data +@Accessors(chain = true) +public class BizDistributeTrainContainer { + @K8sField("name") + private String name; + @K8sField("image") + private String image; + @K8sField("imagePullPolicy") + private String imagePullPolicy; + @K8sField("volumeMounts") + private List volumeMounts; + @K8sField("command") + private List command = new ArrayList<>(); + @K8sField("args") + private List args = new ArrayList<>(); + +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizDistributeTrainResources.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizDistributeTrainResources.java new file mode 100644 index 0000000..2976805 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizDistributeTrainResources.java @@ -0,0 +1,35 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.resource; + +import lombok.Data; +import lombok.experimental.Accessors; +import org.dubhe.k8s.annotation.K8sField; + +import java.util.Map; + +/** + * @description BizDistributeTrainResources实体类 + * @date 2020-07-08 + */ +@Data +@Accessors(chain = true) +public class BizDistributeTrainResources { + @K8sField("limits") + private Map limits; +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizHTTPIngressPath.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizHTTPIngressPath.java new file mode 100644 index 0000000..7fe38b1 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizHTTPIngressPath.java @@ -0,0 +1,35 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.resource; + +import lombok.Data; +import lombok.experimental.Accessors; +import org.dubhe.k8s.annotation.K8sField; + +/** + * @description Kubernetes HTTPIngressPath + * @date 2020-09-17 + */ +@Data +@Accessors(chain = true) +public class BizHTTPIngressPath { + @K8sField("backend:serviceName") + private String serviceName; + @K8sField("backend:servicePort") + private BizIntOrString servicePort; +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizIngress.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizIngress.java new file mode 100644 index 0000000..92c7fd9 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizIngress.java @@ -0,0 +1,58 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.resource; + +import com.google.common.collect.Maps; +import lombok.Data; +import lombok.experimental.Accessors; +import org.dubhe.k8s.annotation.K8sField; + +import java.util.List; +import java.util.Map; + +/** + * @description Kubernetes Ingress + * @date 2020-09-09 + */ +@Data +@Accessors(chain = true) +public class BizIngress { + @K8sField("apiVersion") + private String apiVersion; + @K8sField("kind") + private String kind; + + @K8sField("metadata:creationTimestamp") + private String creationTimestamp; + @K8sField("metadata:name") + private String name; + @K8sField("metadata:labels") + private Map labels = Maps.newHashMap(); + @K8sField("metadata:namespace") + private String namespace; + @K8sField("metadata:uid") + private String uid; + @K8sField("metadata:resourceVersion") + private String resourceVersion; + + @K8sField("spec:rules") + private List rules; + + @K8sField("spec:tls") + private List tls; +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizIngressRule.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizIngressRule.java new file mode 100644 index 0000000..102ebc8 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizIngressRule.java @@ -0,0 +1,49 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.resource; + +import lombok.Data; +import lombok.experimental.Accessors; +import org.dubhe.k8s.annotation.K8sField; + +import java.util.List; + +/** + * @description Kubernetes IngressRule + * @date 2020-09-09 + */ +@Data +@Accessors(chain = true) +public class BizIngressRule { + @K8sField("host") + private String host; + @K8sField("http:paths") + private List paths; + + private String servicePort; + + /** + * 获取service 端口 + */ + public void takeServicePort(){ + if (paths == null || paths.size() == 0){ + return; + } + servicePort = paths.get(0).getServicePort().getStrVal() == null ? String.valueOf(paths.get(0).getServicePort().getIntVal()):paths.get(0).getServicePort().getStrVal(); + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizIngressTLS.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizIngressTLS.java new file mode 100644 index 0000000..e2247fa --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizIngressTLS.java @@ -0,0 +1,35 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.resource; + +import lombok.Data; +import lombok.experimental.Accessors; +import org.dubhe.k8s.annotation.K8sField; + +import java.util.List; + +/** + * @description Kubernetes IngressTLS + * @date 2020-09-10 + */ +@Data +@Accessors(chain = true) +public class BizIngressTLS { + @K8sField("hosts") + private List hosts; +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizIntOrString.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizIntOrString.java new file mode 100644 index 0000000..2403190 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizIntOrString.java @@ -0,0 +1,37 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.resource; + +import lombok.Data; +import lombok.experimental.Accessors; +import org.dubhe.k8s.annotation.K8sField; + +/** + * @description Kubernetes BizIntOrString + * @date 2020-09-17 + */ +@Data +@Accessors(chain = true) +public class BizIntOrString { + @K8sField("IntVal") + private Integer IntVal; + @K8sField("Kind") + private Integer Kind; + @K8sField("StrVal") + private String StrVal; +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizJob.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizJob.java new file mode 100644 index 0000000..8594333 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizJob.java @@ -0,0 +1,54 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.resource; + +import org.dubhe.k8s.annotation.K8sField; +import com.google.common.collect.Maps; +import lombok.Data; +import lombok.experimental.Accessors; +import org.dubhe.k8s.domain.PtBaseResult; + +import java.util.List; +import java.util.Map; + +/** + * @description BizJob实体类 + * @date 2020-04-22 + */ +@Data +@Accessors(chain = true) +public class BizJob extends PtBaseResult { + @K8sField("metadata:name") + private String name; + @K8sField("metadata:labels") + private Map labels = Maps.newHashMap(); + @K8sField("metadata:namespace") + private String namespace; + @K8sField("metadata:uid") + private String uid; + @K8sField("spec:template:spec:containers") + private List containers; + @K8sField("status:completionTime") + private String completionTime; + @K8sField("status:conditions") + private List conditions; + @K8sField("status:startTime") + private String startTime; + @K8sField("status:succeeded") + private Integer succeeded; +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizJobCondition.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizJobCondition.java new file mode 100644 index 0000000..48ed15a --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizJobCondition.java @@ -0,0 +1,45 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.resource; + +import org.dubhe.k8s.annotation.K8sField; +import lombok.Data; +import lombok.experimental.Accessors; + +/** + * @description BizJobCondition实体类 + * @date 2020-04-22 + */ +@Data +@Accessors(chain = true) +public class BizJobCondition { + @K8sField("lastProbeTime") + private String lastProbeTime; + @K8sField("lastTransitionTime") + private String lastTransitionTime; + @K8sField("status") + private String status; + /** + * PodScheduled:已将Pod调度到一个节点; + * Ready:该Pod能够处理请求,应将其添加到所有匹配服务的负载平衡池中; + * Initialized:所有初始化容器已成功启动; + * ContainersReady:容器中的所有容器均已准备就绪。 + */ + @K8sField("type") + private String type; +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizLimitRange.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizLimitRange.java new file mode 100644 index 0000000..e5a5ae7 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizLimitRange.java @@ -0,0 +1,52 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.resource; + +import org.dubhe.k8s.annotation.K8sField; +import org.dubhe.k8s.domain.PtBaseResult; +import lombok.Data; +import lombok.experimental.Accessors; + +import java.util.List; + +/** + * @description BizLimitRange实体类 + * @date 2020-04-23 + */ +@Data +@Accessors(chain = true) +public class BizLimitRange extends PtBaseResult { + @K8sField("apiVersion") + private String apiVersion; + @K8sField("kind") + private String kind; + + @K8sField("metadata:creationTimestamp") + private String creationTimestamp; + @K8sField("metadata:name") + private String name; + @K8sField("metadata:namespace") + private String namespace; + @K8sField("metadata:uid") + private String uid; + @K8sField("metadata:resourceVersion") + private String resourceVersion; + + @K8sField("spec:limits") + private List limits; +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizLimitRangeItem.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizLimitRangeItem.java new file mode 100644 index 0000000..3f10a9d --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizLimitRangeItem.java @@ -0,0 +1,46 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.resource; + +import org.dubhe.k8s.annotation.K8sField; +import org.dubhe.k8s.domain.PtBaseResult; +import lombok.Data; +import lombok.experimental.Accessors; + +import java.util.Map; + +/** + * @description BizLimitRangeItem实体类 + * @date 2020-04-23 + */ +@Data +@Accessors(chain = true) +public class BizLimitRangeItem extends PtBaseResult { + @K8sField("default") + Map _default; + @K8sField("defaultRequest") + Map defaultRequest; + @K8sField("max") + Map max; + @K8sField("maxLimitRequestRatio") + Map maxLimitRequestRatio; + @K8sField("min") + Map min; + @K8sField("type") + private String type = "Container"; +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizNamespace.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizNamespace.java new file mode 100644 index 0000000..41718d2 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizNamespace.java @@ -0,0 +1,53 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.resource; + +import org.dubhe.k8s.annotation.K8sField; +import org.dubhe.k8s.domain.PtBaseResult; +import com.google.common.collect.Maps; +import lombok.Data; +import lombok.experimental.Accessors; + +import java.util.Map; + +/** + * @description Namespace 业务类 + * @date 2020-04-23 + */ +@Data +@Accessors(chain = true) +public class BizNamespace extends PtBaseResult { + @K8sField("apiVersion") + private String apiVersion; + @K8sField("kind") + private String kind; + + @K8sField("metadata:creationTimestamp") + private String creationTimestamp; + @K8sField("metadata:labels") + private Map labels = Maps.newHashMap(); + @K8sField("metadata:name") + private String name; + @K8sField("metadata:uid") + private String uid; + @K8sField("metadata:resourceVersion") + private String resourceVersion; + + @K8sField("status:phase") + private String phase; +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizNode.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizNode.java new file mode 100644 index 0000000..e558db3 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizNode.java @@ -0,0 +1,111 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.resource; + +import cn.hutool.core.collection.CollectionUtil; +import org.dubhe.k8s.annotation.K8sField; +import org.dubhe.k8s.domain.PtBaseResult; +import com.google.common.collect.Maps; +import lombok.Data; +import lombok.experimental.Accessors; +import org.dubhe.k8s.constant.K8sParamConstants; +import org.dubhe.k8s.enums.NodeConditionTypeEnum; + +import java.util.List; +import java.util.Map; + +/** + * @description BizNode实体类 + * @date 2020-04-22 + */ +@Data +@Accessors(chain = true) +public class BizNode extends PtBaseResult { + @K8sField("apiVersion") + private String apiVersion; + @K8sField("kind") + private String kind; + + @K8sField("metadata:creationTimestamp") + private String creationTimestamp; + /** + * node的标签 + */ + @K8sField("metadata:labels") + private Map labels = Maps.newHashMap(); + /** + * node的名称 + */ + @K8sField("metadata:name") + private String name; + /** + * 唯一标识 + */ + @K8sField("metadata:uid") + private String uid; + @K8sField("metadata:resourceVersion") + private String resourceVersion; + /** + * 不可调度,为true时pod不会调度到此节点 + */ + @K8sField("spec:unschedulable") + private boolean unschedulable; + /** + * 污点 + */ + @K8sField("spec:taints") + private List taints; + + /** + * 节点可到达的地址列表,主机名和ip + */ + @K8sField("status:addresses") + private List addresses; + /** + * 可用于调度的节点资源 + */ + @K8sField("status:allocatable") + private Map allocatable; + /** + * 节点的总资源 + */ + @K8sField("status:capacity") + private Map capacity; + /** + * 当前的节点状态数组 + */ + @K8sField("status:conditions") + private List conditions; + /** + * 节点的一些信息 + */ + @K8sField("status:nodeInfo") + private BizNodeSystemInfo nodeInfo; + + /** + * 是否ready + */ + private Boolean ready; + + public BizNode setReady() { + if (CollectionUtil.isNotEmpty(conditions)) { + ready = conditions.stream().filter(obj -> NodeConditionTypeEnum.READY.getType().equals(obj.getType()) && K8sParamConstants.NODE_READY_TRUE.equals(obj.getStatus())).count() > 0; + } + return this; + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizNodeAddress.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizNodeAddress.java new file mode 100644 index 0000000..b44059b --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizNodeAddress.java @@ -0,0 +1,35 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.resource; + +import org.dubhe.k8s.annotation.K8sField; +import lombok.Data; +import lombok.experimental.Accessors; + +/** + * @description BizNodeAddress实体类 + * @date 2020-04-22 + */ +@Data +@Accessors(chain = true) +public class BizNodeAddress { + @K8sField("address") + private String address; + @K8sField("type") + private String type; +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizNodeCondition.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizNodeCondition.java new file mode 100644 index 0000000..defcf78 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizNodeCondition.java @@ -0,0 +1,65 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.resource; + +import org.dubhe.k8s.annotation.K8sField; +import lombok.Data; +import lombok.experimental.Accessors; + +/** + * @description BizNodeCondition实体类 + * @date 2020-04-22 + */ +@Data +@Accessors(chain = true) +public class BizNodeCondition { + /** + * 上次心跳时间 + */ + @K8sField("lastHeartbeatTime") + private String lastHeartbeatTime; + /** + * 上一次从一种状态转换为另一种状态的时间戳 + */ + @K8sField("lastTransitionTime") + private String lastTransitionTime; + /** + * 相关信息 + */ + @K8sField("message") + private String message; + /** + * 原因 + */ + @K8sField("reason") + private String reason; + /** + * True or False + */ + @K8sField("status") + private String status; + /** + * NetworkUnavailable:网络是否可用 + * MemoryPressure:内存压力 + * DiskPressure:磁盘压力 + * PIDPressure:PID压力 + * KubeletReady:node是否准备好 + */ + @K8sField("type") + private String type; +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizNodeSystemInfo.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizNodeSystemInfo.java new file mode 100644 index 0000000..ec67f19 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizNodeSystemInfo.java @@ -0,0 +1,51 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.resource; + +import org.dubhe.k8s.annotation.K8sField; +import lombok.Data; +import lombok.experimental.Accessors; + +/** + * @description BizNodeSystemInfo实体类 + * @date 2020-04-22 + */ +@Data +@Accessors(chain = true) +public class BizNodeSystemInfo { + @K8sField("architecture") + private String architecture; + @K8sField("bootID") + private String bootID; + @K8sField("containerRuntimeVersion") + private String containerRuntimeVersion; + @K8sField("kernelVersion") + private String kernelVersion; + @K8sField("kubeProxyVersion") + private String kubeProxyVersion; + @K8sField("kubeletVersion") + private String kubeletVersion; + @K8sField("machineID") + private String machineID; + @K8sField("operatingSystem") + private String operatingSystem; + @K8sField("osImage") + private String osImage; + @K8sField("systemUUID") + private String systemUUID; +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizPersistentVolumeClaim.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizPersistentVolumeClaim.java new file mode 100644 index 0000000..32cb16d --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizPersistentVolumeClaim.java @@ -0,0 +1,72 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.resource; + +import org.dubhe.k8s.annotation.K8sField; +import org.dubhe.k8s.domain.PtBaseResult; +import com.google.common.collect.Maps; +import lombok.Data; +import lombok.experimental.Accessors; + +import java.util.List; +import java.util.Map; + +/** + * @description BizPersistentVolumeClaim实体类 + * @date 2020-04-23 + */ +@Data +@Accessors(chain = true) +public class BizPersistentVolumeClaim extends PtBaseResult { + @K8sField("apiVersion") + private String apiVersion; + @K8sField("kind") + private String kind; + + @K8sField("metadata:creationTimestamp") + private String creationTimestamp; + @K8sField("metadata:labels") + private Map labels = Maps.newHashMap(); + @K8sField("metadata:name") + private String name; + @K8sField("metadata:namespace") + private String namespace; + @K8sField("metadata:uid") + private String uid; + @K8sField("metadata:resourceVersion") + private String resourceVersion; + + @K8sField("spec:accessModes") + private List accessModes; + @K8sField("spec:resources:limits") + private Map limits; + @K8sField("spec:resources:requests") + private Map requests; + @K8sField("spec:storageClassName") + private String storageClassName; + @K8sField("spec:volumeMode") + private String volumeMode; + + @K8sField("status:capacity") + private Map capacity; + @K8sField("status:conditions") + private List conditions; + @K8sField("status:phase") + private String phase; + +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizPersistentVolumeClaimCondition.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizPersistentVolumeClaimCondition.java new file mode 100644 index 0000000..a7b6ac3 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizPersistentVolumeClaimCondition.java @@ -0,0 +1,44 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.resource; + +import org.dubhe.k8s.annotation.K8sField; +import org.dubhe.k8s.domain.PtBaseResult; +import lombok.Data; +import lombok.experimental.Accessors; + +/** + * @description BizPersistentVolumeClaimCondition实体类 + * @date 2020-04-23 + */ +@Data +@Accessors(chain = true) +public class BizPersistentVolumeClaimCondition extends PtBaseResult { + @K8sField("lastProbeTime") + private String lastProbeTime; + @K8sField("lastTransitionTime") + private String lastTransitionTime; + @K8sField("message") + private String message; + @K8sField("reason") + private String reason; + @K8sField("status") + private String status; + @K8sField("type") + private String type; +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizPod.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizPod.java new file mode 100644 index 0000000..80bcbdd --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizPod.java @@ -0,0 +1,128 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.resource; + +import cn.hutool.core.util.StrUtil; +import org.dubhe.k8s.annotation.K8sField; +import org.dubhe.k8s.domain.PtBaseResult; +import com.google.common.collect.Maps; +import lombok.Data; +import lombok.experimental.Accessors; +import org.dubhe.k8s.constant.K8sLabelConstants; + +import java.util.List; +import java.util.Map; + + +/** + * @description 供业务层使用的k8s pod + * @date 2020-04-15 + */ +@Data +@Accessors(chain = true) +public class BizPod extends PtBaseResult { + private static final String CONTAINER_STATE_MESSAGE = "Pod {} {} reason : {}, message {} "; + + @K8sField("metadata:name") + private String name; + /** + * 创建此资源对象时间戳 + */ + @K8sField("metadata:creationTimestamp") + private String creationTimestamp; + @K8sField("metadata:labels") + private Map labels = Maps.newHashMap(); + @K8sField("metadata:namespace") + private String namespace; + @K8sField("metadata:uid") + private String uid; + @K8sField("spec:containers") + private List containers; + @K8sField("spec:nodeName") + private String nodeName; + @K8sField("status:podIP") + private String podIp; + @K8sField("spec:volumes") + private List volumes; + + /** + * Pending:待处理 + * Running:运行 + * Succeeded:pod中的所有container已成功终止,将不会重新启动 + * Failed:pod中的所有container均已终止,并且至少一个容器因故障而终止 + * Unknown:由于某种原因,无法获得Pod的状态 + */ + @K8sField("status:phase") + private String phase; + /** + * Kubelet确认时间,此时间戳生成在pull images之前 + */ + @K8sField("status:startTime") + private String startTime; + /** + * 状态变化时间戳 + */ + @K8sField("status:conditions") + private List conditions; + /** + * container 状态 + */ + @K8sField("status:containerStatuses") + private List containerStatuses; + + /** + * 训练结束时间 + */ + private String completedTime; + + public String getBusinessLabel() { + return labels.get(K8sLabelConstants.BASE_TAG_BUSINESS); + } + + /** + * 根据键获取label + * + * @param labelKey + * @return + */ + public String getLabel(String labelKey) { + return labels.get(labelKey); + } + + /** + * 拼接message + * + * @return + */ + public String getContainerStateMessages() { + StringBuilder messages = new StringBuilder(); + if (containerStatuses == null) { + return null; + } + containerStatuses.stream().map(obj -> { + if (obj.getTerminated() != null) { + messages.append(StrUtil.format(CONTAINER_STATE_MESSAGE, name, phase, obj.getTerminated().getReason(), obj.getTerminated().getMessage())); + } + if (obj.getWaiting() != null) { + messages.append(StrUtil.format(CONTAINER_STATE_MESSAGE, name, phase, obj.getWaiting().getReason(), obj.getWaiting().getMessage())); + } + return null; + }); + return messages.toString(); + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizPodCondition.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizPodCondition.java new file mode 100644 index 0000000..629422c --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizPodCondition.java @@ -0,0 +1,54 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.resource; + +import org.dubhe.k8s.annotation.K8sField; +import lombok.Data; +import lombok.experimental.Accessors; + +/** + * @description BizPodCondition实体类 + * @date 2020-04-22 + */ +@Data +@Accessors(chain = true) +public class BizPodCondition { + /** + * Pod上一次从一种状态转换为另一种状态的时间戳 + */ + @K8sField("lastTransitionTime") + private String lastTransitionTime; + /** + * Pod状态信息 + */ + @K8sField("message") + private String message; + /** + * True or False + */ + @K8sField("status") + private String status; + /** + * PodScheduled:已将Pod调度到一个节点; + * Ready:该Pod能够处理请求,应将其添加到所有匹配服务的负载平衡池中; + * Initialized:所有初始化容器已成功启动; + * ContainersReady:容器中的所有容器均已准备就绪。 + */ + @K8sField("type") + private String type; +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizPodMetrics.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizPodMetrics.java new file mode 100644 index 0000000..bd3e692 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizPodMetrics.java @@ -0,0 +1,61 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.resource; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import io.fabric8.kubernetes.api.model.Duration; +import io.fabric8.kubernetes.api.model.ObjectMeta; +import io.fabric8.kubernetes.api.model.metrics.v1beta1.ContainerMetrics; +import lombok.Data; +import lombok.experimental.Accessors; +import org.dubhe.k8s.annotation.K8sField; +import org.dubhe.k8s.enums.K8sKindEnum; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * @description BizPodMetrics实体类 + * @date 2020-05-22 + */ +@Data +@Accessors(chain = true) +public class BizPodMetrics { + @K8sField("apiVersion") + private java.lang.String apiVersion = "metrics.k8s.io/v1beta1"; + + @K8sField("containers") + private List containers = new ArrayList<>(); + + @K8sField("kind") + private String kind = K8sKindEnum.PODMETRICS.getKind(); + + @K8sField("metadata") + private ObjectMeta metadata; + + @K8sField("timestamp") + private String timestamp; + + @K8sField("window") + private Duration window; + + @JsonIgnore + private Map additionalProperties = new HashMap<>(0); +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizQuantity.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizQuantity.java new file mode 100644 index 0000000..5447d37 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizQuantity.java @@ -0,0 +1,61 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.resource; + +import lombok.Data; +import lombok.experimental.Accessors; +import org.dubhe.biz.base.utils.MathUtils; +import org.dubhe.k8s.annotation.K8sField; + +/** + * @description BizQuantity实体类 + * @date 2020-04-22 + */ +@Data +@Accessors(chain = true) +public class BizQuantity { + @K8sField("amount") + private String amount; + @K8sField("format") + private String format; + + public BizQuantity() { + + } + + public BizQuantity(String amount, String format) { + this.amount = amount; + this.format = format; + } + + public boolean isIllegal() { + return true; + } + + /** + * 单位相同时相减 + * @param bizQuantity 减数 + * @return + */ + public BizQuantity reduce(BizQuantity bizQuantity){ + if (bizQuantity == null || !bizQuantity.getFormat().equals(format)){ + return this; + } + return new BizQuantity(MathUtils.reduce(amount,bizQuantity.getAmount()),format); + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizResourceQuota.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizResourceQuota.java new file mode 100644 index 0000000..369fc60 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizResourceQuota.java @@ -0,0 +1,77 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.resource; + +import lombok.Data; +import lombok.experimental.Accessors; +import org.dubhe.k8s.annotation.K8sField; +import org.dubhe.k8s.domain.PtBaseResult; +import org.springframework.util.CollectionUtils; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * @description ResourceQuota 业务类 + * @date 2020-04-23 + */ +@Data +@Accessors(chain = true) +public class BizResourceQuota extends PtBaseResult { + @K8sField("apiVersion") + private String apiVersion; + @K8sField("kind") + private String kind; + + @K8sField("metadata:creationTimestamp") + private String creationTimestamp; + @K8sField("metadata:name") + private String name; + @K8sField("metadata:namespace") + private String namespace; + @K8sField("metadata:uid") + private String uid; + @K8sField("metadata:resourceVersion") + private String resourceVersion; + + @K8sField("status:hard") + private Map hard; + + @K8sField("status:used") + private Map used; + + @K8sField("spec:scopeSelector:matchExpressions") + private List matchExpressions; + + /** + * 获取余量 + * @return 余量列表 + */ + public Map getRemainder(){ + Map remainder = new HashMap<>(); + if (!CollectionUtils.isEmpty(hard)){ + for (Map.Entry entry : hard.entrySet()) { + if (used.get(entry.getKey()) != null){ + remainder.put(entry.getKey(),entry.getValue().reduce(used.get(entry.getKey()))); + } + } + } + return remainder; + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizScopedResourceSelectorRequirement.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizScopedResourceSelectorRequirement.java new file mode 100644 index 0000000..280371c --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizScopedResourceSelectorRequirement.java @@ -0,0 +1,49 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.resource; + +import org.dubhe.k8s.annotation.K8sField; +import lombok.Data; +import lombok.experimental.Accessors; + +import java.util.List; + +/** + * @description BizScopedResourceSelectorRequirement实体类 + * @date 2020-04-23 + */ +@Data +@Accessors(chain = true) +public class BizScopedResourceSelectorRequirement { + @K8sField("operator") + private String operator; + @K8sField("scopeName") + private String scopeName; + @K8sField("values") + private List values; + + public BizScopedResourceSelectorRequirement(){ + + } + + public BizScopedResourceSelectorRequirement(String operator, String scopeName, List values) { + this.operator = operator; + this.scopeName = scopeName; + this.values = values; + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizSecret.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizSecret.java new file mode 100644 index 0000000..054f51e --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizSecret.java @@ -0,0 +1,37 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.resource; + +import lombok.Data; +import lombok.experimental.Accessors; +import org.dubhe.k8s.annotation.K8sField; + +/** + * @description Kubernetes Secret + * @date 2020-09-09 + */ +@Data +@Accessors(chain = true) +public class BizSecret { + @K8sField("metadata:name") + private String name; + @K8sField("metadata:namespace") + private String namespace; + @K8sField("metadata:uid") + private String uid; +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizService.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizService.java new file mode 100644 index 0000000..c3a9c31 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizService.java @@ -0,0 +1,37 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.resource; + +import lombok.Data; +import lombok.experimental.Accessors; +import org.dubhe.k8s.annotation.K8sField; + +/** + * @description Kubernetes Service + * @date 2020-09-09 + */ +@Data +@Accessors(chain = true) +public class BizService { + @K8sField("metadata:name") + private String name; + @K8sField("metadata:namespace") + private String namespace; + @K8sField("metadata:uid") + private String uid; +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizTaint.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizTaint.java new file mode 100644 index 0000000..2b77f0f --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizTaint.java @@ -0,0 +1,39 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.resource; + +import lombok.Data; +import lombok.experimental.Accessors; +import org.dubhe.k8s.annotation.K8sField; + +/** + * @description BizTaint 实体类 + * @date 2020-11-20 + */ +@Data +@Accessors(chain = true) +public class BizTaint { + @K8sField("effect") + private String effect; + @K8sField("key") + private String key; + @K8sField("timeAdded") + private String timeAdded; + @K8sField("value") + private String value; +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizVolume.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizVolume.java new file mode 100644 index 0000000..aa9ca10 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizVolume.java @@ -0,0 +1,37 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.resource; + +import org.dubhe.k8s.annotation.K8sField; +import lombok.Data; +import lombok.experimental.Accessors; + +/** + * @description BizVolume实体类 + * @date 2020-04-15 + */ +@Data +@Accessors(chain = true) +public class BizVolume { + @K8sField("name") + private String name; + @K8sField("nfs:path") + private String path; + @K8sField("nfs:server") + private String server; +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizVolumeMount.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizVolumeMount.java new file mode 100644 index 0000000..37f27d7 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/resource/BizVolumeMount.java @@ -0,0 +1,37 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.resource; + +import org.dubhe.k8s.annotation.K8sField; +import lombok.Data; +import lombok.experimental.Accessors; + +/** + * @description BizVolumeMount实体类 + * @date 2020-04-15 + */ +@Data +@Accessors(chain = true) +public class BizVolumeMount { + @K8sField("mountPath") + private String mountPath; + @K8sField("name") + private String name; + @K8sField("readOnly") + private Boolean readOnly; +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/vo/GpuUsageVO.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/vo/GpuUsageVO.java new file mode 100644 index 0000000..2f3a2d7 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/vo/GpuUsageVO.java @@ -0,0 +1,38 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.vo; + +import lombok.AllArgsConstructor; +import lombok.Data; + +/** + * @description Gpu usage percent + * @date 2020-10-13 + */ +@Data +@AllArgsConstructor +public class GpuUsageVO { + /** + * 显卡id + */ + private String accId; + /** + * 使用率 百分比 + */ + Float usage; +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/vo/LogMonitoringVO.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/vo/LogMonitoringVO.java new file mode 100644 index 0000000..68ff8a4 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/vo/LogMonitoringVO.java @@ -0,0 +1,43 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.vo; + +import lombok.AllArgsConstructor; +import lombok.Data; +import org.dubhe.k8s.domain.PtBaseResult; +import java.util.List; + + +/** + * @description LogMonitoringVO对象 + * @date 2020-05-13 + */ +@Data +@AllArgsConstructor +public class LogMonitoringVO extends PtBaseResult { + private Long totalLogs; + private List logs; + + public LogMonitoringVO() { + + } + + public LogMonitoringVO(String code, String message){ + super(); + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/vo/MetricsDataResultVO.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/vo/MetricsDataResultVO.java new file mode 100644 index 0000000..0c8caa3 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/vo/MetricsDataResultVO.java @@ -0,0 +1,44 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.vo; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +import java.util.List; + +/** + * @description 监控指标 VO + * @date 2021-02-02 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@Accessors(chain = true) +public class MetricsDataResultVO { + /** + * 显卡编号 + */ + private String accId; + /** + * 监控指标值 + */ + List values; +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/vo/MetricsDataResultValueVO.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/vo/MetricsDataResultValueVO.java new file mode 100644 index 0000000..0ca580b --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/vo/MetricsDataResultValueVO.java @@ -0,0 +1,42 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.vo; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +/** + * @description 监控指标数据 VO + * @date 2021-02-02 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@Accessors(chain = true) +public class MetricsDataResultValueVO { + /** + * unix时间戳 + */ + private String time; + /** + * 值 + */ + private String value; +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/vo/ModelServingVO.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/vo/ModelServingVO.java new file mode 100644 index 0000000..d59fb24 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/vo/ModelServingVO.java @@ -0,0 +1,48 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.vo; + +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; +import org.dubhe.k8s.domain.PtBaseResult; +import org.dubhe.k8s.domain.resource.BizDeployment; +import org.dubhe.k8s.domain.resource.BizIngress; +import org.dubhe.k8s.domain.resource.BizSecret; +import org.dubhe.k8s.domain.resource.BizService; + +/** + * @description 模型部署VO + * @date 2020-09-09 + */ +@Data +@NoArgsConstructor +@Accessors(chain = true) +public class ModelServingVO extends PtBaseResult { + private BizSecret bizSecret; + private BizService bizService; + private BizDeployment bizDeployment; + private BizIngress bizIngress; + + public ModelServingVO(BizSecret bizSecret, BizService bizService, BizDeployment bizDeployment, BizIngress bizIngress){ + this.bizSecret = bizSecret; + this.bizService = bizService; + this.bizDeployment = bizDeployment; + this.bizIngress = bizIngress; + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/vo/PodLogQueryVO.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/vo/PodLogQueryVO.java new file mode 100644 index 0000000..82b02eb --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/vo/PodLogQueryVO.java @@ -0,0 +1,50 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.vo; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.experimental.Accessors; + +import java.util.List; + +/** + * @description Pod日志 查询响应VO + * @date 2020-08-14 + */ +@Data +@Accessors(chain = true) +@Api("Pod日志 查询响应VO") +@AllArgsConstructor +public class PodLogQueryVO { + + @ApiModelProperty("log内容") + private List content; + + @ApiModelProperty(value = "起始行") + private Integer startLine; + + @ApiModelProperty(value = "结束行") + private Integer endLine; + + @ApiModelProperty(value = "查询行数") + private Integer lines; + +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/vo/PodRangeMetricsVO.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/vo/PodRangeMetricsVO.java new file mode 100644 index 0000000..359fae7 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/vo/PodRangeMetricsVO.java @@ -0,0 +1,54 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.vo; + +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +import java.util.List; + +/** + * @description Pod历史监控指标 VO + * @date 2021-02-02 + */ +@Data +@NoArgsConstructor +@Accessors(chain = true) +public class PodRangeMetricsVO { + /** + * pod名称 + **/ + private String podName; + /** + * cpu 监控指标 value为使用百分比 + */ + List cpuMetrics; + /** + * gpu 监控指标 value为使用百分比 + */ + List gpuMetrics; + /** + * 内存 监控指标 value为占用内存 单位 Ki + */ + List memoryMetrics; + + public PodRangeMetricsVO(String podName){ + this.podName = podName; + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/vo/PodVO.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/vo/PodVO.java new file mode 100644 index 0000000..96fee79 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/vo/PodVO.java @@ -0,0 +1,41 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.vo; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Data; + +/** + * @description Pod信息展示类 + * @date 2020-08-14 + */ +@Data +@AllArgsConstructor +@ApiModel("Pod信息展示类") +public class PodVO { + + @ApiModelProperty("K8s中Pod的真实名称") + private String podName; + + @ApiModelProperty("Pod展示名称") + private String displayName; + + @ApiModelProperty(value = "命名空间") + private String namespace; +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/vo/PtContainerMetricsVO.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/vo/PtContainerMetricsVO.java new file mode 100644 index 0000000..750a39c --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/vo/PtContainerMetricsVO.java @@ -0,0 +1,98 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.vo; + +import lombok.Data; +import lombok.experimental.Accessors; + +import java.io.Serializable; + +/** + * @description metrics result + * @date 2020-05-22 + */ +@Data +@Accessors(chain = true) +public class PtContainerMetricsVO implements Serializable { + private static final long serialVersionUID = 1L; + /** + * pod名称 + **/ + private String podName; + /** + * container名称 + **/ + private String containerName; + /** + * 时间 + **/ + private String timestamp; + /** + * cpu用量 + **/ + private String cpuUsageAmount; + /** + * cpu用量 单位 1核=1000m,1m=1000000n + **/ + private String cpuUsageFormat; + /** + * 内存用量 + **/ + private String memoryUsageAmount; + /** + * 内存用量单位 + **/ + private String memoryUsageFormat; + /****/ + private String nodeName; + + public PtContainerMetricsVO(String podName, String containerName, String timestamp, String cpuUsageAmount, String cpuUsageFormat, String memoryUsageAmount, String memoryUsageFormat) { + this.podName = podName; + this.containerName = containerName; + this.timestamp = timestamp; + this.cpuUsageAmount = cpuUsageAmount; + this.cpuUsageFormat = cpuUsageFormat; + this.memoryUsageAmount = memoryUsageAmount; + this.memoryUsageFormat = memoryUsageFormat; + } + + public PtContainerMetricsVO(String podName, String cpuUsageAmount, String cpuUsageFormat, String memoryUsageAmount, String memoryUsageFormat) { + this.podName = podName; + this.cpuUsageAmount = cpuUsageAmount; + this.cpuUsageFormat = cpuUsageFormat; + this.memoryUsageAmount = memoryUsageAmount; + this.memoryUsageFormat = memoryUsageFormat; + } + + /** + * 增加 cpuUsageAmount + * @param cpuUsageAmount + */ + public void addCpuUsageAmount(String cpuUsageAmount){ + this.cpuUsageAmount = String.valueOf(Long.valueOf(this.cpuUsageAmount)+Long.valueOf(cpuUsageAmount)); + } + + /** + * 增加 memoryUsageAmount + * @param memoryUsageAmount + */ + public void addMemoryUsageAmount(String memoryUsageAmount){ + this.memoryUsageAmount = String.valueOf(Long.valueOf(this.memoryUsageAmount)+Long.valueOf(memoryUsageAmount)); + } + +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/vo/PtJupyterDeployVO.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/vo/PtJupyterDeployVO.java new file mode 100644 index 0000000..e71f522 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/vo/PtJupyterDeployVO.java @@ -0,0 +1,129 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.vo; + +import cn.hutool.core.codec.Base64; +import io.fabric8.kubernetes.api.model.Secret; +import io.fabric8.kubernetes.api.model.Service; +import io.fabric8.kubernetes.api.model.apps.StatefulSet; +import io.fabric8.kubernetes.api.model.extensions.HTTPIngressRuleValue; +import io.fabric8.kubernetes.api.model.extensions.Ingress; +import lombok.Data; +import lombok.experimental.Accessors; +import org.dubhe.biz.base.constant.SymbolConstant; +import org.dubhe.k8s.annotation.K8sField; +import org.dubhe.k8s.constant.K8sParamConstants; +import org.dubhe.k8s.domain.PtBaseResult; +import org.dubhe.k8s.domain.resource.BizContainer; +import org.dubhe.k8s.utils.MappingUtils; + +import java.util.List; +import java.util.Optional; + +/** + * @description Notebook deploy result + * @date 2020-04-17 + */ +@Data +@Accessors(chain = true) +public class PtJupyterDeployVO extends PtBaseResult { + + private String defaultJupyterPwd; + private String baseUrl; + private SecretInfo secretInfo; + private StatefulSetInfo statefulSetInfo; + private ServiceInfo serviceInfo; + private IngressInfo ingressInfo; + + public PtJupyterDeployVO() { + + } + + public PtJupyterDeployVO(Secret secret, StatefulSet statefulSet, Service service, Ingress ingress) { + Optional.ofNullable(secret).ifPresent(v -> { + String base64edPwd = v.getData().get(K8sParamConstants.SECRET_PWD_KEY); + String base64edBaseUrl = v.getData().get(K8sParamConstants.SECRET_URL_KEY); + this.defaultJupyterPwd = Base64.decodeStr(base64edPwd); + this.baseUrl = Base64.decodeStr(base64edBaseUrl) + SymbolConstant.SLASH; + this.secretInfo = MappingUtils.mappingTo(v, SecretInfo.class); + }); + Optional.ofNullable(statefulSet).ifPresent(v -> { + this.statefulSetInfo = MappingUtils.mappingTo(v, StatefulSetInfo.class); + }); + Optional.ofNullable(service).ifPresent(v -> { + this.serviceInfo = MappingUtils.mappingTo(v, ServiceInfo.class); + }); + Optional.ofNullable(ingress).ifPresent(v -> { + this.ingressInfo = MappingUtils.mappingTo(v, IngressInfo.class); + }); + } + + @Data + public static class SecretInfo { + @K8sField("metadata:name") + private String name; + @K8sField("metadata:namespace") + private String namespace; + @K8sField("metadata:uid") + private String uid; + } + + @Data + public static class StatefulSetInfo { + @K8sField("metadata:name") + private String name; + @K8sField("metadata:namespace") + private String namespace; + @K8sField("metadata:uid") + private String uid; + @K8sField("spec:template:metadata:uid") + private String podId; + @K8sField("spec:template:spec:containers") + private List containers; + } + + @Data + public static class ServiceInfo { + @K8sField("metadata:name") + private String name; + @K8sField("metadata:namespace") + private String namespace; + @K8sField("metadata:uid") + private String uid; + } + + @Data + public static class IngressInfo { + @K8sField("metadata:name") + private String name; + @K8sField("metadata:namespace") + private String namespace; + @K8sField("metadata:uid") + private String uid; + @K8sField("spec:rules") + private List rules; + } + + @Data + public static class BizIngressRule { + @K8sField("host") + private String host; + @K8sField("http") + private HTTPIngressRuleValue http; + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/vo/PtJupyterJobVO.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/vo/PtJupyterJobVO.java new file mode 100644 index 0000000..b6543fe --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/vo/PtJupyterJobVO.java @@ -0,0 +1,50 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.vo; + +import org.dubhe.k8s.annotation.K8sField; +import org.dubhe.k8s.domain.PtBaseResult; +import org.dubhe.k8s.domain.resource.BizContainer; +import org.dubhe.k8s.utils.MappingUtils; +import io.fabric8.kubernetes.api.model.batch.Job; +import lombok.Data; + +import java.util.List; + +/** + * @description job result + * @date 2020-04-22 + */ +@Data +public class PtJupyterJobVO extends PtBaseResult { + + @K8sField("metadata:name") + private String name; + @K8sField("metadata:namespace") + private String namespace; + @K8sField("metadata:uid") + private String uid; + @K8sField("spec:template:metadata:uid") + private String podId; + @K8sField("spec:template:spec:containers") + private List containers; + + public static PtJupyterJobVO getInstance(Job job) { + return MappingUtils.mappingTo(job, PtJupyterJobVO.class); + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/vo/PtNodeMetricsVO.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/vo/PtNodeMetricsVO.java new file mode 100644 index 0000000..c506c0e --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/vo/PtNodeMetricsVO.java @@ -0,0 +1,66 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.vo; + +import lombok.Data; +import lombok.experimental.Accessors; + +import java.io.Serializable; + +/** + * @description Node Metrics Result + * @date 2020-05-22 + */ +@Data +@Accessors(chain = true) +public class PtNodeMetricsVO implements Serializable { + private static final long serialVersionUID = 1L; + /** + * 节点名称 + **/ + private String nodeName; + /** + * 时间 + **/ + private String timestamp; + /** + * cpu用量 + **/ + private String cpuUsageAmount; + /** + * cpu用量 单位 1核=1000m,1m=1000000n + **/ + private String cpuUsageFormat; + /** + * 内存用量 + **/ + private String memoryUsageAmount; + /** + * 内存用量单位 + **/ + private String memoryUsageFormat; + + public PtNodeMetricsVO(String nodeName, String timestamp, String cpuUsageAmount, String cpuUsageFormat, String memoryUsageAmount, String memoryUsageFormat) { + this.nodeName = nodeName; + this.timestamp = timestamp; + this.cpuUsageAmount = cpuUsageAmount; + this.cpuUsageFormat = cpuUsageFormat; + this.memoryUsageAmount = memoryUsageAmount; + this.memoryUsageFormat = memoryUsageFormat; + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/vo/PtPodsVO.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/vo/PtPodsVO.java new file mode 100644 index 0000000..5c746f3 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/vo/PtPodsVO.java @@ -0,0 +1,151 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.vo; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.dubhe.biz.base.constant.MagicNumConstant; +import org.dubhe.biz.base.utils.MathUtils; +import org.dubhe.biz.base.utils.StringUtils; +import org.dubhe.k8s.utils.UnitConvertUtils; +import org.springframework.util.CollectionUtils; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +/** + * @description 封装pod信息 + * @date 2020-06-03 + */ +@Data +@AllArgsConstructor +@NoArgsConstructor +public class PtPodsVO implements Serializable { + private static final long serialVersionUID = 1L; + /** + * 命名空间 + */ + private String namespace; + /** + * pod名称 + **/ + private String podName; + /** + * cpu 申请量 + */ + private String cpuRequestAmount; + /** + * cpu用量 + **/ + private String cpuUsageAmount; + /** + * cpu 申请量 单位 1核=1000m,1m=1000000n + */ + private String cpuRequestFormat; + /** + * cpu用量 单位 1核=1000m,1m=1000000n + **/ + private String cpuUsageFormat; + /** + * cpu 使用百分比 + */ + private Float cpuUsagePercent; + /** + * 内存申请量 + */ + private String memoryRequestAmount; + /** + * 内存用量 + **/ + private String memoryUsageAmount; + /** + * 内存申请量单位 + **/ + private String memoryRequestFormat; + /** + * 内存用量单位 + **/ + private String memoryUsageFormat; + /** + * 内存使用百分比 + */ + private Float memoryUsagePercent; + /****/ + private String nodeName; + /** + * 设置status状态值 + **/ + private String status; + /** + * 设置gpu的使用情况 + **/ + private String gpuUsed; + /** + * gpu使用百分比 + */ + private List gpuUsagePersent; + + public PtPodsVO(String namespace,String podName,String cpuRequestAmount,String cpuUsageAmount,String cpuRequestFormat,String cpuUsageFormat,String memoryRequestAmount,String memoryUsageAmount,String memoryRequestFormat,String memoryUsageFormat,String nodeName,String status,String gpuUsed){ + this.namespace = namespace; + this.podName = podName; + this.cpuRequestAmount = cpuRequestAmount; + this.cpuUsageAmount = cpuUsageAmount; + this.cpuRequestFormat = cpuRequestFormat; + this.cpuUsageFormat = cpuUsageFormat; + this.memoryRequestAmount = memoryRequestAmount; + this.memoryUsageAmount = memoryUsageAmount; + this.memoryRequestFormat = memoryRequestFormat; + this.memoryUsageFormat = memoryUsageFormat; + this.nodeName = nodeName; + this.status = status; + this.gpuUsed = gpuUsed; + } + + public PtPodsVO(String namespace,String podName,String cpuUsageAmount,String cpuUsageFormat,String memoryUsageAmount,String memoryUsageFormat,String nodeName,String status,String gpuUsed){ + this.namespace = namespace; + this.podName = podName; + this.cpuUsageAmount = cpuUsageAmount; + this.cpuUsageFormat = cpuUsageFormat; + this.memoryUsageAmount = memoryUsageAmount; + this.memoryUsageFormat = memoryUsageFormat; + this.nodeName = nodeName; + this.status = status; + this.gpuUsed = gpuUsed; + } + + /** + * 计算资源使用百分比 + */ + public void calculationPercent(){ + if (StringUtils.isNotEmpty(cpuRequestAmount) && StringUtils.isNotEmpty(cpuUsageAmount)){ + cpuUsagePercent = MathUtils.floatDivision(UnitConvertUtils.cpuFormatToN(cpuUsageAmount,cpuUsageFormat).toString(),UnitConvertUtils.cpuFormatToN(cpuRequestAmount,cpuRequestFormat).toString(), MagicNumConstant.TWO) * MagicNumConstant.ONE_HUNDRED; + } + if (StringUtils.isNotEmpty(memoryRequestAmount) && StringUtils.isNotEmpty(memoryUsageAmount)){ + memoryUsagePercent = MathUtils.floatDivision(UnitConvertUtils.cpuFormatToN(memoryUsageAmount,memoryUsageFormat).toString(),UnitConvertUtils.cpuFormatToN(memoryRequestAmount,memoryRequestFormat).toString(), MagicNumConstant.TWO) * MagicNumConstant.ONE_HUNDRED; + } + } + + public void addGpuUsage(String accId,Float usage){ + if (CollectionUtils.isEmpty(gpuUsagePersent)){ + gpuUsagePersent = new ArrayList<>(); + } + gpuUsagePersent.add(new GpuUsageVO(accId,usage)); + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/vo/VolumeVO.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/vo/VolumeVO.java new file mode 100644 index 0000000..2aad091 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/domain/vo/VolumeVO.java @@ -0,0 +1,60 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.domain.vo; + +import io.fabric8.kubernetes.api.model.Volume; +import io.fabric8.kubernetes.api.model.VolumeMount; +import lombok.Data; +import lombok.experimental.Accessors; +import org.dubhe.k8s.domain.PtBaseResult; + +import java.util.ArrayList; +import java.util.List; + +/** + * @description 存储卷配置VO + * @date 2020-09-10 + */ +@Data +@Accessors(chain = true) +public class VolumeVO extends PtBaseResult { + private List volumeMounts; + private List volumes; + + /** + * 添加存储卷 + * @param volumeMount Kubernetes VolumeMount + */ + public void addVolumeMount(VolumeMount volumeMount){ + if (volumeMounts == null){ + volumeMounts = new ArrayList<>(); + } + volumeMounts.add(volumeMount); + } + + /** + * 添加存储卷 + * @param volume Kubernetes volume + */ + public void addVolume(Volume volume){ + if (volumes == null){ + volumes = new ArrayList<>(); + } + volumes.add(volume); + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/enums/AccessModeEnum.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/enums/AccessModeEnum.java new file mode 100644 index 0000000..c30002f --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/enums/AccessModeEnum.java @@ -0,0 +1,48 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.enums; + +/** + * @description AccessModes contains the desired access modes the volume should have + * @date 2020-06-19 + */ +public enum AccessModeEnum { + /** + * 单路读写 + */ + READ_WRITE_ONCE("ReadWriteOnce"), + /** + * 多路只读 + */ + READ_ONLY_MANY("ReadOnlyMany"), + /** + * 多路读写 + */ + READ_WRITE_MANY("ReadWriteMany"), + ; + + private String type; + + AccessModeEnum(String type) { + this.type = type; + } + + public String getType() { + return type; + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/enums/BusinessLabelServiceNameEnum.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/enums/BusinessLabelServiceNameEnum.java new file mode 100644 index 0000000..66c24d0 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/enums/BusinessLabelServiceNameEnum.java @@ -0,0 +1,90 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.enums; + +import org.dubhe.biz.base.constant.ApplicationNameConst; +import org.dubhe.biz.base.enums.BizEnum; +import org.dubhe.biz.base.utils.StringUtils; + +import static org.dubhe.biz.base.constant.SymbolConstant.BLANK; + +/** + * @description 业务标签->服务名 映射枚举类 + * @date 2020-12-8 + */ +public enum BusinessLabelServiceNameEnum { + /** + * 模型开发 + */ + NOTEBOOK(BizEnum.NOTEBOOK.getBizCode(), ApplicationNameConst.SERVER_NOTEBOOK), + /** + * 训练管理 + */ + TRAIN(BizEnum.ALGORITHM.getBizCode(), ApplicationNameConst.SERVER_TRAIN), + /** + * 模型优化 + */ + MODEL_OPTIMIZE(BizEnum.MODEL_OPT.getBizCode(), ApplicationNameConst.SERVER_OPTIMIZE), + /** + * 云端Serving + */ + SERVING(BizEnum.SERVING.getBizCode(), ApplicationNameConst.SERVER_SERVING), + /** + * 批量服务 + */ + BATCH_SERVING(BizEnum.BATCH_SERVING.getBizCode(), ApplicationNameConst.SERVER_SERVING), + ; + /** + * 业务标签 + */ + private String businessLabel; + /** + * 服务名 + */ + private String serviceName; + + public String getBusinessLabel() { + return businessLabel; + } + + public String getServiceName() { + return serviceName; + } + + BusinessLabelServiceNameEnum(String businessLabel, String serviceName) { + this.businessLabel = businessLabel; + this.serviceName = serviceName; + } + public static String getServiceNameByBusinessLabel(String businessLabel){ + for (BusinessLabelServiceNameEnum businessLabelServiceNameEnum : BusinessLabelServiceNameEnum.values()) { + if (StringUtils.equals(businessLabel, businessLabelServiceNameEnum.getBusinessLabel() )){ + return businessLabelServiceNameEnum.getServiceName(); + } + } + return BLANK; + } + + public static String getBusinessLabelByServiceName(String serviceName){ + for (BusinessLabelServiceNameEnum businessLabelServiceNameEnum : BusinessLabelServiceNameEnum.values()) { + if (StringUtils.equals(serviceName, businessLabelServiceNameEnum.getServiceName() )){ + return businessLabelServiceNameEnum.getBusinessLabel(); + } + } + return BLANK; + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/enums/GraphicsCardTypeEnum.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/enums/GraphicsCardTypeEnum.java new file mode 100644 index 0000000..bf6c11e --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/enums/GraphicsCardTypeEnum.java @@ -0,0 +1,50 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.enums; + +/** + * @description graphics card type enum + * @date 2020-05-09 + */ +public enum GraphicsCardTypeEnum { + /** + * 显卡型号 英伟达泰坦v + */ + TITAN_V("Titan V", "英伟达泰坦v"), + /** + * 显卡型号 特斯拉v100 + */ + TESLA_V100("Tesla V100", "特斯拉v100"); + + GraphicsCardTypeEnum(String type, String caption) { + this.type = type; + this.caption = caption; + } + + private String type; + private String caption; + + public String getType() { + return type; + } + + public String getCaption() { + return caption; + } + +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/enums/ImagePullPolicyEnum.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/enums/ImagePullPolicyEnum.java new file mode 100644 index 0000000..e2b3536 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/enums/ImagePullPolicyEnum.java @@ -0,0 +1,48 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.enums; + +/** + * @description 镜像拉取策略 + * @date 2020-07-01 + */ +public enum ImagePullPolicyEnum { + /** + * 默认值,本地有则使用本地镜像,不拉取 + */ + IFNOTPRESENT("IfNotPresent"), + /** + * 总是拉取 + */ + ALWAYS("Always"), + /** + * 只使用本地镜像,从不拉取 + */ + NEVER("Never"), + ; + + private String policy; + + ImagePullPolicyEnum(String policy) { + this.policy = policy; + } + + public String getPolicy(){ + return policy; + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/enums/K8sKindEnum.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/enums/K8sKindEnum.java new file mode 100644 index 0000000..8d057bd --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/enums/K8sKindEnum.java @@ -0,0 +1,76 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.enums; + +/** + * @description k8s资源类型枚举 + * @date 2020-07-01 + */ +public enum K8sKindEnum { + /** + * Job + */ + JOB("Job"), + /** + * Pod + */ + POD("Pod"), + /** + * Deployment + */ + DEPLOYMENT("Deployment"), + /** + * StatefulSet + */ + STATEFULSET("StatefulSet"), + /** + * DistributeTrain + */ + DISTRIBUTETRAIN("DistributeTrain"), + /** + * StorageClass + */ + STORAGECLASS("StorageClass"), + /** + * PersistentVolumeClaim + */ + PERSISTENTVOLUMECLAIM("PersistentVolumeClaim"), + /** + * Namespace + */ + NAMESPACE("Namespace"), + /** + * PodMetrics + */ + PODMETRICS("PodMetrics"), + /** + * 原生混合资源类型 + */ + MixedNativeResource("MixedNativeResource"), + ; + + private String kind; + + K8sKindEnum(String kind) { + this.kind = kind; + } + + public String getKind(){ + return kind; + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/enums/K8sResponseEnum.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/enums/K8sResponseEnum.java new file mode 100644 index 0000000..d340d43 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/enums/K8sResponseEnum.java @@ -0,0 +1,82 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.enums; + +import org.dubhe.k8s.domain.PtBaseResult; + +/** + * @description K8s response enum + * @date 2020-05-09 + */ +public enum K8sResponseEnum { + /** + * 成功 + */ + SUCCESS("200", ""), + + /** + * 没有对应的资源 + */ + NOT_FOUND("403", "请求的资源不存在"), + /** + * 创建,删除等操作的重复提交 + */ + REPEAT("404", "重复提交"), + /** + * 资源已存在 + */ + EXISTS("409", "资源已存在"), + /** + * 参数缺失 + */ + BAD_REQUEST("400", "参数缺失"), + /** + * 先决条件错误 + */ + PRECONDITION_FAILED("412", "先决条件错误"), + + /** + * k8s-client 内部错误 + */ + INTERNAL_SERVER_ERROR("500", "内部错误"), + /** + * 资源不足 + */ + LACK_OF_RESOURCES("516", "资源不足"), + ; + + K8sResponseEnum(String code, String message) { + this.code = code; + this.message = message; + } + + private String code; + private String message; + + public String getCode() { + return code; + } + + public String getMessage() { + return message; + } + + public PtBaseResult toPtBaseResult() { + return new PtBaseResult(this.code, this.message); + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/enums/K8sTaskStatusEnum.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/enums/K8sTaskStatusEnum.java new file mode 100644 index 0000000..9a61727 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/enums/K8sTaskStatusEnum.java @@ -0,0 +1,48 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.enums; + +/** + * @description k8s_task 状态枚举类 + * @date 2020-09-01 + */ +public enum K8sTaskStatusEnum { + /** + * 成功 + */ + NONE(0, "无需操作"), + UNEXECUTED(1, "待执行"), + EXECUTED(2, "已完成"), + ; + + private Integer status; + private String message; + K8sTaskStatusEnum(Integer status, String message) { + this.status = status; + this.message = message; + } + + + + public Integer getStatus() { + return status; + } + + public String getMessage() { + return message; + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/enums/K8sTolerationEffectEnum.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/enums/K8sTolerationEffectEnum.java new file mode 100644 index 0000000..0a161b5 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/enums/K8sTolerationEffectEnum.java @@ -0,0 +1,48 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.enums; + +/** + * @description k8s Toleration effect 枚举 + * @date 2021-05-17 + */ +public enum K8sTolerationEffectEnum { + /** + * NoSchedule + */ + NOSCHEDULE("NoSchedule"), + /** + * PreferNoSchedule + */ + PREFERNOSCHEDULE("PreferNoSchedule"), + /** + * NoExecute + */ + NOEXECUTE("NoExecute"), + ; + + private String effect; + + K8sTolerationEffectEnum(String effect) { + this.effect = effect; + } + + public String getEffect() { + return effect; + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/enums/K8sTolerationOperatorEnum.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/enums/K8sTolerationOperatorEnum.java new file mode 100644 index 0000000..262c00d --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/enums/K8sTolerationOperatorEnum.java @@ -0,0 +1,44 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.enums; + +/** + * @description k8s Toleration Operator 枚举 + * @date 2021-05-17 + */ +public enum K8sTolerationOperatorEnum { + /** + * Exists + */ + EXISTS("Exists"), + /** + * Equal + */ + EQUAL("Equal"), + ; + + private String operator; + + K8sTolerationOperatorEnum(String operator) { + this.operator = operator; + } + + public String getOperator() { + return operator; + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/enums/LackOfResourcesEnum.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/enums/LackOfResourcesEnum.java new file mode 100644 index 0000000..ddf3103 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/enums/LackOfResourcesEnum.java @@ -0,0 +1,62 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.enums; + +/** + * @description 资源缺乏枚举类 + * @date 2020-06-22 + */ +public enum LackOfResourcesEnum { + /** + * 资源充足 + */ + ADEQUATE(0, "资源充足"), + /** + * cpu不足 + */ + LACK_OF_CPU(1, "cpu不足"), + /** + * 内存不足 + */ + LACK_OF_MEM(2, "内存不足"), + /** + * gpu不足 + */ + LACK_OF_GPU(3, "gpu不足"), + /** + * 没有可调度节点 + */ + LACK_OF_NODE(4, "没有可调度节点"), + ; + + LackOfResourcesEnum(int code, String message) { + this.code = code; + this.message = message; + } + + private int code; + private String message; + + public int getCode() { + return code; + } + + public String getMessage() { + return message; + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/enums/LimitsOfResourcesEnum.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/enums/LimitsOfResourcesEnum.java new file mode 100644 index 0000000..f91f29f --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/enums/LimitsOfResourcesEnum.java @@ -0,0 +1,58 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.enums; + +/** + * @description 资源超限枚举类 + * @date 2021-04-14 + */ +public enum LimitsOfResourcesEnum { + /** + * 资源充足 + */ + ADEQUATE(0, "资源充足"), + /** + * cpu不足 + */ + LIMITS_OF_CPU(1, "cpu用量超限"), + /** + * 内存不足 + */ + LIMITS_OF_MEM(2, "内存用量超限"), + /** + * gpu不足 + */ + LIMITS_OF_GPU(3, "gpu用量超限"), + ; + + LimitsOfResourcesEnum(int code, String message) { + this.code = code; + this.message = message; + } + + private int code; + private String message; + + public int getCode() { + return code; + } + + public String getMessage() { + return message; + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/enums/NodeConditionTypeEnum.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/enums/NodeConditionTypeEnum.java new file mode 100644 index 0000000..eb09996 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/enums/NodeConditionTypeEnum.java @@ -0,0 +1,56 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.enums; + +/** + * @description node健康状态枚举类 + * @date 2020-05-25 + */ +public enum NodeConditionTypeEnum { + /** + * 网络是否可用 + */ + NETWORKUNAVAILABLE("NetworkUnavailable"), + /** + * 内存压力 + */ + MEMORYPRESSURE("MemoryPressure"), + /** + * 磁盘压力 + */ + DISKPRESSURE("DiskPressure"), + /** + * PID压力 + */ + PIDPRESSURE("PIDPressure"), + /** + * node是否准备好 + */ + READY("Ready"), + ; + + private String type; + + NodeConditionTypeEnum(String type) { + this.type = type; + } + + public String getType() { + return type; + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/enums/PodPhaseEnum.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/enums/PodPhaseEnum.java new file mode 100644 index 0000000..776c013 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/enums/PodPhaseEnum.java @@ -0,0 +1,61 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.enums; + +import lombok.Getter; + +/** + * @description pod状态 + * @date 2020-05-14 + */ +@Getter +public enum PodPhaseEnum { + + /** + * Pending + */ + PENDING("Pending"), + /** + * Running + */ + RUNNING("Running"), + /** + * Succeeded + */ + SUCCEEDED("Succeeded"), + /** + * Deleted + */ + DELETED("Deleted"), + /** + * Failed + */ + FAILED("Failed"), + /** + * Unknown + */ + UNKNOWN("Unknown"), + ; + + private String phase; + + PodPhaseEnum(String phase) { + this.phase = phase; + } + +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/enums/PvReclaimPolicyEnum.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/enums/PvReclaimPolicyEnum.java new file mode 100644 index 0000000..9261cc8 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/enums/PvReclaimPolicyEnum.java @@ -0,0 +1,48 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.enums; + +/** + * @description PV回收策略枚举 + * @date 2020-07-01 + */ +public enum PvReclaimPolicyEnum { + /** + * 删除PV时,删除数据,只有 NFS 和 HostPath 支持 + */ + RECYCLE("Recycle"), + /** + * 不清理, 保留 Volume(需要手动清理) + */ + RETAIN("Retain"), + /** + * 删除存储资源,比如删除 AWS EBS 卷(只有 AWS EBS, GCE PD, Azure Disk 和 Cinder 支持) + */ + DELETE("Delete"), + ; + + private String policy; + + PvReclaimPolicyEnum(String policy) { + this.policy = policy; + } + + public String getPolicy(){ + return policy; + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/enums/RestartPolicyEnum.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/enums/RestartPolicyEnum.java new file mode 100644 index 0000000..1d27f7c --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/enums/RestartPolicyEnum.java @@ -0,0 +1,48 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.enums; + +/** + * @description k8s pod restart policy enum + * @date 2020-05-29 + */ +public enum RestartPolicyEnum { + /** + * 当容器退出时,总是重启容器,默认策略 + */ + ALWAYS("Always"), + /** + * 当容器异常退出(退出状态码非0)时,重启容器 + */ + ONFAILURE("OnFailure"), + /** + * 当容器退出时,从不重启容器 + */ + NEVER("Never"), + ; + + private String restartPolicy; + + RestartPolicyEnum(String restartPolicy) { + this.restartPolicy = restartPolicy; + } + + public String getRestartPolicy() { + return restartPolicy; + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/enums/ShellCommandEnum.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/enums/ShellCommandEnum.java new file mode 100644 index 0000000..5ef19f8 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/enums/ShellCommandEnum.java @@ -0,0 +1,44 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.enums; + +/** + * @description command的shell类型枚举 + * @date 2020-07-01 + */ +public enum ShellCommandEnum { + /** + * /bin/bash + */ + BIN_BANSH("/bin/bash"), + /** + * + */ + BASH("bash"), + ; + + private String shell; + + ShellCommandEnum(String shell) { + this.shell = shell; + } + + public String getShell(){ + return shell; + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/enums/TopLogInfoEnum.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/enums/TopLogInfoEnum.java new file mode 100644 index 0000000..8f7eb6c --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/enums/TopLogInfoEnum.java @@ -0,0 +1,73 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.enums; + +import lombok.Getter; +import org.dubhe.biz.base.utils.StringUtils; + +/** + * @description TopLogInfoEnum枚举类 + * @date 2020-06-30 + */ +@Getter +public enum TopLogInfoEnum { + + /** + * Succeeded + */ + SUCCESSED("Succeeded","任务日志为空"), + /** + * Pending + */ + PENDING("Pending","No log or log file has expired"), + /** + * Running + */ + RUNNING("Running",""), + /** + * Failed + */ + FAILED("Failed","No log or log file has expired"), + /** + * Unknown + */ + UNKNOWN("Unknown","No log or log file has expired"), + /** + * NotExist + */ + NOT_EXIST("NotExist","No log or log file has expired") + + ; + private String status; + private String info; + + TopLogInfoEnum(String status,String info) { + this.status = status; + this.info = info; + } + + public static TopLogInfoEnum getTopLogInfoEnum(String status){ + for (TopLogInfoEnum topLogInfoEnum : TopLogInfoEnum.values()) { + if (StringUtils.equals(status,topLogInfoEnum.getStatus())){ + return topLogInfoEnum; + } + } + return NOT_EXIST; + + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/enums/ValidationTypeEnum.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/enums/ValidationTypeEnum.java new file mode 100644 index 0000000..477929d --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/enums/ValidationTypeEnum.java @@ -0,0 +1,29 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.enums; + +/** + * @description 字段校验类型 + * @date 2020-06-04 + */ +public enum ValidationTypeEnum { + /** + * k8s资源对象名称校验 + */ + K8S_RESOURCE_NAME +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/enums/WatcherActionEnum.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/enums/WatcherActionEnum.java new file mode 100644 index 0000000..2b634af --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/enums/WatcherActionEnum.java @@ -0,0 +1,63 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.enums; + +import org.dubhe.biz.base.utils.StringUtils; + +/** + * @description k8s event watcher action enum + * @date 2020-06-02 + */ +public enum WatcherActionEnum { + /** + * 添加 + */ + ADDED("ADDED"), + /** + * 修改 + */ + MODIFIED("MODIFIED"), + /** + * 删除 + */ + DELETED("DELETED"), + /** + * 错误 + */ + ERROR("ERROR"), + ; + + private String action; + + WatcherActionEnum(String action) { + this.action = action; + } + + public String getAction() { + return action; + } + + public static WatcherActionEnum get(String action) { + for (WatcherActionEnum watcherActionEnum : WatcherActionEnum.values()) { + if (StringUtils.equals(action, watcherActionEnum.getAction())) { + return watcherActionEnum; + } + } + return null; + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/interceptor/K8sCallBackPodInterceptor.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/interceptor/K8sCallBackPodInterceptor.java new file mode 100644 index 0000000..324fb8a --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/interceptor/K8sCallBackPodInterceptor.java @@ -0,0 +1,57 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.interceptor; + +import org.dubhe.biz.base.utils.StringUtils; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.dubhe.k8s.utils.K8sCallBackTool; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * @description k8s pod 异步回调拦截器 + * @date 2020-05-28 + */ +@Component +public class K8sCallBackPodInterceptor extends HandlerInterceptorAdapter { + + @Autowired + private K8sCallBackTool k8sCallBackTool; + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { + String uri = request.getRequestURI(); + LogUtil.debug(LogEnum.BIZ_K8S,"接收到k8s异步请求,URI:{}",uri); + String k8sCallbackToken = request.getHeader(K8sCallBackTool.K8S_CALLBACK_TOKEN); + if (StringUtils.isBlank(k8sCallbackToken)){ + LogUtil.warn(LogEnum.BIZ_K8S,"k8s异步回调没有配置【{}】,URI:{}",K8sCallBackTool.K8S_CALLBACK_TOKEN,uri); + return false; + } + boolean pass = k8sCallBackTool.validateToken(k8sCallbackToken); + if (!pass){ + LogUtil.warn(LogEnum.BIZ_K8S,"k8s异步回调token:【{}】 验证不通过,URI:{}",k8sCallbackToken,uri); + } + return pass; + } + +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/properties/ClusterProperties.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/properties/ClusterProperties.java new file mode 100644 index 0000000..a2b3385 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/properties/ClusterProperties.java @@ -0,0 +1,50 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.properties; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.core.io.Resource; + +/** + * @description k8s connection properties + * @date 2020-04-09 + */ +@Data +@ConfigurationProperties("k8s") +public class ClusterProperties { + + private String url; + + private String nfs; + + private String host; + + private String port; + + private String kubeconfig; + + /** + * 需使用Resource + */ + private Resource clientCrt; + + private Resource clientKey; + + private Resource caCrt; +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/service/DeploymentCallbackAsyncService.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/service/DeploymentCallbackAsyncService.java new file mode 100644 index 0000000..298a7bc --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/service/DeploymentCallbackAsyncService.java @@ -0,0 +1,35 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.service; + +import org.dubhe.k8s.domain.dto.BaseK8sDeploymentCallbackCreateDTO; +import org.springframework.scheduling.annotation.Async; + +/** + * @description deployment 异步回调 + * @date 2020-11-27 + */ +public interface DeploymentCallbackAsyncService { + + /** + * deployment 异步回调 + * @param k8sDeploymentCallbackCreateDTO + */ + @Async + void deploymentCallBack (R k8sDeploymentCallbackCreateDTO); +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/service/K8sResourceService.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/service/K8sResourceService.java new file mode 100644 index 0000000..7405207 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/service/K8sResourceService.java @@ -0,0 +1,83 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.service; + +import org.dubhe.k8s.domain.entity.K8sResource; +import org.dubhe.k8s.domain.resource.BizPod; + +import java.util.List; + +/** + * @description k8s资源服务接口 + * @date 2020-07-13 + */ +public interface K8sResourceService { + /** + * 根据pod插入 + * + * @param pod Pod对象 + * @return int 插入数量 + */ + int create(BizPod pod); + + /** + * 新增 + * + * @param k8sResource 对象 + * @return int 插入数量 + */ + int create(K8sResource k8sResource); + + /** + * 根据资源名查询 + * + * @param kind 资源类型 + * @param namespace 命名空间 + * @param resourceName 资源名称 + * @return List K8sResource资源集合 + */ + List selectByResourceName(String kind, String namespace, String resourceName); + + /** + * 根据对象名查询 + * + * @param kind 资源类型 + * @param namespace 命名空间 + * @param name 资源名称 + * @return List K8sResource资源集合 + */ + List selectByName(String kind, String namespace, String name); + + /** + * 根据resourceName删除 + * @param kind 资源类型 + * @param namespace 命名空间 + * @param resourceName 资源名称 + * @return int 删除数量 + */ + int deleteByResourceName(String kind,String namespace,String resourceName); + + /** + * 根据名称删除 + * @param kind + * @param namespace + * @param name 比如kind 是 pod那name就对应 podName + * @return int 删除数量 + */ + int deleteByName(String kind,String namespace,String name); +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/service/K8sTaskService.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/service/K8sTaskService.java new file mode 100644 index 0000000..5c56c7e --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/service/K8sTaskService.java @@ -0,0 +1,85 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.service; + +import org.dubhe.k8s.domain.bo.K8sTaskBO; +import org.dubhe.k8s.domain.entity.K8sTask; + +import java.util.List; + +/** + * @description k8s任务服务 + * @date 2020-08-31 + */ +public interface K8sTaskService { + /** + * 创建或者更新任务 + * + * @param k8sTask 对象 + * @return int 插入数量 + */ + int createOrUpdateTask(K8sTask k8sTask); + + /** + * 修改任务 + * @param k8sTask k8s任务 + * @return int 更新数量 + */ + int update(K8sTask k8sTask); + + /** + * 根据namesapce 和 resourceName 查询 + * @param k8sTask + * @return + */ + List selectByNamespaceAndResourceName(K8sTask k8sTask); + + /** + * 根据条件查询未执行的任务 + * @param k8sTaskBO k8s任务参数 + * @return List k8s任务类集合 + */ + List selectUnexecutedTask(K8sTaskBO k8sTaskBO); + + /** + * 查询未执行的任务 + * @return List k8s任务类集合 + */ + List selectUnexecutedTask(); + + /** + * 添加redis延时队列 + * @param k8sTask + * @return + */ + boolean addRedisDelayTask(K8sTask k8sTask); + + /** + * 加载任务到延时队列 + */ + void loadTaskToRedis(); + + /** + * 根据namespace 和 resourceName 删除 + * + * @param namespace 命名空间 + * @param resourceName 资源名称 + * @return boolean + */ + boolean deleteByNamespaceAndResourceName(String namespace,String resourceName); +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/service/PodCallbackAsyncService.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/service/PodCallbackAsyncService.java new file mode 100644 index 0000000..67171ea --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/service/PodCallbackAsyncService.java @@ -0,0 +1,35 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.service; + +import org.dubhe.k8s.domain.dto.BaseK8sPodCallbackCreateDTO; +import org.springframework.scheduling.annotation.Async; + +/** + * @description Pod 异步回调处理接口 + * @date 2020-05-28 + */ +public interface PodCallbackAsyncService { + + /** + * pod 异步回调 + * @param k8sPodCallbackCreateDTO + */ + @Async + void podCallBack (R k8sPodCallbackCreateDTO); +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/service/PodService.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/service/PodService.java new file mode 100644 index 0000000..2222b72 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/service/PodService.java @@ -0,0 +1,69 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.service; + +import org.dubhe.k8s.domain.dto.PodLogDownloadQueryDTO; +import org.dubhe.k8s.domain.dto.PodLogQueryDTO; +import org.dubhe.k8s.domain.dto.PodQueryDTO; +import org.dubhe.k8s.domain.vo.PodLogQueryVO; +import org.dubhe.k8s.domain.vo.PodVO; + +import javax.servlet.http.HttpServletResponse; +import java.util.List; +import java.util.Map; + +/** + * @description Pod业务接口 + * @date 2020-08-14 + */ +public interface PodService { + + /** + * 查询Pod信息 + * @param podQueryDTO pod查询条件对象 + * @return List pod对象集合 + */ + List getPods(PodQueryDTO podQueryDTO); + + /** + * 按Pod名称分页查询Pod日志 + * @param podLogQueryDTO pod日志查询条件对象 + * @return PodLogQueryVO Pod日志 + */ + PodLogQueryVO getPodLog(PodLogQueryDTO podLogQueryDTO); + + /** + * 获取单pod日志字符串 + * @param podLogQueryDTO pod日志查询条件对象 + * @return String Pod日志 + */ + String getPodLogStr(PodLogQueryDTO podLogQueryDTO); + + /** + * 按Pod名称下载日志 + * @param podLogDownloadQueryDTO pod日志下载查询对象 + * @param response 响应 + */ + void downLoadPodLog(PodLogDownloadQueryDTO podLogDownloadQueryDTO, HttpServletResponse response); + + /** + * 统计Pod日志数量 + * @param podLogDownloadQueryDTO 日志下载查询对象 + * @return Map String:Pod name,Long: Pod count + */ + Map getLogCount(PodLogDownloadQueryDTO podLogDownloadQueryDTO); +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/service/impl/K8sResourceServiceImpl.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/service/impl/K8sResourceServiceImpl.java new file mode 100644 index 0000000..b9511c0 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/service/impl/K8sResourceServiceImpl.java @@ -0,0 +1,163 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.service.impl; + +import cn.hutool.core.collection.CollectionUtil; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; +import org.dubhe.biz.base.utils.SpringContextHolder; +import org.dubhe.biz.base.utils.StringUtils; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.dubhe.k8s.constant.K8sLabelConstants; +import org.dubhe.k8s.dao.K8sResourceMapper; +import org.dubhe.k8s.domain.entity.K8sResource; +import org.dubhe.k8s.domain.resource.BizPod; +import org.dubhe.k8s.enums.K8sKindEnum; +import org.dubhe.k8s.service.K8sResourceService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.List; + +/** + * @description k8s资源服务实现类 + * @date 2020-07-13 + */ +@Service +public class K8sResourceServiceImpl implements K8sResourceService { + @Autowired + private K8sResourceMapper k8sResourceMapper; + + /** + * 根据pod插入 + * + * @param pod Pod对象 + * @return int 插入数量 + */ + @Override + public int create(BizPod pod) { + return create(new K8sResource(K8sKindEnum.POD.getKind(),pod.getNamespace(),pod.getName(),pod.getLabel(K8sLabelConstants.BASE_TAG_SOURCE), SpringContextHolder.getActiveProfile(),pod.getBusinessLabel())); + } + + /** + * 插入 + * + * @param k8sResource + * @return int 插入数量 + */ + @Override + public int create(K8sResource k8sResource) { + if (null == k8sResource){ + return 0; + } + QueryWrapper queryK8sResourceJonWrapper = new QueryWrapper<>(k8sResource); + List list = k8sResourceMapper.selectList(queryK8sResourceJonWrapper); + if (CollectionUtil.isEmpty(list)){ + LogUtil.info(LogEnum.BIZ_K8S,"insert k8sResource:{}",k8sResource); + return k8sResourceMapper.insert(k8sResource); + }else { + LogUtil.warn(LogEnum.BIZ_K8S,"k8sResource already exist:{}",k8sResource); + return 0; + } + } + + /** + * 根据资源名查询 + * + * @param kind 资源类型 + * @param namespace 命名空间 + * @param resourceName 资源名称 + * @return List K8sResource集合 + */ + @Override + public List selectByResourceName(String kind, String namespace, String resourceName) { + if (StringUtils.isEmpty(kind) || StringUtils.isEmpty(namespace) || StringUtils.isEmpty(resourceName)) { + return new ArrayList<>(0); + } + QueryWrapper queryK8sResourceJonWrapper = new QueryWrapper<>(); + queryK8sResourceJonWrapper.eq("kind", kind) + .eq("namespace", namespace) + .eq("resource_name", resourceName) + .eq("env", SpringContextHolder.getActiveProfile()) + .eq("deleted", 0) + .orderByDesc("create_time"); + return k8sResourceMapper.selectList(queryK8sResourceJonWrapper); + } + + /** + * 根据对象名查询 + * + * @param kind 资源名称 + * @param namespace 命名空间 + * @param name 资源名字 + * @return List K8sResource集合 + */ + @Override + public List selectByName(String kind, String namespace, String name) { + if (StringUtils.isEmpty(kind) || StringUtils.isEmpty(namespace) || StringUtils.isEmpty(name)) { + return new ArrayList<>(0); + } + QueryWrapper queryK8sResourceJonWrapper = new QueryWrapper<>(); + queryK8sResourceJonWrapper.eq("kind", kind) + .eq("namespace", namespace) + .eq("name", name) + .eq("env", SpringContextHolder.getActiveProfile()) + .eq("deleted", 0) + .orderByDesc("create_time"); + return k8sResourceMapper.selectList(queryK8sResourceJonWrapper); + } + + /** + * 根据resourceName删除 + * @param kind 资源类型 + * @param namespace 命名空间 + * @param resourceName 资源名称 + * @return int 删除数量 + */ + @Override + public int deleteByResourceName(String kind, String namespace, String resourceName) { + if (StringUtils.isEmpty(kind) || StringUtils.isEmpty(namespace) || StringUtils.isEmpty(resourceName)) { + return 0; + } + UpdateWrapper updateK8sResourceJonWrapper = new UpdateWrapper<>(); + updateK8sResourceJonWrapper.eq("kind", kind) + .eq("namespace", namespace) + .eq("resource_name", resourceName) + .eq("env", SpringContextHolder.getActiveProfile()) + .eq("deleted", 0).set("deleted", 1); + + return k8sResourceMapper.update(null,updateK8sResourceJonWrapper); + } + + @Override + public int deleteByName(String kind, String namespace, String name) { + if (StringUtils.isEmpty(kind) || StringUtils.isEmpty(namespace) || StringUtils.isEmpty(name)) { + return 0; + } + UpdateWrapper updateK8sResourceJonWrapper = new UpdateWrapper<>(); + updateK8sResourceJonWrapper.eq("kind", kind) + .eq("namespace", namespace) + .eq("name", name) + .eq("env", SpringContextHolder.getActiveProfile()) + .eq("deleted", 0).set("deleted", 1); + + return k8sResourceMapper.update(null,updateK8sResourceJonWrapper); + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/service/impl/K8sTaskServiceImpl.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/service/impl/K8sTaskServiceImpl.java new file mode 100644 index 0000000..786c9d6 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/service/impl/K8sTaskServiceImpl.java @@ -0,0 +1,179 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.service.impl; + +import com.alibaba.fastjson.JSON; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import org.dubhe.biz.base.constant.MagicNumConstant; +import org.dubhe.biz.base.utils.StringUtils; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.dubhe.biz.redis.utils.RedisUtils; +import org.dubhe.k8s.constant.RedisConstants; +import org.dubhe.k8s.dao.K8sTaskMapper; +import org.dubhe.k8s.domain.bo.K8sTaskBO; +import org.dubhe.k8s.domain.entity.K8sTask; +import org.dubhe.k8s.enums.K8sTaskStatusEnum; +import org.dubhe.k8s.service.K8sTaskService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.util.CollectionUtils; + +import java.util.ArrayList; +import java.util.List; + +/** + * @description k8s任务服务实现类 + * @date 2020-08-31 + */ +@Service +public class K8sTaskServiceImpl implements K8sTaskService { + + @Autowired + K8sTaskMapper k8sTaskMapper; + @Autowired + private RedisUtils redisUtils; + /** + * 创建或者更新任务 + * + * @param k8sTask 对象 + * @return int 插入数量 + */ + @Override + public int createOrUpdateTask(K8sTask k8sTask) { + if (k8sTask == null){ + return 0; + } + List oldK8sTaskList = selectByNamespaceAndResourceName(k8sTask); + if (CollectionUtils.isEmpty(oldK8sTaskList)){ + addRedisDelayTask(k8sTask); + return k8sTaskMapper.insertOrUpdate(k8sTask); + }else { + k8sTask.setId(oldK8sTaskList.get(0).getId()); + k8sTask.setDeleted(false); + addRedisDelayTask(k8sTask); + return update(k8sTask); + } + } + /** + * 修改任务 + * @param k8sTask k8s任务 + * @return int 更新数量 + */ + @Override + public int update(K8sTask k8sTask) { + if (k8sTask == null){ + return 0; + } + addRedisDelayTask(k8sTask); + if (k8sTask.getId() != null){ + return k8sTaskMapper.updateById(k8sTask); + } + List oldK8sTaskList = selectByNamespaceAndResourceName(k8sTask); + if (!CollectionUtils.isEmpty(oldK8sTaskList)){ + k8sTask.setId(oldK8sTaskList.get(0).getId()); + k8sTask.setDeleted(false); + return k8sTaskMapper.updateById(k8sTask); + } + return 0; + } + + /** + * 根据namesapce 和 resourceName 查询 + * @param k8sTask + * @return + */ + @Override + public List selectByNamespaceAndResourceName(K8sTask k8sTask){ + if (k8sTask == null || StringUtils.isEmpty(k8sTask.getNamespace()) || StringUtils.isEmpty(k8sTask.getResourceName())){ + return null; + } + LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(); + queryWrapper.eq(K8sTask::getNamespace,k8sTask.getNamespace()); + queryWrapper.eq(K8sTask::getResourceName,k8sTask.getResourceName()); + + return k8sTaskMapper.selectList(queryWrapper); + } + + /** + * 查询 + * @param k8sTaskBO k8s任务参数 + * @return List k8s任务类集合 + */ + @Override + public List selectUnexecutedTask(K8sTaskBO k8sTaskBO) { + if (k8sTaskBO == null){ + return new ArrayList<>(); + } + return k8sTaskMapper.selectUnexecutedTask(k8sTaskBO); + } + + @Override + public List selectUnexecutedTask() { + K8sTaskBO k8sTaskBO = new K8sTaskBO(); + Long curUnixTime = System.currentTimeMillis()/ MagicNumConstant.ONE_THOUSAND; + k8sTaskBO.setMaxApplyUnixTime(curUnixTime); + k8sTaskBO.setMaxStopUnixTime(curUnixTime); + k8sTaskBO.setApplyStatus(K8sTaskStatusEnum.UNEXECUTED.getStatus()); + k8sTaskBO.setStopStatus(K8sTaskStatusEnum.UNEXECUTED.getStatus()); + LogUtil.info(LogEnum.BIZ_K8S,"selectUnexecutedTask {}", JSON.toJSONString(k8sTaskBO)); + return selectUnexecutedTask(k8sTaskBO); + } + + /** + * 添加redis延时队列 + * @param k8sTask + * @return + */ + @Override + public boolean addRedisDelayTask(K8sTask k8sTask) { + if (k8sTask == null || StringUtils.isEmpty(k8sTask.getNamespace()) || StringUtils.isEmpty(k8sTask.getResourceName())){ + return false; + } + boolean success = true; + if (k8sTask.getApplyUnixTime() != null && k8sTask.getApplyUnixTime() > 0){ + success &= redisUtils.zAdd(RedisConstants.DELAY_APPLY_ZSET_KEY,k8sTask.getApplyUnixTime(), String.format(RedisConstants.DELAY_ZSET_VALUE,k8sTask.getNamespace(),k8sTask.getResourceName())); + } + if (k8sTask.getStopUnixTime() != null && k8sTask.getStopUnixTime() > 0){ + success &= redisUtils.zAdd(RedisConstants.DELAY_STOP_ZSET_KEY,k8sTask.getStopUnixTime(),String.format(RedisConstants.DELAY_ZSET_VALUE,k8sTask.getNamespace(),k8sTask.getResourceName())); + } + return success; + } + + /** + * 加载任务到延时队列 + */ + @Override + public void loadTaskToRedis(){ + selectUnexecutedTask().forEach(x->addRedisDelayTask(x)); + } + + /** + * 根据namespace 和 resourceName 删除 + * + * @param namespace 命名空间 + * @param resourceName 资源名称 + * @return boolean + */ + @Override + public boolean deleteByNamespaceAndResourceName(String namespace, String resourceName) { + if (StringUtils.isEmpty(namespace) || StringUtils.isEmpty(resourceName)){ + return false; + } + return k8sTaskMapper.deleteByNamespaceAndResourceName(namespace,resourceName,true) > 0 ? true: false; + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/service/impl/PodServiceImpl.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/service/impl/PodServiceImpl.java new file mode 100644 index 0000000..602d0f6 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/service/impl/PodServiceImpl.java @@ -0,0 +1,277 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.service.impl; + +import cn.hutool.core.collection.CollectionUtil; +import cn.hutool.core.date.DatePattern; +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.util.RandomUtil; +import cn.hutool.core.util.StrUtil; +import org.dubhe.biz.base.context.UserContext; +import org.dubhe.biz.base.service.UserContextService; +import org.dubhe.biz.file.api.FileStoreApi; +import org.dubhe.biz.permission.base.BaseService; +import org.dubhe.k8s.api.LogMonitoringApi; +import org.dubhe.k8s.cache.ResourceCache; +import org.dubhe.k8s.domain.bo.LogMonitoringBO; +import org.dubhe.k8s.domain.dto.PodLogDownloadQueryDTO; +import org.dubhe.k8s.domain.dto.PodLogQueryDTO; +import org.dubhe.k8s.domain.dto.PodQueryDTO; +import org.dubhe.k8s.domain.vo.LogMonitoringVO; +import org.dubhe.k8s.domain.vo.PodLogQueryVO; +import org.dubhe.k8s.domain.vo.PodVO; +import org.dubhe.k8s.service.PodService; +import org.dubhe.k8s.utils.K8sNameTool; +import org.dubhe.k8s.utils.PodUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.util.CollectionUtils; + +import javax.annotation.Resource; +import javax.servlet.http.HttpServletResponse; +import java.io.File; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * @description Pod业务接口 + * @date 2020-08-14 + */ +@Service +public class PodServiceImpl implements PodService { + + @Autowired + private ResourceCache resourceCache; + + @Autowired + private K8sNameTool k8sNameTool; + + @Autowired + private LogMonitoringApi logMonitoringApi; + + @Autowired + private UserContextService userContextService; + + @Resource(name = "hostFileStoreApiImpl") + private FileStoreApi fileStoreApi; + + /** + * 查询Pod信息 + * @param podQueryDTO + * @return List Pod信息 + */ + @Override + public List getPods(PodQueryDTO podQueryDTO) { + //获取用户信息 + UserContext user = userContextService.getCurUser(); + String namespace = podQueryDTO.getNamespace(); + if (!BaseService.isAdmin(user)) { + checkNamespace(namespace, user.getId()); + } + List podVOList = new ArrayList<>(); + Set podSet = resourceCache.getPodNameByResourceName(namespace, podQueryDTO.getResourceName()); + if (CollectionUtils.isEmpty(podSet)) { + return podVOList; + } + List podList = new ArrayList<>(podSet); + Collections.sort(podList); + int masterIndex = 1; + int slaveIndex = 1; + int podIndex = 1; + + for (String pod : podList) { + if (PodUtil.isMaster(pod)) { + podVOList.add(new PodVO(pod, "Master" + (masterIndex++), namespace)); + } else if (PodUtil.isSlave(pod)) { + podVOList.add(new PodVO(pod, "Slave" + (slaveIndex++), namespace)); + } else { + podVOList.add(new PodVO(pod, "Pod" + (podIndex++), namespace)); + } + } + Collections.sort(podVOList, Comparator.comparing(PodVO::getDisplayName)); + return podVOList; + } + + /** + * 按Pod名称分页查询Pod日志 + * @param podLogQueryDTO pod日志查询条件实体类 + * @return PodLogQueryVO Pod日志 + */ + @Override + public PodLogQueryVO getPodLog(PodLogQueryDTO podLogQueryDTO) { + //获取用户信息 + UserContext user = userContextService.getCurUser(); + String namespace = podLogQueryDTO.getNamespace(); + if (!BaseService.isAdmin(user)) { + checkNamespace(namespace, user.getId()); + } + LogMonitoringVO result = getLogMonitoringVO(podLogQueryDTO); + return new PodLogQueryVO(result.getLogs(), + podLogQueryDTO.getQueryStart(), + podLogQueryDTO.getQueryStart() + result.getTotalLogs().intValue() - 1, + result.getTotalLogs().intValue()); + } + + /** + * 获取单pod日志字符串 + * @param podLogQueryDTO pod日志查询条件实体类 + * @return String Pod日志 + */ + @Override + public String getPodLogStr(PodLogQueryDTO podLogQueryDTO) { + //获取用户信息 + UserContext user = userContextService.getCurUser(); + String namespace = podLogQueryDTO.getNamespace(); + if (!BaseService.isAdmin(user)) { + checkNamespace(namespace, user.getId()); + } + return getPodLogStr(namespace, podLogQueryDTO); + } + + /** + * 获取单pod日志字符串 + * @param namespace 命名空间 + * @param podLogQueryDTO pod日志查询实体类 + * @return String Pod日志 + */ + private String getPodLogStr(String namespace, PodLogQueryDTO podLogQueryDTO) { + StringBuilder logBuilder = new StringBuilder(); + LogMonitoringVO result = getLogMonitoringVO(namespace, podLogQueryDTO); + // 当前查询总条数 + int curQueryLogSize = 0; + // 计划查询总条数 + Integer toQueryLogSize = podLogQueryDTO.getLines(); + while (CollectionUtil.isNotEmpty(result.getLogs())) { + result.getLogs().forEach(log -> logBuilder.append(log).append(StrUtil.CRLF)); + curQueryLogSize += result.getLogs().size(); + // 设置下次查询起始坐标 = 上次查询坐标+上次查询跨度 + podLogQueryDTO.setStartLine(podLogQueryDTO.getQueryStart() + podLogQueryDTO.getQueryLines()); + if (toQueryLogSize != null) { + // 当前有计划查询总条数 + if (curQueryLogSize >= toQueryLogSize) { + // 满足计划查询总条数,查询完毕 + break; + } else if (curQueryLogSize + podLogQueryDTO.getQueryLines() > toQueryLogSize) { + // 若本批次查询会超出计划查询总条数,则取 计划查询总条数 - 当前查询总条数 作为本批次查询条数 + podLogQueryDTO.setLines(toQueryLogSize - curQueryLogSize); + } + } + result = getLogMonitoringVO(namespace, podLogQueryDTO); + } + return logBuilder.toString(); + } + + /** + * 查询Pod日志 + * @param podLogQueryDTO pod日志查询条件实体类 + * @return LogMonitoringVO Pod日志 + */ + private LogMonitoringVO getLogMonitoringVO(PodLogQueryDTO podLogQueryDTO) { + return getLogMonitoringVO(podLogQueryDTO.getNamespace(), podLogQueryDTO); + } + + /** + * 查询Pod日志 + * @param namespace 命名空间 + * @param podLogQueryDTO pod日志查询实体类 + * @return LogMonitoringVO Pod日志 + */ + private LogMonitoringVO getLogMonitoringVO(String namespace, PodLogQueryDTO podLogQueryDTO) { + LogMonitoringBO logMonitoringBo = new LogMonitoringBO(namespace, podLogQueryDTO); + return logMonitoringApi.searchLogByPodName( + podLogQueryDTO.getQueryStart(), + podLogQueryDTO.getQueryLines(), + logMonitoringBo); + } + + /** + * 按Pod名称下载日志 + * @param podLogDownloadQueryDTO pod日志下载条件实体类 + * @param response 响应 + */ + @Override + public void downLoadPodLog(PodLogDownloadQueryDTO podLogDownloadQueryDTO, HttpServletResponse response) { + //获取用户信息 + UserContext user = userContextService.getCurUser(); + String namespace = podLogDownloadQueryDTO.getNamespace(); + if (!BaseService.isAdmin(user)) { + checkNamespace(namespace, user.getId()); + } + String random = DateUtil.format(new Date(), DatePattern.PURE_DATETIME_FORMAT) + RandomUtil.randomString(4); + String baseTempPath = System.getProperty("java.io.tmpdir"); + // 临时目录 + String tempPath = baseTempPath + File.separator + random; + fileStoreApi.createDir(tempPath); + for (PodVO podVO : podLogDownloadQueryDTO.getPodVOList()) { + // 按节点名称获取日志 + String podLogStr = getPodLogStr(namespace, new PodLogQueryDTO(podVO.getPodName())); + // 生成Pod日志文件 + String podLogFilePath = tempPath + File.separator + podVO.getDisplayName() + ".log"; + fileStoreApi.createOrAppendFile(podLogFilePath, podLogStr, true); + } + // 压缩文件 (与临时目录同目录级) + String zipFile = tempPath + ".zip"; + fileStoreApi.zipDirOrFile(tempPath, zipFile); + // 下载文件 + fileStoreApi.download(zipFile, response); + // 删除临时文件 + fileStoreApi.deleteDirOrFile(zipFile); + fileStoreApi.deleteDirOrFile(tempPath); + } + + /** + * 统计Pod日志数量 + * @param podLogDownloadQueryDTO pod日志下载条件实体类 + * @return Map String:Pod name,Long: Pod count + */ + @Override + public Map getLogCount(PodLogDownloadQueryDTO podLogDownloadQueryDTO) { + //获取用户信息 + UserContext user = userContextService.getCurUser(); + String namespace = podLogDownloadQueryDTO.getNamespace(); + if (!BaseService.isAdmin(user)) { + checkNamespace(namespace, user.getId()); + } + Map logCountMap = new HashMap<>(podLogDownloadQueryDTO.getPodVOList().size() * 2); + for (int i = 0; i < podLogDownloadQueryDTO.getPodVOList().size(); i++) { + String podName = podLogDownloadQueryDTO.getPodVOList().get(i).getPodName(); + logCountMap.put(podName, logMonitoringApi.searchLogCountByPodName(new LogMonitoringBO(namespace, podName))); + } + return logCountMap; + } + + /** + * namespace 命名空间名称校验 + * + * + */ + private void checkNamespace(String namespace, Long curUserId) { + if (curUserId == null) { + throw new RuntimeException("Please Login!"); + } + if (!namespace.equals(k8sNameTool.generateNamespace(curUserId))) { + throw new RuntimeException("权限不足"); + } + } + +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/utils/BizConvertUtils.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/utils/BizConvertUtils.java new file mode 100644 index 0000000..87636bf --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/utils/BizConvertUtils.java @@ -0,0 +1,268 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.utils; + +import cn.hutool.core.collection.CollectionUtil; +import io.fabric8.kubernetes.api.model.*; +import io.fabric8.kubernetes.api.model.apps.Deployment; +import io.fabric8.kubernetes.api.model.batch.Job; +import io.fabric8.kubernetes.api.model.extensions.Ingress; +import org.dubhe.k8s.domain.cr.DistributeTrain; +import org.dubhe.k8s.domain.resource.*; +import org.springframework.util.CollectionUtils; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +/** + * @description Biz转换工具类,统一在此进行fabric8 POJO到Biz的转换,以保证各处转换结果一致 + * @date 2020-06-02 + * */ +public class BizConvertUtils { + private static final String COMPLETED = "Completed"; + + /** + * 将Pod List转为 PodBiz List + * + * @param podList Pod的集合 + * @return List BizPod的集合 + */ + public static List toBizPodList(List podList) { + return podList.parallelStream().map(obj -> toBizPod(obj)).collect(Collectors.toList()); + } + + /** + * 将Pod 转为 PodBiz,并设置completedTime + * + * @param pod Pod对象 + * @return BizPod BizPod对象 + */ + public static BizPod toBizPod(Pod pod) { + if (pod == null) { + return null; + } + BizPod bizPod = MappingUtils.mappingTo(pod, BizPod.class); + List containerStatus = pod.getStatus().getContainerStatuses(); + if (!CollectionUtil.isEmpty(containerStatus)) { + containerStatus.forEach(item -> { + if (item.getState().getTerminated() != null && COMPLETED.equals(item.getState().getTerminated().getReason())) { + bizPod.setCompletedTime(item.getState().getTerminated().getFinishedAt()); + } + }); + } + return bizPod; + } + /** + * 将List 转为 List + * + * @param deploymentList Deployment集合 + * @return List BizDeployment集合 + */ + public static List toBizDeploymentList(List deploymentList) { + return deploymentList.parallelStream().map(obj -> toBizDeployment(obj)).collect(Collectors.toList()); + } + /** + * 将Deployment 转为 BizDeployment + * + * @param deployment Deployment对象 + * @return BizDeployment BizDeployment对象 + */ + public static BizDeployment toBizDeployment(Deployment deployment) { + return MappingUtils.mappingTo(deployment, BizDeployment.class); + } + /** + * 将List 转为 List + * + * @param jobList Job的集合 + * @return List BizJob的集合 + */ + public static List toBizJobList(List jobList) { + return jobList.parallelStream().map(obj -> toBizJob(obj)).collect(Collectors.toList()); + } + /** + * 将Job 转为 BizJob + * + * @param job Job对象 + * @return BizJob BizJob对象 + */ + public static BizJob toBizJob(Job job) { + return MappingUtils.mappingTo(job, BizJob.class); + } + /** + * 将Namespace 转为 BizNamespace + * + * @param namespace 命名空间 + * @return BizNamespace BizNamespace命名空间 + */ + public static BizNamespace toBizNamespace(Namespace namespace) { + return MappingUtils.mappingTo(namespace, BizNamespace.class); + } + /** + * 将Node 转为 BizNode + * + * @param node Node对象 + * @return BizNode BizNode对象 + */ + public static BizNode toBizNode(Node node) { + return MappingUtils.mappingTo(node, BizNode.class); + } + + /** + * 将List 转为 List + * @param nodes + * @return List + */ + public static List toBizNodes(List nodes){ + List bizNodeList = new ArrayList<>(); + if (CollectionUtils.isEmpty(nodes)){ + return bizNodeList; + } + for (Node node : nodes){ + bizNodeList.add(toBizNode(node)); + } + return bizNodeList; + } + + /** + * 将PersistentVolumeClaim 转为 BizPersistentVolumeClaim + * + * @param persistentVolumeClaim 对象 + * @return BizPersistentVolumeClaim PersistentVolumeClaim实体类 + */ + public static BizPersistentVolumeClaim toBizPersistentVolumeClaim(PersistentVolumeClaim persistentVolumeClaim) { + return MappingUtils.mappingTo(persistentVolumeClaim, BizPersistentVolumeClaim.class); + } + + /** + * 将ResourceQuota 转为 BizResourceQuota + * + * @param resourceQuota 资源对象 + * @return BizResourceQuota resourceQuota业务类 + */ + public static BizResourceQuota toBizResourceQuota(ResourceQuota resourceQuota) { + return MappingUtils.mappingTo(resourceQuota, BizResourceQuota.class); + } + + /** + * 将LimitRange 转为 BizLimitRange + * + * @param limitRange 对象 + * @return BizLimitRange BizLimitRange实体类 + */ + public static BizLimitRange toBizLimitRange(LimitRange limitRange) { + return MappingUtils.mappingTo(limitRange, BizLimitRange.class); + } + + /** + * 将DistributeTrain 转为 BizDistributeTrain + * + * @param distributeTrain 对象 + * @return + */ + public static BizDistributeTrain toBizDistributeTrain(DistributeTrain distributeTrain){ + return MappingUtils.mappingTo(distributeTrain,BizDistributeTrain.class); + } + + /** + * 将List 转为 List + * + * @param distributeTrainList 对象 + * @return + */ + public static List toBizDistributeTrainList(List distributeTrainList){ + List distributeTrains = distributeTrainList.parallelStream().map(obj -> toBizDistributeTrain(obj)).collect(Collectors.toList()); + return distributeTrains; + } + + /** + * 将Service 转为 BizService + * + * @param service 对象 + * @return + */ + public static BizService toBizService(Service service) { + return MappingUtils.mappingTo(service, BizService.class); + } + + /** + * 将Secret 转为 BizSecret + * + * @param secret 对象 + * @return + */ + public static BizSecret toBizSecret(Secret secret) { + return MappingUtils.mappingTo(secret, BizSecret.class); + } + + /** + * 将Ingress 转为 BizIngress + * + * @param ingress 对象 + * @return + */ + public static BizIngress toBizIngress(Ingress ingress) { + BizIngress bizIngress = MappingUtils.mappingTo(ingress, BizIngress.class); + bizIngress.getRules().forEach(BizIngressRule::takeServicePort); + return bizIngress; + } + + /** + * 将Taint 转为 BizTaint对象 + * + * @param taint + * @return + */ + public static BizTaint toBizTaint(Taint taint){ + BizTaint bizTaint = MappingUtils.mappingTo(taint,BizTaint.class); + return bizTaint; + } + + /** + * 将BizTaint 转为 Taint + * + * @param bizTaint + * @return Taint + */ + public static Taint toTaint(BizTaint bizTaint){ + if (bizTaint == null){ + return null; + } + return new Taint(bizTaint.getEffect(),bizTaint.getKey(),bizTaint.getTimeAdded(),bizTaint.getValue()); + } + + /** + * 将 List 转为 List + * + * @param bizTaintList + * @return List + */ + public static List toTaints(List bizTaintList){ + List taintList = new ArrayList<>(); + if (CollectionUtils.isEmpty(bizTaintList)){ + return taintList; + } + for (BizTaint bizTaint : bizTaintList){ + Taint taint = toTaint(bizTaint); + if (taint != null){ + taintList.add(taint); + } + } + return taintList; + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/utils/K8sCallBackTool.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/utils/K8sCallBackTool.java new file mode 100644 index 0000000..6f9db2d --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/utils/K8sCallBackTool.java @@ -0,0 +1,189 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.utils; + +import cn.hutool.core.date.DateField; +import cn.hutool.core.date.DatePattern; +import cn.hutool.core.date.DateUtil; +import org.dubhe.biz.base.constant.AuthConst; +import org.dubhe.biz.base.constant.StringConstant; +import org.dubhe.biz.base.constant.SymbolConstant; +import org.dubhe.biz.base.utils.AesUtil; +import org.dubhe.biz.base.utils.StringUtils; +import org.dubhe.k8s.enums.BusinessLabelServiceNameEnum; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +/** + * @description k8s命名相关工具类 token使用MD5加密,并设置超时时间 + * @date 2020-05-28 + */ +@Component +public class K8sCallBackTool { + + /** + * k8s 回调 token秘钥 + */ + @Value("${k8s.callback.token.secret-key}") + private String secretKey; + /** + * k8s 回调token超时时间 + */ + @Value("${k8s.callback.token.expire-seconds}") + private Integer expireSeconds; + /** + * k8s 回调域名或IP:Port + */ + @Value("${k8s.callback.url}") + private String url; + + /** + * k8s 回调token key + */ + public static final String K8S_CALLBACK_TOKEN = AuthConst.K8S_CALLBACK_TOKEN; + /** + * 失败重试次数 + */ + private static final int RETRY_COUNT = 3; + + /** + * k8s 回调匹配地址 + */ + private static final List K8S_CALLBACK_PATH; + /** + * k8s 回调路径 + */ + private static final String K8S_CALLBACK_PATH_DEPLOYMENT = "/api/k8s/callback/deployment/"; + public static final String K8S_CALLBACK_PATH_POD = StringConstant.K8S_CALLBACK_URI+ SymbolConstant.SLASH; + + static { + K8S_CALLBACK_PATH = new ArrayList<>(); + // 添加需要token权限校验的地址(Shiro匿名访问的地址) + K8S_CALLBACK_PATH.add(K8S_CALLBACK_PATH_POD + "**"); + K8S_CALLBACK_PATH.add(K8S_CALLBACK_PATH_DEPLOYMENT + "**"); + } + + /** + * 获取 k8s 回调匹配地址 + * + * @return List + */ + public static List getK8sCallbackPaths() { + return new ArrayList<>(K8S_CALLBACK_PATH); + } + + + /** + * 生成k8s回调 + * + * @return String + */ + public String generateToken() { + String expireTime = DateUtil.format( + DateUtil.offset(new Date(), DateField.SECOND, expireSeconds), + DatePattern.PURE_DATETIME_PATTERN + ); + return AesUtil.encrypt(expireTime, secretKey); + } + + /** + * 验证token + * + * @param token + * @return boolean + */ + public boolean validateToken(String token) { + String expireTime = AesUtil.decrypt(token, secretKey); + if (StringUtils.isEmpty(expireTime)){ + return false; + } + String nowTime = DateUtil.format( + new Date(), + DatePattern.PURE_DATETIME_PATTERN + ); + return expireTime.compareTo(nowTime) > 0; + } + + + /** + * 判断当前是否可以再次重试 + * + * @param retryTimes 第n次试图重试 + * @return boolean + */ + public boolean continueRetry(int retryTimes) { + return retryTimes <= RETRY_COUNT; + } + + /** + * 获取回调地址 + * + * @param podLabel + * @return String + */ + public String getPodCallbackUrl(String podLabel) { + return "http://"+BusinessLabelServiceNameEnum.getServiceNameByBusinessLabel(podLabel) + K8S_CALLBACK_PATH_POD + podLabel; + } + + /** + * 获取回调地址 + * + * @param businessLabel + * @return String + */ + public String getDeploymentCallbackUrl(String businessLabel) { + return "http://"+BusinessLabelServiceNameEnum.getServiceNameByBusinessLabel(businessLabel) + K8S_CALLBACK_PATH_DEPLOYMENT + businessLabel; + } + + + /** + * 获取超时时间秒 + * + * @param timeoutSecond 超时秒数 + * @return Long + */ + public static Long getTimeoutSecondLong(int timeoutSecond) { + return Long.valueOf( + DateUtil.format( + DateUtil.offset( + new Date(), DateField.SECOND, timeoutSecond + ), + DatePattern.PURE_DATETIME_PATTERN + ) + ); + } + + /** + * 获取当前秒数 + * + * @return Long + */ + public static Long getCurrentSecondLong() { + return Long.valueOf( + DateUtil.format( + new Date(), + DatePattern.PURE_DATETIME_PATTERN + ) + ); + } + +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/utils/K8sNameTool.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/utils/K8sNameTool.java new file mode 100644 index 0000000..a4a2d44 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/utils/K8sNameTool.java @@ -0,0 +1,319 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.utils; + +import cn.hutool.core.date.DatePattern; +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.util.RandomUtil; +import org.apache.commons.lang3.StringUtils; +import org.dubhe.biz.base.constant.StringConstant; +import org.dubhe.biz.base.constant.SymbolConstant; +import org.dubhe.biz.base.context.UserContext; +import org.dubhe.biz.base.enums.BizEnum; +import org.dubhe.biz.file.enums.BizPathEnum; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.dubhe.k8s.api.NamespaceApi; +import org.dubhe.k8s.config.K8sNameConfig; +import org.dubhe.k8s.domain.resource.BizNamespace; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import javax.annotation.Resource; +import java.util.Date; + +/** + * @description k8s命名相关工具类 + * @date 2020-05-13 + */ +@Component +public class K8sNameTool { + @Autowired + private K8sNameConfig k8sNameConfig; + /** + * 命名分隔符 + */ + private static final char SEPARATOR = '-'; + /** + * 文件分隔符 + */ + private static final String K8S_FILE_SEPARATOR = "/"; + /** + * 资源名称前缀 + */ + private static final String RESOURCE_NAME = "rn"; + /** + * 随机长度值 + */ + private static final int RANDOM_LENGTH = 4; + + @Resource + private NamespaceApi namespaceApi; + + /** + * 生成 ResourceName + * + * @param bizEnum 业务枚举 + * @param resourceInfo 资源备注信息(保证同业务下唯一并且命名规范) + * @return String + */ + public String generateResourceName(BizEnum bizEnum, String resourceInfo) { + return bizEnum.getBizCode() + SEPARATOR + RESOURCE_NAME + SEPARATOR + resourceInfo; + } + + /** + * 生成 Notebook的Namespace + * + * @param userId + * @return namespace + */ + public String generateNamespace(long userId) { + return this.k8sNameConfig.getNamespace() + SEPARATOR + userId; + } + + /** + * 从resourceName中获取资源信息 + * + * @param bizEnum 业务枚举 + * @param resourceName + * @return resourceInfo + */ + public String getResourceInfoFromResourceName(BizEnum bizEnum, String resourceName) { + if (StringUtils.isEmpty(resourceName) || !resourceName.contains(bizEnum.getBizCode() + SEPARATOR)) { + return null; + } + return resourceName.replace(bizEnum.getBizCode() + SEPARATOR + RESOURCE_NAME + SEPARATOR, SymbolConstant.BLANK); + } + + /** + * 从namespace 获取使用者ID + * + * @param namespace + * @return Long + */ + public Long getUserIdFromNamespace(String namespace) { + if (StringUtils.isEmpty(namespace) || !namespace.contains(this.k8sNameConfig.getNamespace() + SEPARATOR)) { + return null; + } + return Long.valueOf(namespace.replace(this.k8sNameConfig.getNamespace() + SEPARATOR, "")); + } + + + /** + * 生成业务模块相对路径 + * + * @param bizPathEnum 业务路径枚举 + * @return String 例如: /{biz}/{userId}/{YYYYMMDDhhmmssSSS+四位随机数}/ + */ + public String getPath(BizPathEnum bizPathEnum, long userId) { + if (bizPathEnum == null) { + return null; + } + return optimizationPath(K8S_FILE_SEPARATOR + + bizPathEnum.getBizPath() + + K8S_FILE_SEPARATOR + + userId + + K8S_FILE_SEPARATOR + + DateUtil.format(new Date(), DatePattern.PURE_DATETIME_MS_FORMAT) + RandomUtil.randomString(RANDOM_LENGTH) + + K8S_FILE_SEPARATOR); + } + + /** + * 生成业务模块预置路径 + * + * @param bizPathEnum 业务路径枚举 + * @return String 例如: /{biz}/{userId}/{YYYYMMDDhhmmssSSS+四位随机数}/ + */ + public String getPrePath(BizPathEnum bizPathEnum, long userId) { + if (bizPathEnum == null) { + return null; + } + return optimizationPath(K8S_FILE_SEPARATOR + + bizPathEnum.getBizPath() + + K8S_FILE_SEPARATOR + + StringConstant.COMMON + + K8S_FILE_SEPARATOR + + userId + + K8S_FILE_SEPARATOR + + DateUtil.format(new Date(), DatePattern.PURE_DATETIME_MS_FORMAT) + RandomUtil.randomString(RANDOM_LENGTH) + + K8S_FILE_SEPARATOR); + } + + + /** + * 去除根路径 + * + * @param path + * @return String + */ + public String removeRootPath(String path) { + if (StringUtils.isBlank(path) || !path.startsWith(k8sNameConfig.getNfsRootPath())) { + return path; + } + return optimizationPath(K8S_FILE_SEPARATOR + path.replace(k8sNameConfig.getNfsRootPath(), "")); + } + + /** + * 路径添加bucket + * + * @param path + * @return String + */ + public String appendBucket(String path) { + return optimizationPath(K8S_FILE_SEPARATOR + + k8sNameConfig.getFileBucket() + + K8S_FILE_SEPARATOR + + path); + } + + /** + * 路径添加时间戳随机数 + * + * @param path + * @return String + */ + public String appendTimeStampAndRandomNum(String path) { + return optimizationPath(path + + DateUtil.format(new Date(), DatePattern.PURE_DATETIME_MS_FORMAT) + RandomUtil.randomString(RANDOM_LENGTH) + + K8S_FILE_SEPARATOR); + } + + /** + * 路径根据业务转换 + * + * @param path + * @param sourceBizPathEnum 源业务 Path + * @param targetBizPathEnum 目标业务 Path + * @return String + */ + public String convertNfsPath(String path, BizPathEnum sourceBizPathEnum, BizPathEnum targetBizPathEnum) { + if (!validateBizPath(path, sourceBizPathEnum) || targetBizPathEnum == null) { + return path; + } + return optimizationPath(path.replace(K8S_FILE_SEPARATOR + sourceBizPathEnum.getBizPath() + K8S_FILE_SEPARATOR + , K8S_FILE_SEPARATOR + targetBizPathEnum.getBizPath() + K8S_FILE_SEPARATOR)); + } + + /** + * 获取绝对路径 + * + * @param path + * @return String + */ + public String getAbsolutePath(String path) { + if (StringUtils.isBlank(path)) { + return path; + } + return optimizationPath(k8sNameConfig.getNfsRootPath() + + K8S_FILE_SEPARATOR + + k8sNameConfig.getFileBucket() + + K8S_FILE_SEPARATOR + + path); + } + + /** + * 验证 path 是否是所属业务路径 + * + * @param path + * @param bizPathEnum + * @return boolean + */ + public boolean validateBizPath(String path, BizPathEnum bizPathEnum) { + return org.apache.commons.lang3.StringUtils.isNotBlank(path) + && bizPathEnum != null + && path.contains(bizPathEnum.getBizPath()) + && !path.contains(K8S_FILE_SEPARATOR + k8sNameConfig.getFileBucket() + K8S_FILE_SEPARATOR) + && !path.contains(K8S_FILE_SEPARATOR + k8sNameConfig.getNfsRootPath() + K8S_FILE_SEPARATOR); + } + + /** + * 路径优化 + * + * @param path + * @return String + */ + private String optimizationPath(String path) { + if (StringUtils.isBlank(path)) { + return path; + } + return path.replaceAll("///*", K8S_FILE_SEPARATOR); + } + + /** + * 获取k8s pod标签 + * + * @param bizEnum + * @return String + */ + public String getPodLabel(BizEnum bizEnum) { + return bizEnum == null ? null : bizEnum.getBizCode(); + } + + /** + * 获取数据集在镜像中路径 + * + * @return String + */ + public String getDatasetPath() { + return k8sNameConfig.getDatasetPath(); + } + + + /** + * 自送生成K8S名称,供K8S使用 + * + * @return String + */ + public String getK8sName() { + return DateUtil.format(new Date(), DatePattern.PURE_DATETIME_MS_FORMAT) + + RandomUtil.randomString(RANDOM_LENGTH); + } + + /** + * @param curUser 当前用户 + * @return namespace k8s的命名空间 + */ + public String getNamespace(UserContext curUser) { + String namespaceStr = this.generateNamespace(curUser.getId()); + BizNamespace bizNamespace = namespaceApi.get(namespaceStr); + if (null == bizNamespace) { + BizNamespace namespace = namespaceApi.create(namespaceStr, null); + if (null == namespace || !namespace.isSuccess()) { + LogUtil.error(LogEnum.BIZ_K8S, "用户{} namespace为空", curUser.getUsername()); + } + } + return namespaceStr; + } + + /** + * @param userId 用户id + * @return namespace k8s的命名空间 + */ + public String getNamespace(Long userId) { + String namespaceStr = this.generateNamespace(userId); + BizNamespace bizNamespace = namespaceApi.get(namespaceStr); + if (null == bizNamespace) { + BizNamespace namespace = namespaceApi.create(namespaceStr, null); + if (null == namespace || !namespace.isSuccess()) { + LogUtil.error(LogEnum.BIZ_K8S, "用户{} namespace为空", userId); + } + } + return namespaceStr; + } + +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/utils/K8sUtils.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/utils/K8sUtils.java new file mode 100644 index 0000000..557d643 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/utils/K8sUtils.java @@ -0,0 +1,160 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.utils; + +import cn.hutool.core.io.FileUtil; +import cn.hutool.core.util.StrUtil; +import com.alibaba.fastjson.JSON; +import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.ConfigBuilder; +import io.fabric8.kubernetes.client.DefaultKubernetesClient; +import io.fabric8.kubernetes.client.KubernetesClient; +import lombok.Getter; +import org.apache.commons.io.IOUtils; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.k8s.constant.K8sLabelConstants; +import org.dubhe.k8s.properties.ClusterProperties; +import org.dubhe.biz.log.utils.LogUtil; +import org.springframework.beans.BeansException; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.core.io.ClassPathResource; + +import java.io.File; +import java.io.IOException; +import java.util.Base64; +import java.util.HashMap; +import java.util.Map; + +/** + * @description init K8sUtils + * @date 2020-04-09 + */ +@Getter +public class K8sUtils implements ApplicationContextAware { + + /** + * K8S通信协议 + **/ + private final static String HTTPS_PREFIX = "https"; + + private final static String USER_DIR_SYSTEM_PROPERTY = "user.dir"; + + private ApplicationContext applicationContext; + + private KubernetesClient client; + private Config config; + private String nfs; + private String host; + private String port; + + /** + * 获取 k8s 连接配置文件 + * @param kubeConfig + * @return + * @throws IOException + */ + private String getKubeconfigFile(String kubeConfig) throws IOException { + kubeConfig = kubeConfig.startsWith(File.separator) ? kubeConfig : File.separator.concat(kubeConfig); + String path = System.getProperty(USER_DIR_SYSTEM_PROPERTY) + kubeConfig; + LogUtil.info(LogEnum.BIZ_K8S, "kubeconfig path:{}", path); + FileUtil.writeFromStream(new ClassPathResource(kubeConfig).getInputStream(), path); + return path; + } + + /** + * 构造 KubernetesClient + * @param clusterProperties + * @throws IOException + */ + public K8sUtils(ClusterProperties clusterProperties) throws IOException{ + String kubeConfig = clusterProperties.getKubeconfig(); + if (StrUtil.isNotBlank(kubeConfig)) { + String kubeConfigFile = getKubeconfigFile(kubeConfig); + //修改环境变量,重新指定kubeconfig读取位置 + System.setProperty(Config.KUBERNETES_KUBECONFIG_FILE, kubeConfigFile); + client = new DefaultKubernetesClient(); + config = client.getConfiguration(); + + } else { + LogUtil.warn(LogEnum.BIZ_K8S, "can't find kubeconfig in classpath, ignoring"); + String k8sUrl = clusterProperties.getUrl(); + if (k8sUrl.startsWith(HTTPS_PREFIX)) { + config = new ConfigBuilder().withMasterUrl(k8sUrl) + .withTrustCerts(true) + .withCaCertData(IOUtils.toString(clusterProperties.getCaCrt().getInputStream(), "UTF-8")) + .withClientCertData(Base64.getEncoder().encodeToString(IOUtils.toByteArray(clusterProperties.getClientCrt().getInputStream()))) + .withClientKeyData(IOUtils.toString(clusterProperties.getClientKey().getInputStream(), "UTF-8")) + .build(); + } else { + config = new ConfigBuilder().withMasterUrl(k8sUrl).build(); + } + LogUtil.info(LogEnum.BIZ_K8S, "config信息为{}", JSON.toJSONString(config)); + client = new DefaultKubernetesClient(config); + LogUtil.info(LogEnum.BIZ_K8S, "client为{}", JSON.toJSONString(client)); + } + + nfs = clusterProperties.getNfs(); + host = clusterProperties.getHost(); + port = clusterProperties.getPort(); + + //打印集群信息 + LogUtil.info(LogEnum.BIZ_K8S, "ApiVersion : {}", client.getApiVersion()); + LogUtil.info(LogEnum.BIZ_K8S, "MasterUrl : {}", client.getMasterUrl()); + LogUtil.info(LogEnum.BIZ_K8S, "NFS Server : {}", nfs); + LogUtil.info(LogEnum.BIZ_K8S, "VersionInfo : {}", JSON.toJSONString(client.getVersion())); + } + + /** + * 导出成yaml字符串 + * + * @param resource 任意对象 + * @return String 转换后的yaml字符串 + */ + public String convertToYaml(Object resource) { + return YamlUtils.convertToYaml(resource); + } + + /** + * 导出成yaml字符串 + * + * @param resource 任意对象 + * @param filePath 文件路径 + */ + public void dumpToYaml(Object resource, String filePath) { + YamlUtils.dumpToYaml(resource, filePath); + } + + @Override + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { + this.applicationContext = applicationContext; + } + + /** + * 获取gpu选择label + * @param gpuNum + * @return + */ + public Map gpuSelector(Integer gpuNum) { + Map gpuSelector = new HashMap<>(2); + if (gpuNum != null && gpuNum > 0) { + gpuSelector.put(K8sLabelConstants.NODE_GPU_LABEL_KEY, K8sLabelConstants.NODE_GPU_LABEL_VALUE); + } + return gpuSelector; + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/utils/LabelUtils.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/utils/LabelUtils.java new file mode 100644 index 0000000..7ba42a8 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/utils/LabelUtils.java @@ -0,0 +1,140 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.utils; + +import cn.hutool.core.util.ArrayUtil; +import org.dubhe.biz.base.constant.MagicNumConstant; +import org.dubhe.biz.base.utils.SpringContextHolder; +import org.dubhe.k8s.constant.K8sLabelConstants; + +import java.util.HashMap; +import java.util.Map; + +/** + * @description label 工具类 + * @date 2020-06-17 + */ +public class LabelUtils { + /** + * 生成基础标签集,包含资源名、创建者、环境 标签 + * + * @param resourceName 命名空间 + * @param labels 可变参数标签Map + * @return + */ + public static Map getBaseLabels(String resourceName, Map... labels) { + Map baseLabels = new HashMap<>(MagicNumConstant.SIXTEEN); + baseLabels.put(K8sLabelConstants.BASE_TAG_SOURCE, resourceName); + baseLabels.put(K8sLabelConstants.BASE_TAG_CREATE_BY, K8sLabelConstants.BASE_TAG_CREATE_BY_VALUE); + baseLabels.put(K8sLabelConstants.PLATFORM_RUNTIME_ENV, SpringContextHolder.getActiveProfile()); + if (ArrayUtil.isNotEmpty(labels)) { + for (Map obj : labels) { + if (obj != null) { + baseLabels.putAll(obj); + } + } + } + return baseLabels; + } + + /** + * 生成基础标签集,包含资源名、创建者、环境、业务 标签 + * + * @param resourceName 命名空间 + * @param business 业务标签 + * @param labels 可变参数标签Map + * @return + */ + public static Map getBaseLabels(String resourceName, String business, Map... labels) { + Map labelMap = getBaseLabels(resourceName, labels); + if (null != business) { + labelMap.put(K8sLabelConstants.BASE_TAG_BUSINESS, business); + } + return labelMap; + } + + /** + * 生成子资源标签集,包含资源名、创建者、环境、父资源、父类型 标签 + * + * @param resourceName 命名空间 + * @param pName 父资源名称 + * @param pKind 父类型名称 + * @param labels 可变参数标签Map + * @return + */ + public static Map getChildLabels(String resourceName, String pName, String pKind, Map... labels) { + Map baseLabels = getBaseLabels(resourceName, labels); + baseLabels.put(K8sLabelConstants.BASE_TAG_P_NAME, pName); + baseLabels.put(K8sLabelConstants.BASE_TAG_P_KIND, pKind); + return baseLabels; + } + + /** + * 生成子资源标签集,包含资源名、创建者、环境、父资源、父类型、业务标签 标签 + * + * @param resourceName 命名空间 + * @param pName 父资源名称 + * @param pKind 父类型名称 + * @param business 业务标签 + * @param labels 可变参数标签Map + * @return + */ + public static Map getChildLabels(String resourceName, String pName, String pKind, String business, Map... labels) { + Map labelMap = getChildLabels(resourceName, pName, pKind, labels); + if (null != business) { + labelMap.put(K8sLabelConstants.BASE_TAG_BUSINESS, business); + } + return labelMap; + } + + /** + * 添加环境标签用以分流 + * + * @param resourceName 资源名称 + * @return Map map + */ + public static Map withEnvResourceName(String resourceName) { + Map labels = withEnvResourceName(); + labels.put(K8sLabelConstants.BASE_TAG_SOURCE, resourceName); + return labels; + } + + /** + * 添加环境标签用以分流 + * + * @return Map map + */ + public static Map withEnvResourceName() { + Map labels = new HashMap<>(0); + labels.put(K8sLabelConstants.PLATFORM_RUNTIME_ENV, SpringContextHolder.getActiveProfile()); + return labels; + } + + /** + * 附带环境标签 + * + * @param key 标签健 + * @param value 标签值 + * @return Map map + */ + public static Map withEnvLabel(String key, String value) { + Map labels = withEnvResourceName(); + labels.put(key, value); + return labels; + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/utils/MappingUtils.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/utils/MappingUtils.java new file mode 100644 index 0000000..6704455 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/utils/MappingUtils.java @@ -0,0 +1,153 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.utils; + +import cn.hutool.core.util.StrUtil; +import org.dubhe.biz.base.constant.SymbolConstant; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.k8s.annotation.K8sField; +import org.dubhe.biz.log.utils.LogUtil; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +/** + * @description 将 fabric8 pojo 转换为 resource下Biz类 + * 规则: 根据 ":" 分割 @K8sField,反射注入属性 + * 示例:@K8sField("spec:template:spec:containers") + * private List containers; 对应 Deployment.spec.template.containers + * @date 2020-04-17 + */ +public class MappingUtils { + + /** + * fabric pojo 转换为 biz pojo 注意output类和input类中 不要使用基本类型,应使用封装类型 + **/ + public static V mappingTo(T input, Class outputClass) { + //不判null的话,若T的属性有默认值,则会输出包含对应默认值的V实例 + if (null == input || outputClass == null) { + return null; + } + //相同基本类的封装类直接输出 比如 String + if (outputClass.isInstance(input)) { + return outputClass.cast(input); + } + + Field[] fields = outputClass.getDeclaredFields(); + V output = null; + try { + output = outputClass.newInstance(); + if (fields == null || fields.length < 1) { + return output; + } + + for (int i = 0; i < fields.length; i++) { + Field field = fields[i]; + K8sField k8sField = field.getDeclaredAnnotation(K8sField.class); + if (k8sField == null) { + continue; + } + String expression = k8sField.value(); + String[] splitExpression = expression.split(SymbolConstant.COLON); + Object currentArg = input; + + int j = 0; + while (j < splitExpression.length) { + if (currentArg == null) { + break; + } + String funcName = SymbolConstant.GET + StrUtil.upperFirst(splitExpression[j]); + Method getMethod = currentArg.getClass().getDeclaredMethod(funcName, null); + currentArg = getMethod.invoke(currentArg, null); + j++; + } + + if (currentArg == null) { + continue; + } + + //List类型处理 + if (List.class.isAssignableFrom(field.getType()) + && field.getGenericType() instanceof ParameterizedType + && List.class.isAssignableFrom(currentArg.getClass())) { + ParameterizedType pt = (ParameterizedType) field.getGenericType(); + //泛型里的类型 + Class actualTypeArgument = (Class) pt.getActualTypeArguments()[0]; + List outputFieldList = new ArrayList(); + List inputArgList = ((List) currentArg); + for (Object inputArg : inputArgList) { + Object outputElm = mappingTo(inputArg, actualTypeArgument); + outputFieldList.add(outputElm); + } + currentArg = outputFieldList; + } else if (Map.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType + && Map.class.isAssignableFrom(currentArg.getClass())) { + /**处理map value类型不同**/ + Map map = (Map) currentArg; + map.forEach((key, value) -> { + map.put(mappingTo(key, getMapValueClass(field, 0)), mappingTo(value, getMapValueClass(field, 1))); + }); + } else if (!field.getType().isInstance(currentArg) && field.getType().getDeclaredFields().length > 0) { + //递归处理属性 + currentArg = mappingTo(currentArg, field.getType()); + } + + //如果类型相同或是field的子类,赋值 + String setFuncName = SymbolConstant.SET + StrUtil.upperFirst(field.getName()); + Method setMethod = outputClass.getDeclaredMethod(setFuncName, field.getType()); + setMethod.invoke(output, currentArg); + } + } catch (Exception e) { + LogUtil.error(LogEnum.BIZ_K8S, "MappingUtils.mappingTo error, message{} ",e.getMessage(), e); + throw new RuntimeException("fabric to biz failed"); + } + return output; + } + + /** + * 获取map 的key或value 的类型 + * + * @param field 反射字段 + * @param fieldIndex 0获取key的Class 1获取Value的Class + * @return Class Class类对象 + */ + private static Class getMapValueClass(Field field, int fieldIndex) { + try { + if (Map.class.isAssignableFrom(field.getType())) { + Type mapMainType = field.getGenericType(); + if (mapMainType instanceof ParameterizedType) { + // 执行强制类型转换 + ParameterizedType parameterizedType = (ParameterizedType) mapMainType; + // 获取泛型类型的泛型参数 + Type[] types = parameterizedType.getActualTypeArguments(); + return Class.forName(types[fieldIndex].getTypeName()); + } else { + LogUtil.error(LogEnum.BIZ_K8S, "Error getting generic type {}",mapMainType.getTypeName()); + } + } + } catch (ClassNotFoundException e) { + LogUtil.error(LogEnum.BIZ_K8S, "MappingUtils.getMapValueClass error, message {}", e.toString(),e); + } + return null; + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/utils/PodUtil.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/utils/PodUtil.java new file mode 100644 index 0000000..02fdff1 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/utils/PodUtil.java @@ -0,0 +1,54 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.utils; + +/** + * @description k8s Pod 工具类 + * @date 2020-09-17 + */ +public class PodUtil { + + private PodUtil(){ + + } + + /** + * 判断节点是否是master节点 + * @param podName k8s pod名称 + * @return true master节点,false 其他 + */ + public static boolean isMaster(String podName){ + if(podName == null){ + return false; + } + return podName.contains("-master-"); + } + + /** + * 判断节点是否是slave节点 + * @param podName k8s pod名称 + * @return true slave节点,false 其他 + */ + public static boolean isSlave(String podName){ + if(podName == null){ + return false; + } + return podName.contains("-slave-"); + } + + +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/utils/PrometheusUtil.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/utils/PrometheusUtil.java new file mode 100644 index 0000000..d0df8f2 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/utils/PrometheusUtil.java @@ -0,0 +1,102 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.utils; + +import cn.hutool.http.HttpUtil; +import com.alibaba.fastjson.JSON; +import org.apache.commons.collections4.map.HashedMap; +import org.dubhe.biz.base.constant.MagicNumConstant; +import org.dubhe.biz.base.constant.StringConstant; +import org.dubhe.biz.base.utils.StringUtils; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.dubhe.k8s.constant.K8sParamConstants; +import org.dubhe.k8s.domain.bo.PrometheusMetricBO; +import org.dubhe.k8s.domain.dto.PodQueryDTO; + +import java.util.Map; + +/** + * @description prometheus 工具类 + * @date 2021-02-03 + */ +public class PrometheusUtil { + /** + * prometheus get查询 + * @param url + * @param paramMap + * @return + */ + public static PrometheusMetricBO getQuery(String url,Map paramMap){ + if (StringUtils.isEmpty(url)){ + return null; + } + try { + String metricStr = HttpUtil.get(url,paramMap); + if (StringUtils.isEmpty(metricStr)){ + return null; + } + return JSON.parseObject(metricStr, PrometheusMetricBO.class); + }catch (Exception e){ + LogUtil.error(LogEnum.BIZ_K8S, "getQuery url:{} paramMap:{} error:{}", url,paramMap,e.getMessage(),e); + return null; + } + } + + /** + * 组装参数 + * @param param 查询表达式 + * @param podName pod名称 + * @param podQueryDTO 查询参数 + * @return + */ + public static Map getQueryParamMap(String param,String podName,PodQueryDTO podQueryDTO){ + Map paramMap = new HashedMap<>(MagicNumConstant.EIGHT); + if (StringUtils.isEmpty(param) || StringUtils.isEmpty(podName)){ + return paramMap; + } + paramMap.put(StringConstant.QUERY, param.replace(K8sParamConstants.POD_NAME_PLACEHOLDER,podName)); + if (podQueryDTO == null){ + return paramMap; + } + if (podQueryDTO.getStartTime() != null){ + paramMap.put(StringConstant.START_LOW,podQueryDTO.getStartTime()); + } + if (podQueryDTO.getEndTime() != null){ + paramMap.put(StringConstant.END_LOW,podQueryDTO.getEndTime()); + } + if (podQueryDTO.getStep() != null){ + paramMap.put(StringConstant.STEP_LOW,podQueryDTO.getStep()); + } + return paramMap; + } + + /** + * 组装参数 + * @param param 查询表达式 + * @param podName pod名称 + * @return + */ + public static Map getQueryParamMap(String param,String podName){ + Map paramMap = new HashedMap<>(MagicNumConstant.TWO); + if (StringUtils.isEmpty(param) || StringUtils.isEmpty(podName)){ + return paramMap; + } + paramMap.put(StringConstant.QUERY, param.replace(K8sParamConstants.POD_NAME_PLACEHOLDER,podName)); + return paramMap; + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/utils/ResourceBuildUtils.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/utils/ResourceBuildUtils.java new file mode 100644 index 0000000..b74b630 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/utils/ResourceBuildUtils.java @@ -0,0 +1,205 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.utils; + +import io.fabric8.kubernetes.api.model.Secret; +import io.fabric8.kubernetes.api.model.SecretBuilder; +import io.fabric8.kubernetes.api.model.Service; +import io.fabric8.kubernetes.api.model.ServiceBuilder; +import io.fabric8.kubernetes.api.model.ServicePort; +import io.fabric8.kubernetes.api.model.ServicePortBuilder; +import io.fabric8.kubernetes.api.model.Toleration; +import io.fabric8.kubernetes.api.model.extensions.Ingress; +import io.fabric8.kubernetes.api.model.extensions.IngressBuilder; +import io.fabric8.kubernetes.api.model.extensions.IngressRule; +import io.fabric8.kubernetes.api.model.extensions.IngressRuleBuilder; +import io.fabric8.kubernetes.api.model.extensions.IngressTLS; +import io.fabric8.kubernetes.api.model.extensions.IngressTLSBuilder; +import org.dubhe.biz.base.constant.SymbolConstant; +import org.dubhe.k8s.constant.K8sParamConstants; +import org.dubhe.k8s.domain.bo.BuildIngressBO; +import org.dubhe.k8s.domain.bo.BuildServiceBO; +import org.dubhe.k8s.enums.K8sTolerationEffectEnum; +import org.dubhe.k8s.enums.K8sTolerationOperatorEnum; + +import java.util.Map; + +/** + * @description 构建 Kubernetes 资源对象 + * @date 2020-09-10 + */ +public class ResourceBuildUtils { + + /** + * 构建 Service + * @param bo + * @return + */ + public static Service buildService(BuildServiceBO bo) { + return new ServiceBuilder() + .withNewMetadata() + .withName(bo.getName()) + .addToLabels(bo.getLabels()) + .withNamespace(bo.getNamespace()) + .endMetadata() + .withNewSpec() + .withPorts(bo.getPorts()) + .withSelector(bo.getSelector()) + .endSpec() + .build(); + } + + /** + * 构建 ServicePort + * @param targetPort + * @param port + * @param name + * @return + */ + public static ServicePort buildServicePort(Integer targetPort, Integer port, String name){ + ServicePort servicePort = new ServicePortBuilder() + .withNewTargetPort(targetPort) + .withPort(port) + .withName(name) + .build(); + return servicePort; + } + + /** + * 构建 IngressRule + * @param host + * @param serviceName + * @param servicePort + * @return + */ + public static IngressRule buildIngressRule(String host, String serviceName, Integer servicePort){ + return new IngressRuleBuilder() + .withHost(host) + .withNewHttp() + .addNewPath() + .withPath(SymbolConstant.SLASH) + .withNewBackend() + .withNewServiceName(serviceName) + .withNewServicePort(servicePort) + .endBackend() + .endPath() + .endHttp() + .build(); + } + + /** + * 构建 IngressRule + * @param host + * @param serviceName + * @param servicePort + * @return + */ + public static IngressRule buildIngressRule(String host, String serviceName, String servicePort){ + return new IngressRuleBuilder() + .withHost(host) + .withNewHttp() + .addNewPath() + .withPath(SymbolConstant.SLASH) + .withNewBackend() + .withNewServiceName(serviceName) + .withNewServicePort(servicePort) + .endBackend() + .endPath() + .endHttp() + .build(); + } + + /** + * 构建 IngressTLS + * @param secretName + * @param host + * @return + */ + public static IngressTLS buildIngressTLS(String secretName, String host){ + return new IngressTLSBuilder() + .withSecretName(secretName) + .withHosts(host) + .build(); + } + + /** + * 构建 Ingress + * @param bo + * @return + */ + public static Ingress buildIngress(BuildIngressBO bo) { + return new IngressBuilder() + .withNewMetadata() + .withName(bo.getName()) + .addToLabels(bo.getLabels()) + .withNamespace(bo.getNamespace()) + .addToAnnotations(bo.getAnnotations()) + .endMetadata() + .withNewSpec() + .withRules(bo.getIngressRules()) + .withTls(bo.getIngressTLSs()) + .endSpec() + .build(); + } + + /** + * 构建 Secret + * @param namespace + * @param name + * @param labels + * @param map + * @return + */ + public static Secret buildTlsSecret(String namespace, String name, Map labels, Map map){ + Secret secret = new SecretBuilder() + .withType(K8sParamConstants.SECRET_TLS_TYPE) + .withNewMetadata() + .withName(name) + .addToLabels(labels) + .withNamespace(namespace) + .endMetadata() + .addToData(map) + .build(); + return secret; + } + + /** + * 构建 Toleration + * + * @param effect + * @param key + * @param operator + * @param tolerationSeconds + * @param value + * @return + */ + public static Toleration buildToleration(String effect,String key,String operator,Long tolerationSeconds,String value){ + return new Toleration(effect,key,operator,tolerationSeconds,value); + } + + /** + * 构建 effect=NoSchedule operator=Equal 的 Toleration + * + * @param key 键 + * @param value 值 + * @return + */ + public static Toleration buildNoScheduleEqualToleration(String key,String value){ + return new Toleration(K8sTolerationEffectEnum.NOSCHEDULE.getEffect(),key, K8sTolerationOperatorEnum.EQUAL.getOperator(),null,value); + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/utils/UnitConvertUtils.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/utils/UnitConvertUtils.java new file mode 100644 index 0000000..c2cf706 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/utils/UnitConvertUtils.java @@ -0,0 +1,71 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.utils; + +import org.dubhe.biz.base.constant.MagicNumConstant; +import org.dubhe.biz.base.utils.RegexUtil; +import org.dubhe.biz.base.utils.StringUtils; +import org.dubhe.k8s.constant.K8sParamConstants; + +/** + * @description k8s 资源单位转换 + * @date 2020-10-13 + */ +public class UnitConvertUtils { + + /** + * cpu转化为 n + * @param amount 值 + * @param format 单位 + * @return + */ + public static Long cpuFormatToN(String amount,String format){ + if (StringUtils.isEmpty(amount) || !RegexUtil.isDigits(amount)){ + return MagicNumConstant.ZERO_LONG; + } + if (StringUtils.isEmpty(format)){ + return Long.valueOf(amount) * MagicNumConstant.ONE_THOUSAND * MagicNumConstant.MILLION; + } + if (K8sParamConstants.CPU_UNIT.equals(format)){ + return Long.valueOf(amount) * MagicNumConstant.MILLION; + } + return Long.valueOf(amount); + } + + /** + * 内存转为 Mi + * @param amount 值 + * @param format 单位 + * @return + */ + public static Long memFormatToMi(String amount,String format){ + if (StringUtils.isEmpty(amount) || !RegexUtil.isDigits(amount)){ + return MagicNumConstant.ZERO_LONG; + } + if (K8sParamConstants.MEM_UNIT_TI.equals(format)){ + return Long.valueOf(amount) * MagicNumConstant.BINARY_TEN_EXP * MagicNumConstant.BINARY_TEN_EXP; + } + if (K8sParamConstants.MEM_UNIT_GI.equals(format)){ + return Long.valueOf(amount) * MagicNumConstant.BINARY_TEN_EXP; + } + if (K8sParamConstants.MEM_UNIT_KI.equals(format)){ + return Long.valueOf(amount) / MagicNumConstant.BINARY_TEN_EXP; + } + return Long.valueOf(amount); + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/utils/ValidationUtils.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/utils/ValidationUtils.java new file mode 100644 index 0000000..5fba7d6 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/utils/ValidationUtils.java @@ -0,0 +1,37 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.utils; + +import org.dubhe.k8s.constant.K8sParamConstants; +import org.dubhe.biz.base.utils.StringUtils; + +/** + * @description 校验工具类 + * @date 2020-06-05 + */ +public class ValidationUtils { + /** + * 校验resourceName是否符合k8s命名规范 + * + * @param resourceName 资源名称 + * @return boolean true 成功 false 不成功 + */ + public static boolean validateResourceName(String resourceName) { + return !(StringUtils.isEmpty(resourceName) || resourceName.length() > K8sParamConstants.RESOURCE_NAME_LENGTH || !resourceName.matches(K8sParamConstants.K8S_RESOURCE_NAME_REGEX)); + } +} diff --git a/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/utils/YamlUtils.java b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/utils/YamlUtils.java new file mode 100644 index 0000000..96232cf --- /dev/null +++ b/dubhe-server/common-k8s/src/main/java/org/dubhe/k8s/utils/YamlUtils.java @@ -0,0 +1,120 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.k8s.utils; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.google.common.collect.ImmutableList; +import io.fabric8.kubernetes.api.model.HasMetadata; +import io.fabric8.kubernetes.client.internal.SerializationUtils; +import org.dubhe.biz.base.constant.SymbolConstant; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.introspector.Property; +import org.yaml.snakeyaml.nodes.NodeTuple; +import org.yaml.snakeyaml.nodes.Tag; +import org.yaml.snakeyaml.representer.Representer; + +import java.io.FileWriter; +import java.io.IOException; +import java.io.Writer; +import java.util.Collection; + +/** + * @description yaml基本操作工具类 + * @date 2020-04-15 + */ +public class YamlUtils { + + /** + * 导出yaml时无论有没有值都忽略的属性 + **/ + private final static ImmutableList IGNORE_PROPERTIES_WHEN_DUMP_YAML = ImmutableList.of("resourceVersion"); + + private static Yaml yaml; + + static { + initYaml(); + } + + /** + * 初始化Yaml + */ + private static void initYaml() { + DumperOptions options = new DumperOptions(); + options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + options.setPrettyFlow(true); + + yaml = new Yaml(new Representer() { + @Override + protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue, Tag customTag) { + // 如果属性为null空数组,忽略它 + boolean beIgnored = (propertyValue instanceof Collection && ((Collection) propertyValue).size() == 0); + if (propertyValue == null || beIgnored) { + return null; + } else { + if (IGNORE_PROPERTIES_WHEN_DUMP_YAML.contains(property.getName())) { + return null; + } + return super.representJavaBeanProperty(javaBean, property, propertyValue, customTag); + } + } + }, options); + } + + /** + * javabean转yaml字符串 + * + * @param resource 对象 + * @return String + */ + public static String convertToYaml(Object resource) { + return yaml.dump(resource); + } + + /** + * javabean导出成yaml文件 + * + * @param resource 资源名称 + * @param filePath 文件路径 + * @return void + */ + public static void dumpToYaml(Object resource, String filePath) { + try (Writer writer = new FileWriter(filePath)) { + yaml.dump(resource, writer); + } catch (IOException e) { + LogUtil.error(LogEnum.BIZ_K8S, "dumpToYaml error:{}", e); + } + } + + /** + * 转换成Yml格式字符串 + * + * @param obj KubernetesResource对象 + * @return yml格式字符串 + */ + public static String dumpAsYaml(HasMetadata obj) { + try { + return SerializationUtils.dumpAsYaml(obj); + } catch (JsonProcessingException e) { + LogUtil.error(LogEnum.BIZ_K8S, "dumpAsYamle error:{}", e); + } + return SymbolConstant.BLANK; + } +} diff --git a/dubhe-server/common-k8s/src/main/resources/kubeconfig_test b/dubhe-server/common-k8s/src/main/resources/kubeconfig_test new file mode 100644 index 0000000..9b9f6e5 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/resources/kubeconfig_test @@ -0,0 +1,19 @@ +apiVersion: v1 +clusters: +- cluster: + certificate-authority-data: LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUN5RENDQWJDZ0F3SUJBZ0lCQURBTkJna3Foa2lHOXcwQkFRc0ZBREFWTVJNd0VRWURWUVFERXdwcmRXSmwKY201bGRHVnpNQjRYRFRJeE1EVXhOekF4TXpJd05Gb1hEVE14TURVeE5UQXhNekl3TkZvd0ZURVRNQkVHQTFVRQpBeE1LYTNWaVpYSnVaWFJsY3pDQ0FTSXdEUVlKS29aSWh2Y05BUUVCQlFBRGdnRVBBRENDQVFvQ2dnRUJBTHNEClVhOHJBQ3o3SHZETHN0UGhqZFBwWDJ2b1Vlb3hobFcraVdLTDNZanpIcFZVdWhOQktFNzlrZUNuZXhUMkxuUkgKanF2SGJTajZNMkpVbys3dyttWDQ4R3FpaTRRRENtTy9OWXJ6NGVpdTFTTEJsWmJlWWtBeWVYVDRwQVN3UFFTWQozY3FjUVh3N1pXY2hUNkl0R1kySHZPSWRKeFZvOTJEL2lxQUZwT0grR2Focld3Wm9wZWMwREpXaEE2RlZCOVE3CkpPeXRJQVE2alpjc2ZrQm9DdVRUOExqVXhya1cxSGRVTkFFOS9PTjVhNlhPQzF2b3Bia01aTE5uU2tjK2lDQ2EKK1M2WkI5b3VvWGNOOW5XN1NTdThhNHZDL2VhZU9WZGR6bFlrVHRnTC9LTm1DSVFkZEVVQmswVG5EUHhKeVhHTwpqUXVwWFVUYTByOXYxV21pVzFrQ0F3RUFBYU1qTUNFd0RnWURWUjBQQVFIL0JBUURBZ0trTUE4R0ExVWRFd0VCCi93UUZNQU1CQWY4d0RRWUpLb1pJaHZjTkFRRUxCUUFEZ2dFQkFDQnVYb0F1M2tLbkNCWlhkbmd1cVNHRHRoaWUKVHRPSmJFcHBxUWo0SG43Sm9pcnVkVmdDMXQvWU8zVDZkRmxqL1ZLRFl3dXB0cFVmTHVWVTRWTVJmNHFCU3lQaAovb3ZLM285YkoxU1hjWVllenJ0dkFwUWNnQmdEVjcwQ0xlRHRkcnI1c0VWaUFvcklSdSsyT3Z6Vm85U2dCTFN4CmFMZTVKZEU0Z3NNYndTaUkxRlkza0E3OHlEcHU4THZVZFE2MWRvSVR4dE1VWE9HTkpVMkw2cVliRkxUeDZGaDIKWDkwOGIrMmRIZ0ZvSlk0OXVNaVdLUHAvbzlXU3pPQnphQ3lEK0UzbFBYdXFrakNZRzRodVg5dkExRXZIZ3ZOMwpuK2NyWTYzNWVKWGtVcjhIRFo2Rm1qeWtBUUFNUkFickJJYTJtY0laL3B2V1hYRW9yY1o3TjV2WXlIaz0KLS0tLS1FTkQgQ0VSVElGSUNBVEUtLS0tLQo= + server: https://127.0.0.1:6443 + name: kubernetes +contexts: +- context: + cluster: kubernetes + user: kubernetes-admin + name: kubernetes-admin@kubernetes +current-context: kubernetes-admin@kubernetes +kind: Config +preferences: {} +users: +- name: kubernetes-admin + user: + client-certificate-data: LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUM4akNDQWRxZ0F3SUJBZ0lJQll2OGYvY21KUzh3RFFZSktvWklodmNOQVFFTEJRQXdGVEVUTUJFR0ExVUUKQXhNS2EzVmlaWEp1WlhSbGN6QWVGdzB5TVRBMU1UY3dNVE15TURSYUZ3MHlNakExTVRjd01UTXlNRGRhTURReApGekFWQmdOVkJBb1REbk41YzNSbGJUcHRZWE4wWlhKek1Sa3dGd1lEVlFRREV4QnJkV0psY201bGRHVnpMV0ZrCmJXbHVNSUlCSWpBTkJna3Foa2lHOXcwQkFRRUZBQU9DQVE4QU1JSUJDZ0tDQVFFQXdqZTQ2MXNiMGo5RDlQWG8KK3NleTg3bCtFZXNXRjRQTzk1ZXVGWmkwcGozMmx1MVJuZm9XbFhYSDVDNzhKalFQdXN0RU5pcmU3RTJyMEpJYgphWVBQSmpubVNNMXBLSXNnejl4bmNvTDFpSTdlK3RxQXBjcXRVcENwQVhoZ0YvbnlUNnZCT1BBaVMyNjdKcDBpCjBZU1VxMkc2TFovNlowWk9aT2ppb0NZOEN2U0ZJbjU1RUROUmUvL1U0QTV2SjgzVW1YMHRxTW1aUWhNZUtYaGYKa1NCWGRrZmlBcXVSNDNOVWxBcDNwT3NRUmxBU1ExRUNTek1yblE5MHNzYlRCWnF3djVXSCtKREZ2aTZLVWtTcwpxYmtUbWFvWEoyaS9hT1BtTWJJNUZNVm1zcWwvRk1mTXJ1K0IrZU1vUkpPeE53Nmx0VnlGOUJaaTNjZ29aQzlQClQrdWp4UUlEQVFBQm95Y3dKVEFPQmdOVkhROEJBZjhFQkFNQ0JhQXdFd1lEVlIwbEJBd3dDZ1lJS3dZQkJRVUgKQXdJd0RRWUpLb1pJaHZjTkFRRUxCUUFEZ2dFQkFKcXU0OXdXWkF4QzNxRCtiYVA0TE1maHFpZWNJeXZkSEc2YwpNU3RaUzNpZmt3a0JYNEN4QnJFaWh2a051TEpGNHI4dS9aT1Q0SStYVFpMUG8xTFYzRlNadU9Hc0JiYXJJVHpLCnA5a3ZaQ0tER1ltTng0OVg4aDEvcFpqS3VDWTNUSUF4VTE1VDZmK2pXOVhKa3JNRzFOeDdRVytySWs1VWpKa2YKemlTb2ZNY3VsM3QxOGMyQUUwYitob2RqNHVhMEd4N2U1ZkxwNjd3YUxERHZNdVQwTHNEelZkWWdGK2M1UWhmNQpBa1RsVFRqWGtZckRhbUpPKzRZN080UTd6NkpEUnNVK1ZiTU53S0NocCtzNGYzeS82SkdGSnZYaHgrNVZoRURZCnJ6TDZTTXIwR3M0MG9sNXNSUUNKZHpUUFA4dDZtdGdZVmlLeXJPeFlNcm5CTUtNN1VvRT0KLS0tLS1FTkQgQ0VSVElGSUNBVEUtLS0tLQo= + client-key-data: LS0tLS1CRUdJTiBSU0EgUFJJVkFURSBLRVktLS0tLQpNSUlFb2dJQkFBS0NBUUVBd2plNDYxc2IwajlEOVBYbytzZXk4N2wrRWVzV0Y0UE85NWV1RlppMHBqMzJsdTFSCm5mb1dsWFhINUM3OEpqUVB1c3RFTmlyZTdFMnIwSkliYVlQUEpqbm1TTTFwS0lzZ3o5eG5jb0wxaUk3ZSt0cUEKcGNxdFVwQ3BBWGhnRi9ueVQ2dkJPUEFpUzI2N0pwMGkwWVNVcTJHNkxaLzZaMFpPWk9qaW9DWThDdlNGSW41NQpFRE5SZS8vVTRBNXZKODNVbVgwdHFNbVpRaE1lS1hoZmtTQlhka2ZpQXF1UjQzTlVsQXAzcE9zUVJsQVNRMUVDClN6TXJuUTkwc3NiVEJacXd2NVdIK0pERnZpNktVa1NzcWJrVG1hb1hKMmkvYU9QbU1iSTVGTVZtc3FsL0ZNZk0KcnUrQitlTW9SSk94Tnc2bHRWeUY5QlppM2Nnb1pDOVBUK3VqeFFJREFRQUJBb0lCQUNJZVdkejJ0Mjk2Nzd4RAp5dmJyU0JPcTNXdldhWjRkNktqME8zL053TWFIa2g4M2Q2UVNBQStuamtNV3dmTVFLRWMvV0M5UDNyT1NmWUY1CmVWbFM3M3dlcGNiYVZ3UHBWUTFQQWRsTENrbEFHQW5uZ3J3ZFc4OXFYRlpHeUZMTjlQUnNEdGlxenN1RG0xc1EKTmNLcTBOYytwczlIRUYwK0s1MXNrQXRrVEIzOFFtQjVyTDlCU0UyMkpHQytqUU1IMnk1Y2FaaGlocXRtSEg2OQpyN012WUFlamFDNVlGVDY0L2pMeFNncjM1cUlhKzBqdWxheExyT2xtYURXa2Nva0xieThPN0JUSTRkTmh5bHluCmg4ZWhYUCtvUVkzckJmR21GZG1OZTBNM0R3UGF2TkF1VVRQNkhMQTBOdXczZ0ZaYjdhU0tJU1Q1QWxiaFlzT24KcEZDTjFLRUNnWUVBMjFCY0U5elhqQVdWeWdnVmJYZ3pDRE9wL0pwRktYSE9LNHZVb2RHNHIwSGliUXBWUkJkMQpWSkxRVmQyZW1SSHRlczlmbjFvdnJkZFRWYUpzNXhWWUxiZmR2V2wyYXBnc2UyL1FDRGZ6Y3IzamhNQlNla1B2CjFJd01DOFdHeElWTG85N1VwUkxET0U0cnlxTDJzaUJLbEhhYXdaV1BuVlAzYnorenFXNUtGbTBDZ1lFQTRyU3IKdlpFbDdSdm5wbWhJdjlWQXNjeUtkYUxmRnpTdzFuMnBITWs3UDF6bWJaMldWR2U1MldldHNQNCtrOEZTNG04SQpIc1QwOTMwM2o0SkZ4YWp0b2dtOU1RRnE3TDMvY0tVdEpSTVd6QW95dm5oVVBvRE8vYXBKL2VNeHIrdTdkREhFClFFTlAzMVVjT1daU3lKSHNlRHNNY1JKby9iVlFoUlozS0ROZHk3a0NnWUE3MEZUc2plU3pxYXBLcVoyK2QzUGoKbnNPVHd6ZHRzRDQ4bml4bDNkN3kzWk0xamdYblJrYVh4RnJSc0ZuYkFZcTFYZTJFZG9KZWRVV2pLMk5zT3VRTAp4QVBUN3ZsKzVQWHN6SGYrWmRRZHpUQktPbkhFS3RjMEx1WHlKL016a2U4cFNGTFNtcVZucTlwQnIrUjhmRllhCjI2WWxlZmJyUDhWU01CdDk4RGlBbVFLQmdBVWI5MGJsYjRwaGQ1NExlYUJCS1IwWXRBSWtzb3h1VnBIdThSSEMKQTBEUlVpd2tRaEFTNm1CWTh0UXJWck96eHE5dHV5d2VXanI5cW5Qa2hyZ0dyNXhZUmRoRjVPZ0MvQy9JdVRTOQpzbVRVMGdIeTZrc2lVZ2ZyZjVGbVBtZHRrNkx4d0MrR2xOVStzTTBtWGpWQS9LaFZCRm5FQlhPNlUxODhlMkQvCmoxeVpBb0dBVmdZd0ZSRTBDUW81YUdFZXNLWDYvWVNEcHJZMjBLTzJROTV4RUVTRms0Ujl0WDI4TjhRcitBQ0EKUzI2eWZrY21vSjNXb3lGYVBSTlBUd0xvRVcyc0dVWmdCTWF4SzRHcy9HeUtXMzk4aGRmR0h2VGFwamNac0FDcgppeTFGams4dkwybGFrSTlMN0hzRjY0bHhCaG5QQmJtY3pMQW10bkZFNjY4cWhoMXc5cnM9Ci0tLS0tRU5EIFJTQSBQUklWQVRFIEtFWS0tLS0tCg== \ No newline at end of file diff --git a/dubhe-server/common-k8s/src/main/resources/mapper/K8sTaskMapper.xml b/dubhe-server/common-k8s/src/main/resources/mapper/K8sTaskMapper.xml new file mode 100644 index 0000000..89e8bc8 --- /dev/null +++ b/dubhe-server/common-k8s/src/main/resources/mapper/K8sTaskMapper.xml @@ -0,0 +1,200 @@ + + + + + + id,namespace,resource_name,task_yaml,business,apply_unix_time,apply_display_time,apply_status, + stop_unix_time,stop_display_time,stop_status,create_time,create_user_id,update_time,update_user_id,deleted + + + + + insert into k8s_task + + + namespace, + + + resource_name, + + + task_yaml, + + + business, + + + apply_unix_time, + + + apply_display_time, + + + apply_status, + + + stop_unix_time, + + + stop_display_time, + + + stop_status, + + + create_time, + + + create_user_id, + + + update_time, + + + update_user_id, + + + deleted, + + + + + #{namespace}, + + + #{resourceName}, + + + #{taskYaml}, + + + #{business}, + + + #{applyUnixTime}, + + + #{applyDisplayTime}, + + + #{applyStatus}, + + + #{stopUnixTime}, + + + #{stopDisplayTime}, + + + #{stopStatus}, + + + #{createTime}, + + + #{createUserId}, + + + #{updateTime}, + + + #{updateUserId}, + + + #{deleted}, + + + ON DUPLICATE KEY UPDATE + + + task_yaml = #{taskYaml}, + + + business = #{business}, + + + apply_unix_time = #{applyUnixTime}, + + + apply_display_time = #{applyDisplayTime}, + + + apply_status = #{applyStatus}, + + + stop_unix_time = #{stopUnixTime}, + + + stop_display_time = #{stopDisplayTime}, + + + stop_status = #{stopStatus}, + + + create_time = #{createTime}, + + + create_user_id = #{createUserId}, + + + update_time = #{updateTime}, + + + update_user_id = #{updateUserId}, + + + deleted = #{deleted}, + + + + + + \ No newline at end of file diff --git a/dubhe-server/common-recycle/pom.xml b/dubhe-server/common-recycle/pom.xml new file mode 100644 index 0000000..e4c3631 --- /dev/null +++ b/dubhe-server/common-recycle/pom.xml @@ -0,0 +1,49 @@ + + + + server + org.dubhe + 0.0.1-SNAPSHOT + + 4.0.0 + common-recycle + 0.0.1-SNAPSHOT + 垃圾回收 recycle 通用模块 + Dubhe recycle Common + + + + org.dubhe.biz + base + ${org.dubhe.biz.base.version} + + + org.dubhe.biz + file + ${org.dubhe.biz.file.version} + + + org.dubhe.biz + data-permission + ${org.dubhe.biz.data-permission.version} + + + org.dubhe.biz + redis + ${org.dubhe.biz.redis.version} + + + + org.dubhe.biz + data-response + ${org.dubhe.biz.data-response.version} + + + + + + + + \ No newline at end of file diff --git a/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/config/RecycleConfig.java b/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/config/RecycleConfig.java new file mode 100644 index 0000000..b698b81 --- /dev/null +++ b/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/config/RecycleConfig.java @@ -0,0 +1,72 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.recycle.config; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +/** + * @description 垃圾回收机制配置常量 + * @date 2020-09-21 + */ +@Data +@Component +@ConfigurationProperties(prefix = "recycle.timeout") +public class RecycleConfig { + + /** + * 回收无效文件的默认有效时长 + */ + private Integer date; + + /** + * 用户上传文件至临时路径下后文件最大有效时长,以小时为单位 + */ + private Integer fileValid; + + /** + * 用户删除某一算法后,其算法文件最大有效时长,以天为单位 + */ + private Integer algorithmValid; + + /** + * 用户删除某一模型后,其模型文件最大有效时长,以天为单位 + */ + private Integer modelValid; + + /** + * 用户删除训练任务后,其训练管理文件最大有效时长,以天为单位 + */ + private Integer trainValid; + + /** + * 用户删除度量文件后,其度量文件最大有效时长,以天为单位 + */ + private Integer measureValid; + + /** + * 用户删除镜像后,其镜像最大有效时长,以天为单位 + */ + private Integer imageValid; + + /** + * 回收serving相关文件后,回收文件最大有效时长,以天为单位 + */ + private Integer servingValid; + +} \ No newline at end of file diff --git a/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/config/RecycleMvcConfig.java b/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/config/RecycleMvcConfig.java new file mode 100644 index 0000000..6ba1e0d --- /dev/null +++ b/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/config/RecycleMvcConfig.java @@ -0,0 +1,47 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.recycle.config; + + +import org.dubhe.recycle.interceptor.RecycleCallInterceptor; +import org.dubhe.recycle.utils.RecycleTool; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.InterceptorRegistration; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +import javax.annotation.Resource; + +/** + * @description 资源回收 Mvc Config + * @date 2021-01-21 + */ +@Configuration +public class RecycleMvcConfig implements WebMvcConfigurer { + + @Resource + private RecycleCallInterceptor recycleCallInterceptor; + + @Override + public void addInterceptors(InterceptorRegistry registry) { + InterceptorRegistration registration = registry.addInterceptor(recycleCallInterceptor); + // 拦截配置 + registration.addPathPatterns(RecycleTool.MATCH_RECYCLE_PATH); + } + +} diff --git a/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/dao/RecycleDetailMapper.java b/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/dao/RecycleDetailMapper.java new file mode 100644 index 0000000..9a801f3 --- /dev/null +++ b/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/dao/RecycleDetailMapper.java @@ -0,0 +1,27 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.recycle.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.dubhe.recycle.domain.entity.RecycleDetail; + +/** + * @description 回收垃圾详情 mapper + * @date 2021-02-03 + */ +public interface RecycleDetailMapper extends BaseMapper { +} diff --git a/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/dao/RecycleMapper.java b/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/dao/RecycleMapper.java new file mode 100644 index 0000000..cbbbe74 --- /dev/null +++ b/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/dao/RecycleMapper.java @@ -0,0 +1,27 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.recycle.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.dubhe.recycle.domain.entity.Recycle; + +/** + * @description 回收垃圾任务 mapper + * @date 2021-02-03 + */ +public interface RecycleMapper extends BaseMapper { +} diff --git a/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/domain/dto/RecycleCreateDTO.java b/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/domain/dto/RecycleCreateDTO.java new file mode 100644 index 0000000..678bab9 --- /dev/null +++ b/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/domain/dto/RecycleCreateDTO.java @@ -0,0 +1,111 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.recycle.domain.dto; + +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; +import org.dubhe.biz.db.entity.BaseEntity; +import org.dubhe.recycle.domain.entity.Recycle; +import org.dubhe.recycle.domain.entity.RecycleDetail; +import org.springframework.beans.BeanUtils; + +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +/** + * @description 创建垃圾回收任务DTO + * @date 2021-02-03 + */ +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Accessors(chain = true) +public class RecycleCreateDTO extends BaseEntity implements Serializable { + + private static final long serialVersionUID = 1L; + + private Long id; + + @ApiModelProperty(value = "回收模块", required = true) + @NotNull(message = "回收模块不能为空") + private Integer recycleModule; + + @ApiModelProperty(value = "回收延迟时间,以天为单位") + private Integer recycleDelayDate; + + @ApiModelProperty(value = "回收定制化方式") + private String recycleCustom; + + @ApiModelProperty(value = "回收说明") + private String recycleNote; + + @ApiModelProperty(value = "回收备注") + private String remark; + + @ApiModelProperty(value = "还原定制化方式") + private String restoreCustom; + + @ApiModelProperty(value = "回收任务详情") + @NotEmpty(message = "回收任务详情不能为空") + private List detailList; + + /** + * 添加 RecycleDetailCreateDTO + * @param detailCreateDTO RecycleDetailCreateDTO + */ + public void addRecycleDetailCreateDTO(RecycleDetailCreateDTO detailCreateDTO){ + if (detailList == null){ + detailList = new ArrayList<>(); + } + detailList.add(detailCreateDTO); + } + + /** + * 创建 RecycleCreateDTO + * @param recycle 回收任务 + * @return RecycleCreateDTO + */ + public static RecycleCreateDTO recycleTaskCreateDTO(Recycle recycle){ + RecycleCreateDTO instance = new RecycleCreateDTO(); + if (recycle != null){ + BeanUtils.copyProperties(recycle, instance); + } + return instance; + } + + /** + * 添加任务详情 + * @param recycleDetailList 任务详情 + */ + public void setDetailList(List recycleDetailList) { + detailList = new ArrayList<>(); + for (RecycleDetail recycleDetail:recycleDetailList){ + recycleDetail.setUpdateUserId(this.getUpdateUserId()); + detailList.add(RecycleDetailCreateDTO.recycleDetailCreateDTO(recycleDetail)); + } + } + +} + diff --git a/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/domain/dto/RecycleDetailCreateDTO.java b/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/domain/dto/RecycleDetailCreateDTO.java new file mode 100644 index 0000000..fcb44d8 --- /dev/null +++ b/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/domain/dto/RecycleDetailCreateDTO.java @@ -0,0 +1,82 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.recycle.domain.dto; + +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; +import org.dubhe.biz.db.entity.BaseEntity; +import org.dubhe.recycle.domain.entity.RecycleDetail; +import org.springframework.beans.BeanUtils; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; +import java.io.Serializable; + +/** + * @description 创建垃圾回收任务详情DTO + * @date 2021-02-03 + */ +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Accessors(chain = true) +public class RecycleDetailCreateDTO extends BaseEntity implements Serializable { + + private static final long serialVersionUID = 1L; + + private Long id; + + private Long recycleId; + + @ApiModelProperty(value = "回收类型(0文件,1数据库表数据)", required = true) + @NotNull(message = "回收类型不能为空") + private Integer recycleType; + + @ApiModelProperty(value = "回收条件(回收表数据sql、回收文件绝对路径)", required = true) + @NotBlank(message = "回收条件不能为空") + private String recycleCondition; + + @ApiModelProperty(value = "回收说明") + private String recycleNote; + + @ApiModelProperty(value = "回收备注") + private String remark; + + @ApiModelProperty(value = "回收状态") + private Integer recycleStatus; + + + /** + * 创建 RecycleDetailCreateDTO + * @param recycleDetail 回收任务详情 + * @return RecycleDetailCreateDTO + */ + public static RecycleDetailCreateDTO recycleDetailCreateDTO(RecycleDetail recycleDetail){ + RecycleDetailCreateDTO instance = new RecycleDetailCreateDTO(); + if (recycleDetail != null){ + BeanUtils.copyProperties(recycleDetail, instance); + } + return instance; + } + +} + diff --git a/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/domain/dto/RecycleTaskDeleteDTO.java b/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/domain/dto/RecycleTaskDeleteDTO.java new file mode 100644 index 0000000..16db3d5 --- /dev/null +++ b/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/domain/dto/RecycleTaskDeleteDTO.java @@ -0,0 +1,38 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.recycle.domain.dto; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import javax.validation.constraints.NotEmpty; +import java.io.Serializable; +import java.util.List; + +/** + * @description 回收任务执行列表 + * @date 2021-01-27 + */ +@Data +public class RecycleTaskDeleteDTO implements Serializable { + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "待回收任务ID") + @NotEmpty(message = "请选择回收任务") + private List recycleTaskIdList; + +} diff --git a/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/domain/dto/RecycleTaskQueryDTO.java b/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/domain/dto/RecycleTaskQueryDTO.java new file mode 100644 index 0000000..ec74398 --- /dev/null +++ b/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/domain/dto/RecycleTaskQueryDTO.java @@ -0,0 +1,52 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.recycle.domain.dto; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import lombok.experimental.Accessors; +import org.dubhe.biz.db.base.PageQueryBase; + +import java.io.Serializable; +import java.util.List; + +/** + * @description 回收任务列表查询条件 + * @date 2020-09-23 + */ +@Data +@Accessors(chain = true) +public class RecycleTaskQueryDTO extends PageQueryBase implements Serializable { + private static final long serialVersionUID = 2016225581479036412L; + + /** + * 具体值参考RecycleStatusEnum + */ + @ApiModelProperty(value = "回收任务状态(0:待回收,1:已回收,2:回收失败,3:回收中,4:还原中,5:已还原)") + private Integer recycleStatus; + + @ApiModelProperty(value = "回收类型(0文件,1数据库表数据)") + private Integer recycleType; + + @ApiModelProperty(value = "回收模块") + private String recycleModel; + + @ApiModelProperty(value = "回收任务ID") + private List recycleTaskIdList; + + +} diff --git a/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/domain/entity/Recycle.java b/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/domain/entity/Recycle.java new file mode 100644 index 0000000..9c80153 --- /dev/null +++ b/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/domain/entity/Recycle.java @@ -0,0 +1,91 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.recycle.domain.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.experimental.Accessors; +import org.dubhe.biz.db.entity.BaseEntity; + +import java.sql.Timestamp; + +/** + * @description 垃圾回收主表 + * @date 2021-02-03 + */ +@Data +@EqualsAndHashCode(callSuper = true) +@Accessors(chain = true) +@TableName(value = "recycle") +public class Recycle extends BaseEntity { + + @TableId(value = "id", type = IdType.AUTO) + private Long id; + + /** + * 回收模块 + */ + @TableField(value = "recycle_module") + private Integer recycleModule; + + /** + * 回收延迟时间,以天为单位 + */ + @TableField(value = "recycle_delay_date") + private Timestamp recycleDelayDate; + + /** + * 回收定制化方式 + */ + @TableField(value = "recycle_custom") + private String recycleCustom; + + /** + * 回收状态 + */ + @TableField(value = "recycle_status") + private Integer recycleStatus; + + /** + * 回收说明 + */ + @TableField(value = "recycle_note") + private String recycleNote; + + /** + * 备注 + */ + @TableField(value = "remark") + private String remark; + + /** + * 回收响应信息 + */ + @TableField(value = "recycle_response") + private String recycleResponse; + + /** + * 还原定制化方式 + */ + @TableField(value = "restore_custom") + private String restoreCustom; + +} diff --git a/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/domain/entity/RecycleDetail.java b/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/domain/entity/RecycleDetail.java new file mode 100644 index 0000000..e4fe2b6 --- /dev/null +++ b/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/domain/entity/RecycleDetail.java @@ -0,0 +1,80 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.recycle.domain.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.experimental.Accessors; +import org.dubhe.biz.db.entity.BaseEntity; + +/** + * @description 垃圾回收详情表 + * @date 2021-02-03 + */ +@Data +@EqualsAndHashCode(callSuper = true) +@Accessors(chain = true) +@TableName(value = "recycle_detail") +public class RecycleDetail extends BaseEntity { + + @TableId(value = "id", type = IdType.AUTO) + private Long id; + + @TableField(value = "recycle_id") + private Long recycleId; + + /** + * 回收类型(0文件,1数据库表数据 + */ + @TableField(value = "recycle_type") + private Integer recycleType; + + /** + * 回收条件(回收表数据sql、回收文件绝对路径) + */ + @TableField(value = "recycle_condition") + private String recycleCondition; + + /** + * 回收状态 + */ + @TableField(value = "recycle_status") + private Integer recycleStatus; + + /** + * 回收说明 + */ + @TableField(value = "recycle_note") + private String recycleNote; + + /** + * 备注 + */ + @TableField(value = "remark") + private String remark; + + /** + * 回收响应信息 + */ + @TableField(value = "recycle_response") + private String recycleResponse; + +} diff --git a/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/enums/RecycleModuleEnum.java b/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/enums/RecycleModuleEnum.java new file mode 100644 index 0000000..11cb250 --- /dev/null +++ b/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/enums/RecycleModuleEnum.java @@ -0,0 +1,99 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.recycle.enums; + +import org.dubhe.biz.base.constant.MagicNumConstant; +import org.dubhe.biz.base.exception.BusinessException; + +import java.util.LinkedHashMap; +import java.util.Map; + +import static org.dubhe.biz.base.constant.ApplicationNameConst.*; +/** + * @description 垃圾回收模块枚举 + * @date 2020-09-17 + */ +public enum RecycleModuleEnum { + + + BIZ_TRAIN(1, "训练任务管理",SERVER_TRAIN), + BIZ_DATASET(2, "数据集管理",SERVER_DATA), + BIZ_NOTEBOOK(3, "Notebook",SERVER_NOTEBOOK), + BIZ_ALGORITHM(4, "算法管理",SERVER_ALGORITHM), + BIZ_IMAGE(5, "镜像管理",SERVER_IMAGE), + BIZ_MODEL_OPT(6, "模型优化",SERVER_OPTIMIZE), + BIZ_MODEL(7, "模型管理",SERVER_MODEL), + BIZ_DATAMEDICINE(8, "医学影像",SERVER_DATA_DCM), + BIZ_MEASURE(9, "度量管理",SERVER_MEASURE), + BIZ_SERVING(10, "云端Serving", SERVER_SERVING); + + private Integer value; + + private String desc; + + /** + * 模块服务名 + */ + private String server; + + RecycleModuleEnum(Integer value, String desc,String server) { + this.value = value; + this.desc = desc; + this.server = server; + } + + public Integer getValue() { + return this.value; + } + + public String getDesc() { + return desc; + } + + public void setDesc(String desc) { + this.desc = desc; + } + + /** + * 获取服务名 + * @param value 模块代号 + * @return 服务 + */ + public static String getServer(int value){ + for (RecycleModuleEnum recycleModuleEnum:RecycleModuleEnum.values()){ + if (value == recycleModuleEnum.getValue()){ + if (recycleModuleEnum.server == null){ + throw new BusinessException(recycleModuleEnum.desc + " 服务未配置服务名!"); + } + return recycleModuleEnum.server; + } + } + throw new BusinessException(value+" 服务不存在!"); + } + + /** + * 模块代号,模块名称 映射 + */ + public static final Map RECYCLE_MODULE_MAP; + static { + RECYCLE_MODULE_MAP = new LinkedHashMap<>(MagicNumConstant.SIXTEEN); + for (RecycleModuleEnum recycleModuleEnum:RecycleModuleEnum.values()){ + RECYCLE_MODULE_MAP.put(recycleModuleEnum.value,recycleModuleEnum.desc); + } + } + +} diff --git a/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/enums/RecycleResourceEnum.java b/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/enums/RecycleResourceEnum.java new file mode 100644 index 0000000..5358662 --- /dev/null +++ b/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/enums/RecycleResourceEnum.java @@ -0,0 +1,93 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.recycle.enums; + +import lombok.Getter; + +/** + * @description 资源回收枚举类 + * @date 2020-10-10 + */ +@Getter +public enum RecycleResourceEnum { + + /** + * 数据集文件回收 + */ + DATASET_RECYCLE_FILE("datasetRecycleFile", "数据集文件回收"), + + /** + * 医学数据集文件回收 + */ + DATAMEDICINE_RECYCLE_FILE("dataMedicineRecycleFile", "数据集文件回收"), + + /** + * 数据集版本文件回收 + */ + DATASET_RECYCLE_VERSION_FILE("datasetRecycleVersionFile", "数据集版本文件回收"), + + /** + * 云端Serving在线服务输入文件回收 + */ + SERVING_RECYCLE_FILE("servingRecycleFile", "云端Serving在线服务文件回收"), + /** + * 云端Serving批量服务输入文件回收 + */ + BATCH_SERVING_RECYCLE_FILE("batchServingRecycleFile", "云端Serving批量服务文件回收"), + + /** + * 标签组文件回收 + */ + LABEL_GROUP_RECYCLE_FILE("labelGroupRecycleFile", "标签组文件回收"), + + /** + * 度量文件回收 + */ + MEASURE_RECYCLE_FILE("measureRecycleFile", "度量文件回收"), + + /** + * 镜像回收 + */ + IMAGE_RECYCLE_FILE("imageRecycleFile", "镜像回收"), + + /** + * 算法文件回收 + */ + ALGORITHM_RECYCLE_FILE("algorithmRecycleFile", "算法文件回收"), + + /** + * 模型文件回收 + */ + MODEL_RECYCLE_FILE("modelRecycleFile", "模型文件回收"), + /** + * 模型优化文件回收 + */ + MODEL_OPT_RECYCLE_FILE("modelOptRecycleFile","模型优化文件回收"), + ; + + private String className; + + private String message; + + RecycleResourceEnum(String className, String message) { + this.className = className; + this.message = message; + } + + +} diff --git a/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/enums/RecycleStatusEnum.java b/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/enums/RecycleStatusEnum.java new file mode 100644 index 0000000..9ffcadc --- /dev/null +++ b/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/enums/RecycleStatusEnum.java @@ -0,0 +1,57 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.recycle.enums; + +/** + * @description 垃圾回收状态 + * @date 2020-09-17 + */ +public enum RecycleStatusEnum { + + PENDING(0, "待删除"), + + SUCCEEDED(1, "已删除"), + FAILED(2, "删除失败"), + DOING(3,"删除中"), + + RESTORING(4,"还原中"), + RESTORED(5,"已还原"), + ; + + /** + * 编码 + */ + private Integer code; + + /** + * 描述 + */ + private String description; + + RecycleStatusEnum(int code, String description) { + this.code = code; + this.description = description; + } + + public Integer getCode() { + return code; + } + + public String getDescription() { + return description; + } +} diff --git a/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/enums/RecycleTypeEnum.java b/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/enums/RecycleTypeEnum.java new file mode 100644 index 0000000..45d5760 --- /dev/null +++ b/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/enums/RecycleTypeEnum.java @@ -0,0 +1,45 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.recycle.enums; + +/** + * @description 垃圾回收类型 + * @date 2020-09-17 + */ +public enum RecycleTypeEnum { + + FILE(0, "文件"), + TABLE_DATA(1, "表数据"); + + private Integer code; + + private String type; + + + RecycleTypeEnum(Integer code, String type) { + this.code = code; + this.type = type; + } + + public Integer getCode() { + return code; + } + + public String getType() { + return type; + } +} diff --git a/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/global/AbstractGlobalRecycle.java b/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/global/AbstractGlobalRecycle.java new file mode 100644 index 0000000..db335d2 --- /dev/null +++ b/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/global/AbstractGlobalRecycle.java @@ -0,0 +1,215 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.recycle.global; + +import org.dubhe.biz.base.constant.NumberConstant; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.dubhe.recycle.domain.dto.RecycleCreateDTO; +import org.dubhe.recycle.domain.dto.RecycleDetailCreateDTO; +import org.dubhe.recycle.domain.entity.Recycle; +import org.dubhe.recycle.domain.entity.RecycleDetail; +import org.dubhe.recycle.enums.RecycleStatusEnum; +import org.dubhe.recycle.service.CustomRecycleService; +import org.dubhe.recycle.service.RecycleService; +import org.springframework.beans.BeanUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.transaction.annotation.Transactional; + +import java.util.Objects; + +/** + * @description 数据集清理回收类 + * @date 2020-10-09 + */ +public abstract class AbstractGlobalRecycle implements CustomRecycleService { + + /** + * 回收服务 + */ + @Autowired + private RecycleService recycleService; + + /** + * 回收线程初始时间 + */ + private final ThreadLocal startTimeLocal = new ThreadLocal<>(); + + /** + * 重写自定义回收入口 + * 注意: + * 1:异步执行避免服务调用者等待 + * 2:不开启事务,避免大事务,且可以小事务分批执行 + * @param dto 资源回收创建对象 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public void recycle(RecycleCreateDTO dto) { + if (dto == null || dto.getId() == null){ + // 非法入参 + return; + } + long userId = dto.getUpdateUserId(); + try { + // 回收前置处理 + // 设置 线程回收开始时间 + startTimeLocal.set(System.currentTimeMillis()); + Recycle recycle = getRecycle(dto); + // 标记执行中 + recycleService.updateRecycle(recycle, RecycleStatusEnum.DOING,null,userId); + try { + // 回收业务详情 + clear(dto); + // 回收成功 + recycleService.updateRecycle(recycle, RecycleStatusEnum.SUCCEEDED,null,userId); + } catch (Exception e) { + // 回收失败 + LogUtil.error(LogEnum.GARBAGE_RECYCLE, "custom recycle {} error {},", recycle.getId(), e); + recycleService.updateRecycle(recycle, RecycleStatusEnum.FAILED,e.getMessage(),userId); + } + }finally { + // 清除 线程回收开始时间 + startTimeLocal.remove(); + } + } + + /** + * 清理回收详情 + * @param dto 资源回收创建对象 + */ + private void clear(RecycleCreateDTO dto){ + long userId = dto.getUpdateUserId(); + for (RecycleDetailCreateDTO detail:dto.getDetailList()) { + RecycleDetail recycleDetail = getRecycleDetail(detail); + if (RecycleStatusEnum.SUCCEEDED.getCode().equals(recycleDetail.getRecycleStatus())){ + // 跳过已删除成功任务详情 + continue; + } + recycleService.updateRecycleDetail(recycleDetail, RecycleStatusEnum.DOING,null,userId); + try { + boolean continued = clearDetail(detail, dto); + recycleService.updateRecycleDetail(recycleDetail, RecycleStatusEnum.SUCCEEDED, null, userId); + if (!continued){ + // 中断任务详情回收 + break; + } + }catch (Exception e) { + LogUtil.error(LogEnum.GARBAGE_RECYCLE, "custom recycle detail{} error {},", recycleDetail.getId(), e); + recycleService.updateRecycleDetail(recycleDetail, RecycleStatusEnum.FAILED,e.getMessage(),userId); + } + // 同步最新状态,以备this.addNewRecycleTask + detail.setRecycleStatus(recycleDetail.getRecycleStatus()); + } + } + + /** + * 单个回收详情清理 + * + * @param detail 数据清理详情参数 + * @param dto 资源回收创建对象 + * @return true 继续执行,false 中断任务详情回收(本次无法执行完毕,创建新任务到下次执行) + */ + protected abstract boolean clearDetail(RecycleDetailCreateDTO detail,RecycleCreateDTO dto) throws Exception; + + /** + * 获取Recycle + * @param recycleCreateDTO 数据清理参数 + * @return Recycle + */ + private Recycle getRecycle(RecycleCreateDTO recycleCreateDTO){ + Recycle recycle = new Recycle(); + BeanUtils.copyProperties(recycleCreateDTO, recycle); + return recycle; + } + + /** + * 获取RecycleDetail + * @param recycleDetailCreateDTO 数据清理详情参数 + * @return RecycleDetail + */ + private RecycleDetail getRecycleDetail(RecycleDetailCreateDTO recycleDetailCreateDTO){ + RecycleDetail recycleDetail = new RecycleDetail(); + BeanUtils.copyProperties(recycleDetailCreateDTO, recycleDetail); + return recycleDetail; + } + + + /** + * 超时校验 + * + * @return true: 未超时,可继续资源回收 false: 已超时 + */ + protected boolean validateOverTime() { + return (System.currentTimeMillis() - startTimeLocal.get()) / NumberConstant.NUMBER_1000 < getRecycleOverSecond(); + } + + + /** + * 初始化开始时间 + * + */ + protected void initOverTime() { + startTimeLocal.set(System.currentTimeMillis()); + } + + /** + * 新增回收任务 + * + * @param dto 数据清理参数 + */ + protected void addNewRecycleTask(RecycleCreateDTO dto) { + if (Objects.nonNull(dto)) { + recycleService.createRecycleTask(dto); + } + } + + /** + * 重写自定义还原入口 + * + * @param dto + */ + @Override + public void restore(RecycleCreateDTO dto){ + if (dto == null || dto.getId() == null){ + // 非法入参 + return; + } + long userId = dto.getUpdateUserId(); + Recycle recycle = getRecycle(dto); + // 标记还原中 + recycleService.updateRecycle(recycle, RecycleStatusEnum.RESTORING,null,userId); + try { + // 业务回收 + rollback(dto); + // 还原成功 + recycleService.updateRecycle(recycle, RecycleStatusEnum.RESTORED,null,userId); + } catch (Exception e) { + // 还原失败,回归初始状态 + recycleService.updateRecycle(recycle, RecycleStatusEnum.PENDING, e.getMessage(),userId); + // 抛出异常 + throw e; + } + } + + /** + * 业务数据还原 + * + * @param dto 数据还原参数 + */ + protected abstract void rollback(RecycleCreateDTO dto); + +} diff --git a/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/interceptor/RecycleCallInterceptor.java b/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/interceptor/RecycleCallInterceptor.java new file mode 100644 index 0000000..b4c5790 --- /dev/null +++ b/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/interceptor/RecycleCallInterceptor.java @@ -0,0 +1,57 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.recycle.interceptor; + +import org.dubhe.biz.base.utils.StringUtils; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.dubhe.recycle.utils.RecycleTool; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * @description 资源回收调用拦截器 + * @date 2021-01-21 + */ +@Component +public class RecycleCallInterceptor extends HandlerInterceptorAdapter { + + @Autowired + private RecycleTool recycleTool; + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { + String uri = request.getRequestURI(); + LogUtil.debug(LogEnum.GARBAGE_RECYCLE,"资源回收接收到请求,URI:{}",uri); + String token = request.getHeader(RecycleTool.RECYCLE_TOKEN); + if (StringUtils.isBlank(token)){ + LogUtil.warn(LogEnum.GARBAGE_RECYCLE,"资源回收没有token配置【{}】,URI:{}",RecycleTool.RECYCLE_TOKEN,uri); + return false; + } + boolean pass = recycleTool.validateToken(token); + if (!pass){ + LogUtil.warn(LogEnum.GARBAGE_RECYCLE,"资源回收token:【{}】 验证不通过,URI:{}",token,uri); + } + return pass; + } + +} diff --git a/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/rest/RecycleCallController.java b/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/rest/RecycleCallController.java new file mode 100644 index 0000000..55ccfef --- /dev/null +++ b/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/rest/RecycleCallController.java @@ -0,0 +1,70 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.recycle.rest; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import org.dubhe.biz.base.utils.SpringContextHolder; +import org.dubhe.biz.base.vo.DataResponseBody; +import org.dubhe.biz.dataresponse.factory.DataResponseFactory; +import org.dubhe.recycle.domain.dto.RecycleCreateDTO; +import org.dubhe.recycle.service.CustomRecycleService; +import org.dubhe.recycle.utils.RecycleTool; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +/** + * @description 资源回收远程调用处理类 + * @date 2021-01-21 + */ +@Api(tags = "通用:资源回收远程调用") +@RestController +@RequestMapping(RecycleTool.RECYCLE_CALL_PATH) +public class RecycleCallController { + + + @PostMapping(value = RecycleTool.BIZ_RECYCLE) + @ApiOperation("资源回收远程调用统一入口") + public DataResponseBody recycle(@ApiParam(type = "head") @RequestHeader(name= RecycleTool.RECYCLE_TOKEN) String token + , @Validated @RequestBody RecycleCreateDTO dto) { + CustomRecycleService customRecycleService = SpringContextHolder.getBean(dto.getRecycleCustom()); + if (customRecycleService == null){ + return DataResponseFactory.failed("本服务未实现自定义资源删除!"); + }else { + // 因作业量大,异步执行 + customRecycleService.recycle(dto); + return DataResponseFactory.successWithMsg("资源删除正在异步处理中。"); + } + } + + @PostMapping(value = RecycleTool.BIZ_RESTORE) + @ApiOperation("资源还原远程调用统一入口") + public DataResponseBody restore(@ApiParam(type = "head") @RequestHeader(name= RecycleTool.RECYCLE_TOKEN) String token + , @Validated @RequestBody RecycleCreateDTO dto) { + CustomRecycleService customRecycleService = SpringContextHolder.getBean(dto.getRestoreCustom()); + if (customRecycleService == null){ + return DataResponseFactory.failed("本服务未实现自定义资源还原!"); + }else { + // 同步执行 + customRecycleService.restore(dto); + return DataResponseFactory.successWithMsg("还原成功!"); + } + } + +} diff --git a/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/service/CustomRecycleService.java b/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/service/CustomRecycleService.java new file mode 100644 index 0000000..97d8d1a --- /dev/null +++ b/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/service/CustomRecycleService.java @@ -0,0 +1,55 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.recycle.service; + +import org.dubhe.biz.base.exception.BusinessException; +import org.dubhe.recycle.domain.dto.RecycleCreateDTO; +import org.springframework.scheduling.annotation.Async; + +/** + * @description 垃圾回收执行接口 + * @date 2021-01-20 + */ +public interface CustomRecycleService { + + /** + * 自定义回收入口 + * 注意: + * 1:异步执行避免服务调用者等待 + * 2:不开启事务,避免大事务,且可以小事务分批执行 + * @param dto 资源回收创建对象 + */ + @Async + void recycle(RecycleCreateDTO dto); + + /** + * 自定义回收超时时间(单位:秒) + * @return 默认60秒 + */ + default long getRecycleOverSecond(){ + return 60L; + } + + /** + * 还原资源回收 + * @param dto 资源回收创建对象 + */ + default void restore(RecycleCreateDTO dto){ + throw new BusinessException("还原资源回收暂未实现!"); + } + +} diff --git a/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/service/RecycleService.java b/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/service/RecycleService.java new file mode 100644 index 0000000..9995b69 --- /dev/null +++ b/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/service/RecycleService.java @@ -0,0 +1,58 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.recycle.service; + +import org.dubhe.recycle.domain.dto.RecycleCreateDTO; +import org.dubhe.recycle.domain.entity.Recycle; +import org.dubhe.recycle.domain.entity.RecycleDetail; +import org.dubhe.recycle.enums.RecycleStatusEnum; + +/** + * @description 通用回收垃圾 服务类 + * @date 2021-02-03 + */ +public interface RecycleService { + + + /** + * 创建垃圾回收任务 + * + * @param recycleCreateDTO 垃圾回收任务信息 + */ + void createRecycleTask(RecycleCreateDTO recycleCreateDTO); + + /** + * 修改回收任务状态 + * + * @param recycle 回收任务 + * @param statusEnum 回收状态 + * @param recycleResponse 回收响应 + * @param userId 操作用户 + */ + void updateRecycle(Recycle recycle, RecycleStatusEnum statusEnum, String recycleResponse, long userId); + + /** + * 修改回收任务详情状态 + * + * @param recycleDetail 回收任务详情 + * @param statusEnum 回收状态 + * @param recycleResponse 回收响应 + * @param userId 操作用户 + */ + void updateRecycleDetail(RecycleDetail recycleDetail, RecycleStatusEnum statusEnum, String recycleResponse, long userId); + +} diff --git a/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/service/impl/RecycleServiceImpl.java b/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/service/impl/RecycleServiceImpl.java new file mode 100644 index 0000000..2eb7801 --- /dev/null +++ b/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/service/impl/RecycleServiceImpl.java @@ -0,0 +1,165 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.recycle.service.impl; + +import cn.hutool.core.collection.CollectionUtil; +import org.dubhe.biz.base.constant.MagicNumConstant; +import org.dubhe.biz.base.context.UserContext; +import org.dubhe.biz.base.exception.BusinessException; +import org.dubhe.biz.base.service.UserContextService; +import org.dubhe.biz.base.utils.DateUtil; +import org.dubhe.biz.base.utils.StringUtils; +import org.dubhe.biz.file.api.FileStoreApi; +import org.dubhe.biz.file.config.NfsConfig; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.dubhe.recycle.config.RecycleConfig; +import org.dubhe.recycle.dao.RecycleDetailMapper; +import org.dubhe.recycle.dao.RecycleMapper; +import org.dubhe.recycle.domain.dto.RecycleCreateDTO; +import org.dubhe.recycle.domain.dto.RecycleDetailCreateDTO; +import org.dubhe.recycle.domain.entity.Recycle; +import org.dubhe.recycle.domain.entity.RecycleDetail; +import org.dubhe.recycle.enums.RecycleStatusEnum; +import org.dubhe.recycle.enums.RecycleTypeEnum; +import org.dubhe.recycle.service.RecycleService; +import org.springframework.beans.BeanUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import javax.annotation.Resource; +import java.sql.Timestamp; +import java.util.Objects; + +/** + * @description 通用垃圾回收 实现类 + * @date 2021-02-03 + */ +@Service +public class RecycleServiceImpl implements RecycleService { + + @Autowired + private RecycleMapper recycleMapper; + + @Autowired + private RecycleDetailMapper recycleDetailMapper; + + @Autowired + private RecycleConfig recycleConfig; + + @Autowired + private NfsConfig nfsConfig; + + @Autowired + private UserContextService userContextService; + + @Resource(name = "hostFileStoreApiImpl") + private FileStoreApi fileStoreApi; + + /** + * 创建垃圾回收任务 + * + * @param recycleCreateDTO 垃圾回收任务信息 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public void createRecycleTask(RecycleCreateDTO recycleCreateDTO) { + if (CollectionUtil.isEmpty(recycleCreateDTO.getDetailList())) { + throw new BusinessException("请添加回收详情!"); + } + //获取当前用户信息 + UserContext curUser = userContextService.getCurUser(); + //设置默认回收延迟时间 + if (recycleCreateDTO.getRecycleDelayDate() <= 0) { + recycleCreateDTO.setRecycleDelayDate(recycleConfig.getDate()); + } + for (RecycleDetailCreateDTO detail : recycleCreateDTO.getDetailList()) { + //如果是删除文件任务,校验根目录及系统环境 + if (Objects.equals(detail.getRecycleType(), RecycleTypeEnum.FILE.getCode()) && + fileStoreApi.formatPath(detail.getRecycleCondition()).startsWith(nfsConfig.getRootDir() + nfsConfig.getBucket())) { + LogUtil.error(LogEnum.GARBAGE_RECYCLE, "User {} created recycle task failed,file sourcePath :{} invalid", curUser.getUsername(), detail.getRecycleCondition()); + throw new BusinessException("创建回收文件任务失败"); + } + } + long createUserId = Objects.isNull(recycleCreateDTO.getCreateUserId()) ? curUser.getId() : recycleCreateDTO.getCreateUserId(); + long updateUserId = Objects.isNull(recycleCreateDTO.getUpdateUserId()) ? curUser.getId() : recycleCreateDTO.getUpdateUserId(); + // 组装回收任务 + Recycle recycle = new Recycle(); + BeanUtils.copyProperties(recycleCreateDTO, recycle); + recycle.setRecycleStatus(RecycleStatusEnum.PENDING.getCode()); + recycle.setCreateUserId(createUserId); + recycle.setUpdateUserId(updateUserId); + recycle.setRecycleDelayDate(DateUtil.getRecycleTime(recycleCreateDTO.getRecycleDelayDate())); + recycleMapper.insert(recycle); + // 组装任务详情 + for (RecycleDetailCreateDTO detail : recycleCreateDTO.getDetailList()) { + RecycleDetail recycleDetail = new RecycleDetail(); + BeanUtils.copyProperties(detail, recycleDetail); + recycleDetail.setRecycleId(recycle.getId()); + if (recycleDetail.getRecycleStatus() == null) { + recycleDetail.setRecycleStatus(RecycleStatusEnum.PENDING.getCode()); + } + recycleDetail.setCreateUserId(createUserId); + recycleDetail.setUpdateUserId(updateUserId); + recycleDetailMapper.insert(recycleDetail); + } + } + + /** + * 修改回收任务状态 + * + * @param recycle 回收任务 + * @param statusEnum 回收状态 + * @param recycleResponse 回收响应 + * @param userId 操作用户 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public void updateRecycle(Recycle recycle, RecycleStatusEnum statusEnum, String recycleResponse, long userId) { + recycle.setRecycleStatus(statusEnum.getCode()); + // 确保响应信息会刷新 + if (recycleResponse == null) { + recycleResponse = statusEnum.getDescription(); + } + recycle.setRecycleResponse(StringUtils.truncationString(recycleResponse, MagicNumConstant.FIVE_HUNDRED)); + recycle.setUpdateUserId(userId); + recycle.setRecycleDelayDate(new Timestamp(System.currentTimeMillis())); + recycleMapper.updateById(recycle); + } + + /** + * 修改回收任务详情状态 + * + * @param recycleDetail 回收任务详情 + * @param statusEnum 回收状态 + * @param recycleResponse 回收响应 + * @param userId 操作用户 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public void updateRecycleDetail(RecycleDetail recycleDetail, RecycleStatusEnum statusEnum, String recycleResponse, long userId) { + recycleDetail.setRecycleStatus(statusEnum.getCode()); + // 确保响应信息会刷新 + if (recycleResponse == null) { + recycleResponse = statusEnum.getDescription(); + } + recycleDetail.setRecycleResponse(StringUtils.truncationString(recycleResponse, MagicNumConstant.FIVE_HUNDRED)); + recycleDetail.setUpdateUserId(userId); + recycleDetailMapper.updateById(recycleDetail); + } +} diff --git a/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/utils/RecycleTool.java b/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/utils/RecycleTool.java new file mode 100644 index 0000000..466ff38 --- /dev/null +++ b/dubhe-server/common-recycle/src/main/java/org/dubhe/recycle/utils/RecycleTool.java @@ -0,0 +1,241 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.recycle.utils; + +import cn.hutool.core.date.DateField; +import cn.hutool.core.date.DatePattern; +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.util.RandomUtil; +import cn.hutool.core.util.StrUtil; +import org.dubhe.biz.base.constant.AuthConst; +import org.dubhe.biz.base.constant.MagicNumConstant; +import org.dubhe.biz.base.constant.ResponseCode; +import org.dubhe.biz.base.constant.StringConstant; +import org.dubhe.biz.base.exception.BusinessException; +import org.dubhe.biz.base.utils.AesUtil; +import org.dubhe.biz.base.utils.StringUtils; +import org.dubhe.biz.file.api.FileStoreApi; +import org.dubhe.biz.file.api.impl.ShellFileStoreApiImpl; +import org.dubhe.biz.file.utils.IOUtil; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.dubhe.recycle.enums.RecycleModuleEnum; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import javax.annotation.Resource; +import java.io.BufferedReader; +import java.io.File; +import java.io.InputStreamReader; +import java.util.Date; + +/** + * @description 资源回收工具类 + * @date 2021-01-21 + */ +@Component +public class RecycleTool { + + /** + * token秘钥 + */ + @Value("${recycle.call.token.secret-key}") + private String secretKey; + /** + * token超时时间 + */ + @Value("${recycle.call.token.expire-seconds}") + private Integer expireSeconds; + + /** + * 资源无效文件临时存放目录(默认/tmp/empty_) + */ + @Value("${recycle.file-tmp-path.recycle:/tmp/empty_}") + private String recycleFileTmpPath; + + + @Resource(name = "hostFileStoreApiImpl") + private FileStoreApi fileStoreApi; + + @Value("${storage.file-store}") + private String ip; + + @Value("${data.server.userName}") + private String userName; + + /** + * 资源回收授权token + */ + public static final String RECYCLE_TOKEN = AuthConst.COMMON_TOKEN; + /** + * 路径 + */ + public static final String RECYCLE_CALL_PATH = StringConstant.RECYCLE_CALL_URI; + /** + * 回收业务 + */ + public static final String BIZ_RECYCLE = "recycle"; + /** + * 还原业务 + */ + public static final String BIZ_RESTORE = "restore"; + /** + * 权限匹配地址 + */ + public static final String MATCH_RECYCLE_PATH = RECYCLE_CALL_PATH + "**"; + + + /** + * 生成token + * + * @return token + */ + public String generateToken() { + String expireTime = DateUtil.format( + DateUtil.offset(new Date(), DateField.SECOND, expireSeconds), + DatePattern.PURE_DATETIME_PATTERN + ); + return AesUtil.encrypt(expireTime, secretKey); + } + + /** + * 验证token + * + * @param token 待校验token + * @return true token有效 false 无效 + */ + public boolean validateToken(String token) { + String expireTime = AesUtil.decrypt(token, secretKey); + if (StringUtils.isEmpty(expireTime)) { + return false; + } + String nowTime = DateUtil.format( + new Date(), + DatePattern.PURE_DATETIME_PATTERN + ); + return expireTime.compareTo(nowTime) > 0; + } + + + /** + * 获取调用地址 + * + * @param model 模块代号 RecycleModuleEnum.value + * @param biz 模块业务 + * @return String 回调地址 + */ + public static String getCallUrl(int model, String biz) { + return "http://" + RecycleModuleEnum.getServer(model) + RECYCLE_CALL_PATH + biz; + } + + /** + * 生成回收说明 + * @param baseNote 基本说明信息 + * @param bizId 业务ID + * @return string回收说明 + */ + public static String generateRecycleNote(String baseNote, long bizId) { + return String.format("%s ID:%d", baseNote, bizId); + } + + /** + * 生成回收说明 + * @param baseNote 基本说明信息 + * @param bizId 业务ID + * @return string回收说明 + */ + public static String generateRecycleNote(String baseNote, String name, long bizId) { + return String.format("%s name:%s ID:%d", baseNote, name, bizId); + } + + /** + * 实时删除临时目录完整路径无效文件 + * + * @param sourcePath 删除路径 + */ + public void delTempInvalidResources(String sourcePath) { + String resMsg = deleteFileByCMD(sourcePath, RandomUtil.randomString(MagicNumConstant.TWO)); + if (StrUtil.isNotEmpty(resMsg)) { + throw new BusinessException(ResponseCode.ERROR, resMsg); + } + } + + + /** + * 回收天枢一站式平台中的无效文件资源 + * 处理方式:获取到回收任务表中的无效文件路径,通过linux命令进行具体删除 + * 文件路径必须满足格式如:/nfs/当前系统环境/具体删除的文件或文件夹(至少三层目录) + * + * @param recycleConditionPath 文件回收绝对路径 + * @param randomPath emptyDir目录补偿位置 + * @return String 回收任务失败返回的失败信息 + */ + private String deleteFileByCMD(String recycleConditionPath, String randomPath) { + LogUtil.info(LogEnum.GARBAGE_RECYCLE, "RecycleTool deleteFileByCMD recycleConditionPath:{}, randomPath:{}", recycleConditionPath, randomPath); + + String sourcePath = fileStoreApi.formatPath(recycleConditionPath + File.separator); + //判断该路径是否存在文件或文件夹 + String nfsBucket = fileStoreApi.formatPath(fileStoreApi.getRootDir() + fileStoreApi.getBucket() + File.separator); + sourcePath = sourcePath.startsWith(nfsBucket) ? sourcePath : fileStoreApi.formatPath(nfsBucket + sourcePath); + Process process = null; + try { + if (sourcePath.length() > nfsBucket.length()) { + String emptyDir = recycleFileTmpPath + randomPath + StrUtil.SLASH; + LogUtil.info(LogEnum.GARBAGE_RECYCLE, "recycle task sourcePath:{},emptyDir:{}", sourcePath, emptyDir); + process = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", String.format(ShellFileStoreApiImpl.DEL_COMMAND, userName, ip, emptyDir, emptyDir, sourcePath, emptyDir, sourcePath)}); + } + return processRecycle(process); + + } catch (Exception e) { + LogUtil.error(LogEnum.GARBAGE_RECYCLE, "文件资源回收失败! Exception:{}", e); + return "文件资源回收失败! sourcePath:" + sourcePath + " Exception:" + e.getMessage(); + } + + } + + /** + * 执行服务器命令 + * + * @param process Process对象 + * @return null 成功执行,其他:异常结束信息 + */ + public String processRecycle(Process process) { + InputStreamReader stream = new InputStreamReader(process.getErrorStream()); + BufferedReader reader = new BufferedReader(stream); + StringBuilder errMessage = new StringBuilder(); + try { + while (reader.read() != MagicNumConstant.NEGATIVE_ONE) { + errMessage.append(reader.readLine()); + } + int status = process.waitFor(); + if (status == 0) { + // 成功 + return null; + } else { + // 失败 + LogUtil.info(LogEnum.GARBAGE_RECYCLE, "recycleSourceIsOk is failure,errorMsg:{},processStatus:{}", errMessage.toString(), status); + return errMessage.length() > 0 ? errMessage.toString() : "文件删除失败!"; + } + } catch (Exception e) { + LogUtil.error(LogEnum.GARBAGE_RECYCLE, "recycleSourceIsOk is failure: {} ", e); + return e.getMessage(); + } finally { + IOUtil.close(reader, stream); + } + } +} diff --git a/dubhe-server/deploy-base.sh b/dubhe-server/deploy-base.sh new file mode 100644 index 0000000..fff94ba --- /dev/null +++ b/dubhe-server/deploy-base.sh @@ -0,0 +1,44 @@ +#!/bin/bash +#基础部署脚本 +#环境,用以区分部署的命名空间,日志路径 +ENV=$1 +#本文件绝对路径 +SOURCE_CODE_PATH=$(cd $(dirname ${BASH_SOURCE[0]}); pwd ) + +#harbor 地址 +HARBOR_URL=harbor.dubhe.ai +#harbor 用户名 +HARBOR_USERNAME=admin +#harbor 密码 +HARBOR_PWD=Harbor12345 +#文件存储服务 共享目录 +FS_PATH=/nfs +#容器日志路径 +CONTAINER_LOG_PATH=/logs +#宿主机日志路径 +HOST_LOG_PATH=/logs/dubhe-${ENV} + +#删除镜像 +delete_old_image() { + docker rmi -f ${HARBOR_URL}/dubhe/dubhe-spring-cloud-k8s:${ENV} +} +#构建镜像 +build_image() { + cd ${SOURCE_CODE_PATH} && docker build -t ${HARBOR_URL}/dubhe/dubhe-spring-cloud-k8s:${ENV} . +} +#推送镜像到harbor +push_image() { + docker login -u ${HARBOR_USERNAME} -p ${HARBOR_PWD} ${HARBOR_URL} + docker push ${HARBOR_URL}/dubhe/dubhe-spring-cloud-k8s:${ENV} +} +#编译打包源码 +mvn_build() { + # -T 1C 每核心打包一个工程 + # -Dmaven.test.skip=true 跳过测试代码的编译 + # -Dmaven.compile.fork=true 多线程编译 + cd ${SOURCE_CODE_PATH} && mvn clean compile package -T 1C -Dmaven.test.skip=true -Dmaven.compile.fork=true +} + +update_k8s_yaml() { + sed -i "s#harbor.test.com#${HARBOR_URL}#g;s#fsPath#${FS_PATH}#g;s#env-value#${ENV}#g;s#containerLogPath#${CONTAINER_LOG_PATH}#g;s#hostLogPath#${HOST_LOG_PATH}#g;s#gatewayNodePort#${GATEWAY_NODE_PORT}#g" ${SOURCE_CODE_PATH}/deploy/*/* +} \ No newline at end of file diff --git a/dubhe-server/deploy/cloud/deploy-individual.sh b/dubhe-server/deploy/cloud/deploy-individual.sh new file mode 100644 index 0000000..9ecd1f1 --- /dev/null +++ b/dubhe-server/deploy/cloud/deploy-individual.sh @@ -0,0 +1,41 @@ +#!/bin/bash +#引用基础脚本 +source $(cd $(dirname ${BASH_SOURCE[0]}); pwd )/../../deploy-base.sh + +#网关暴露端口 +GATEWAY_NODE_PORT=$2 +#模块列表 +MODULES=${@:3} + +#删除服务 +delete_k8s_app() { + echo "start delete ${MODULES}" + for i in ${MODULES} + do + echo "kubectl delete -f "server-${i}.yaml" -n dubhe-${ENV}" + cd ${SOURCE_CODE_PATH}/deploy/cloud && kubectl delete -f "server-${i}.yaml" -n dubhe-${ENV} + done +} +#配置gateway端口 +update_gateway_node_port() { + sed -i "s#gatewayNodePort#${GATEWAY_NODE_PORT}#g" ${SOURCE_CODE_PATH}/deploy/*/* +} +#部署服务 +deploy_k8s_app() { + echo "start deploy ${MODULES}" + kubectl create ns dubhe-${ENV} + for i in ${MODULES} + do + echo "kubectl apply -f "server-${i}.yaml" -n dubhe-${ENV}" + cd ${SOURCE_CODE_PATH}/deploy/cloud && kubectl apply -f "server-${i}.yaml" -n dubhe-${ENV} + done +} + +delete_k8s_app +delete_old_image +update_k8s_yaml +update_gateway_node_port +mvn_build +build_image +push_image +deploy_k8s_app diff --git a/dubhe-server/deploy/cloud/deploy.sh b/dubhe-server/deploy/cloud/deploy.sh new file mode 100644 index 0000000..81fea02 --- /dev/null +++ b/dubhe-server/deploy/cloud/deploy.sh @@ -0,0 +1,28 @@ +#!/bin/bash +#引用基础脚本 +source $(cd $(dirname ${BASH_SOURCE[0]}); pwd )/../../deploy-base.sh + +#网关暴露端口 +GATEWAY_NODE_PORT=$2 + +#删除服务 +delete_k8s_app() { + kubectl delete ns dubhe-${ENV} +} +#配置gateway端口 +update_gateway_node_port() { + sed -i "s#gatewayNodePort#${GATEWAY_NODE_PORT}#g" ${SOURCE_CODE_PATH}/deploy/*/* +} +#部署服务 +deploy_k8s_app() { + cd ${SOURCE_CODE_PATH}/deploy/cloud && kubectl create ns dubhe-${ENV} && kubectl apply -f server-dubhe.yaml -n dubhe-${ENV} +} + +delete_k8s_app +delete_old_image +update_k8s_yaml +update_gateway_node_port +mvn_build +build_image +push_image +deploy_k8s_app diff --git a/dubhe-server/deploy/cloud/server-admin.yaml b/dubhe-server/deploy/cloud/server-admin.yaml new file mode 100644 index 0000000..ce239fc --- /dev/null +++ b/dubhe-server/deploy/cloud/server-admin.yaml @@ -0,0 +1,78 @@ +################################################################################################## +# admin +################################################################################################## +--- +apiVersion: v1 +kind: Service +metadata: + name: admin + labels: + app: admin + service: admin +spec: + type: NodePort + ports: + - port: 8870 + name: http + selector: + app: admin +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: admin + labels: + account: admin +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: admin-v1 + labels: + app: admin + version: v1 +spec: + replicas: 1 + selector: + matchLabels: + app: admin + version: v1 + template: + metadata: + labels: + app: admin + version: v1 + spec: + serviceAccountName: admin + containers: + - name: admin + image: harbor.test.com/dubhe/dubhe-spring-cloud-k8s:env-value + imagePullPolicy: Always + env: + - name: JAR_BALL + value: "admin-0.0.1-SNAPSHOT-exec.jar --spring.profiles.active=env-value" + - name: JVM_PARAM + value: "-Xms1024m -Xmx1024m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=containerLogPath/admin-dump.hprof" + ports: + - containerPort: 8870 + volumeMounts: + - mountPath: "fsPath" + name: "fs-volume" + readOnly: false + - mountPath: "containerLogPath" + name: "log-volume" + readOnly: false + - name: "dockersock" + mountPath: "/var/run/docker.sock" + volumes: + - name: "fs-volume" + hostPath: + path: "fsPath" + type: "Directory" + - name: "log-volume" + hostPath: + path: "hostLogPath" + type: "DirectoryOrCreate" + - name: "dockersock" + hostPath: + path: "/var/run/docker.sock" \ No newline at end of file diff --git a/dubhe-server/deploy/cloud/server-auth.yaml b/dubhe-server/deploy/cloud/server-auth.yaml new file mode 100644 index 0000000..88969b2 --- /dev/null +++ b/dubhe-server/deploy/cloud/server-auth.yaml @@ -0,0 +1,78 @@ +################################################################################################## +# auth +################################################################################################## +--- +apiVersion: v1 +kind: Service +metadata: + name: auth + labels: + app: auth + service: auth +spec: + type: NodePort + ports: + - port: 8866 + name: http + selector: + app: auth +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: auth + labels: + account: auth +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: auth-v1 + labels: + app: auth + version: v1 +spec: + replicas: 1 + selector: + matchLabels: + app: auth + version: v1 + template: + metadata: + labels: + app: auth + version: v1 + spec: + serviceAccountName: auth + containers: + - name: auth + image: harbor.test.com/dubhe/dubhe-spring-cloud-k8s:env-value + imagePullPolicy: Always + env: + - name: JAR_BALL + value: "auth-0.0.1-SNAPSHOT-exec.jar --spring.profiles.active=env-value" + - name: JVM_PARAM + value: "-Xms1024m -Xmx1024m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=containerLogPath/auth-dump.hprof" + ports: + - containerPort: 8866 + volumeMounts: + - mountPath: "fsPath" + name: "fs-volume" + readOnly: false + - mountPath: "containerLogPath" + name: "log-volume" + readOnly: false + - name: "dockersock" + mountPath: "/var/run/docker.sock" + volumes: + - name: "fs-volume" + hostPath: + path: "fsPath" + type: "Directory" + - name: "log-volume" + hostPath: + path: "hostLogPath" + type: "DirectoryOrCreate" + - name: "dockersock" + hostPath: + path: "/var/run/docker.sock" \ No newline at end of file diff --git a/dubhe-server/deploy/cloud/server-dubhe-algorithm.yaml b/dubhe-server/deploy/cloud/server-dubhe-algorithm.yaml new file mode 100644 index 0000000..fbd7734 --- /dev/null +++ b/dubhe-server/deploy/cloud/server-dubhe-algorithm.yaml @@ -0,0 +1,78 @@ +################################################################################################## +# dubhe-algorithm +################################################################################################## +--- +apiVersion: v1 +kind: Service +metadata: + name: dubhe-algorithm + labels: + app: dubhe-algorithm + service: dubhe-algorithm +spec: + type: NodePort + ports: + - port: 8889 + name: http + selector: + app: dubhe-algorithm +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: dubhe-algorithm + labels: + account: dubhe-algorithm +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: dubhe-algorithm-v1 + labels: + app: dubhe-algorithm + version: v1 +spec: + replicas: 1 + selector: + matchLabels: + app: dubhe-algorithm + version: v1 + template: + metadata: + labels: + app: dubhe-algorithm + version: v1 + spec: + serviceAccountName: dubhe-algorithm + containers: + - name: dubhe-algorithm + image: harbor.test.com/dubhe/dubhe-spring-cloud-k8s:env-value + imagePullPolicy: Always + env: + - name: JAR_BALL + value: "dubhe-algorithm-0.0.1-SNAPSHOT-exec.jar --spring.profiles.active=env-value" + - name: JVM_PARAM + value: "-Xms1024m -Xmx1024m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=containerLogPath/dubhe-algorithm-dump.hprof" + ports: + - containerPort: 8889 + volumeMounts: + - mountPath: "fsPath" + name: "fs-volume" + readOnly: false + - mountPath: "containerLogPath" + name: "log-volume" + readOnly: false + - name: "dockersock" + mountPath: "/var/run/docker.sock" + volumes: + - name: "fs-volume" + hostPath: + path: "fsPath" + type: "Directory" + - name: "log-volume" + hostPath: + path: "hostLogPath" + type: "DirectoryOrCreate" + - name: "dockersock" + hostPath: + path: "/var/run/docker.sock" \ No newline at end of file diff --git a/dubhe-server/deploy/cloud/server-dubhe-data-dcm.yaml b/dubhe-server/deploy/cloud/server-dubhe-data-dcm.yaml new file mode 100644 index 0000000..5da39ac --- /dev/null +++ b/dubhe-server/deploy/cloud/server-dubhe-data-dcm.yaml @@ -0,0 +1,78 @@ +################################################################################################## +# dubhe-data-dcm +################################################################################################## +--- +apiVersion: v1 +kind: Service +metadata: + name: dubhe-data-dcm + labels: + app: dubhe-data-dcm + service: dubhe-data-dcm +spec: + type: NodePort + ports: + - port: 8011 + name: http + selector: + app: dubhe-data-dcm +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: dubhe-data-dcm + labels: + account: dubhe-data-dcm +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: dubhe-data-dcm-v1 + labels: + app: dubhe-data-dcm + version: v1 +spec: + replicas: 1 + selector: + matchLabels: + app: dubhe-data-dcm + version: v1 + template: + metadata: + labels: + app: dubhe-data-dcm + version: v1 + spec: + serviceAccountName: dubhe-data-dcm + containers: + - name: dubhe-data-dcm + image: harbor.test.com/dubhe/dubhe-spring-cloud-k8s:env-value + imagePullPolicy: Always + env: + - name: JAR_BALL + value: "dubhe-data-dcm-0.0.1-SNAPSHOT-exec.jar --spring.profiles.active=env-value" + - name: JVM_PARAM + value: "-Xms1024m -Xmx1024m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=containerLogPath/dubhe-data-dcm-dump.hprof" + ports: + - containerPort: 8011 + volumeMounts: + - mountPath: "fsPath" + name: "fs-volume" + readOnly: false + - mountPath: "containerLogPath" + name: "log-volume" + readOnly: false + - name: "dockersock" + mountPath: "/var/run/docker.sock" + volumes: + - name: "fs-volume" + hostPath: + path: "fsPath" + type: "Directory" + - name: "log-volume" + hostPath: + path: "hostLogPath" + type: "DirectoryOrCreate" + - name: "dockersock" + hostPath: + path: "/var/run/docker.sock" \ No newline at end of file diff --git a/dubhe-server/deploy/cloud/server-dubhe-data-task.yaml b/dubhe-server/deploy/cloud/server-dubhe-data-task.yaml new file mode 100644 index 0000000..c04a1db --- /dev/null +++ b/dubhe-server/deploy/cloud/server-dubhe-data-task.yaml @@ -0,0 +1,81 @@ +################################################################################################## +# dubhe-data-task +################################################################################################## +--- +apiVersion: v1 +kind: Service +metadata: + name: dubhe-data-task + labels: + app: dubhe-data-task + service: dubhe-data-task +spec: + type: NodePort + ports: + - port: 8801 + name: http + - port: 5005 + name: debug + selector: + app: dubhe-data-task +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: dubhe-data-task + labels: + account: dubhe-data-task +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: dubhe-data-task-v1 + labels: + app: dubhe-data-task + version: v1 +spec: + replicas: 1 + selector: + matchLabels: + app: dubhe-data-task + version: v1 + template: + metadata: + labels: + app: dubhe-data-task + version: v1 + spec: + serviceAccountName: dubhe-data-task + containers: + - name: dubhe-data-task + image: harbor.test.com/dubhe/dubhe-spring-cloud-k8s:env-value + imagePullPolicy: Always + env: + - name: JAR_BALL + value: "dubhe-data-task-0.0.1-SNAPSHOT-exec.jar --spring.profiles.active=env-value" + - name: JVM_PARAM + value: "-Xms1024m -Xmx1024m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=containerLogPath/dubhe-data-task-dump.hprof" + ports: + - containerPort: 8801 + - containerPort: 5005 + volumeMounts: + - mountPath: "fsPath" + name: "fs-volume" + readOnly: false + - mountPath: "containerLogPath" + name: "log-volume" + readOnly: false + - name: "dockersock" + mountPath: "/var/run/docker.sock" + volumes: + - name: "fs-volume" + hostPath: + path: "fsPath" + type: "Directory" + - name: "log-volume" + hostPath: + path: "hostLogPath" + type: "DirectoryOrCreate" + - name: "dockersock" + hostPath: + path: "/var/run/docker.sock" \ No newline at end of file diff --git a/dubhe-server/deploy/cloud/server-dubhe-data.yaml b/dubhe-server/deploy/cloud/server-dubhe-data.yaml new file mode 100644 index 0000000..6efb88e --- /dev/null +++ b/dubhe-server/deploy/cloud/server-dubhe-data.yaml @@ -0,0 +1,81 @@ +################################################################################################## +# dubhe-data +################################################################################################## +--- +apiVersion: v1 +kind: Service +metadata: + name: dubhe-data + labels: + app: dubhe-data + service: dubhe-data +spec: + type: NodePort + ports: + - port: 8823 + name: http + - port: 5005 + name: debug + selector: + app: dubhe-data +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: dubhe-data + labels: + account: dubhe-data +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: dubhe-data-v1 + labels: + app: dubhe-data + version: v1 +spec: + replicas: 1 + selector: + matchLabels: + app: dubhe-data + version: v1 + template: + metadata: + labels: + app: dubhe-data + version: v1 + spec: + serviceAccountName: dubhe-data + containers: + - name: dubhe-data + image: harbor.test.com/dubhe/dubhe-spring-cloud-k8s:env-value + imagePullPolicy: Always + env: + - name: JAR_BALL + value: "dubhe-data-0.0.1-SNAPSHOT-exec.jar --spring.profiles.active=env-value" + - name: JVM_PARAM + value: "-Xms4096m -Xmx4096m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=containerLogPath/dubhe-data-dump.hprof" + ports: + - containerPort: 8823 + - containerPort: 5005 + volumeMounts: + - mountPath: "fsPath" + name: "fs-volume" + readOnly: false + - mountPath: "containerLogPath" + name: "log-volume" + readOnly: false + - name: "dockersock" + mountPath: "/var/run/docker.sock" + volumes: + - name: "fs-volume" + hostPath: + path: "fsPath" + type: "Directory" + - name: "log-volume" + hostPath: + path: "hostLogPath" + type: "DirectoryOrCreate" + - name: "dockersock" + hostPath: + path: "/var/run/docker.sock" \ No newline at end of file diff --git a/dubhe-server/deploy/cloud/server-dubhe-image.yaml b/dubhe-server/deploy/cloud/server-dubhe-image.yaml new file mode 100644 index 0000000..3a62abb --- /dev/null +++ b/dubhe-server/deploy/cloud/server-dubhe-image.yaml @@ -0,0 +1,78 @@ +################################################################################################## +# dubhe-image +################################################################################################## +--- +apiVersion: v1 +kind: Service +metadata: + name: dubhe-image + labels: + app: dubhe-image + service: dubhe-image +spec: + type: NodePort + ports: + - port: 8822 + name: http + selector: + app: dubhe-image +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: dubhe-image + labels: + account: dubhe-image +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: dubhe-image-v1 + labels: + app: dubhe-image + version: v1 +spec: + replicas: 1 + selector: + matchLabels: + app: dubhe-image + version: v1 + template: + metadata: + labels: + app: dubhe-image + version: v1 + spec: + serviceAccountName: dubhe-image + containers: + - name: dubhe-image + image: harbor.test.com/dubhe/dubhe-spring-cloud-k8s:env-value + imagePullPolicy: Always + env: + - name: JAR_BALL + value: "dubhe-image-0.0.1-SNAPSHOT-exec.jar --spring.profiles.active=env-value" + - name: JVM_PARAM + value: "-Xms1024m -Xmx1024m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=containerLogPath/dubhe-image-dump.hprof" + ports: + - containerPort: 8822 + volumeMounts: + - mountPath: "fsPath" + name: "fs-volume" + readOnly: false + - mountPath: "containerLogPath" + name: "log-volume" + readOnly: false + - name: "dockersock" + mountPath: "/var/run/docker.sock" + volumes: + - name: "fs-volume" + hostPath: + path: "fsPath" + type: "Directory" + - name: "log-volume" + hostPath: + path: "hostLogPath" + type: "DirectoryOrCreate" + - name: "dockersock" + hostPath: + path: "/var/run/docker.sock" \ No newline at end of file diff --git a/dubhe-server/deploy/cloud/server-dubhe-k8s.yaml b/dubhe-server/deploy/cloud/server-dubhe-k8s.yaml new file mode 100644 index 0000000..d330313 --- /dev/null +++ b/dubhe-server/deploy/cloud/server-dubhe-k8s.yaml @@ -0,0 +1,81 @@ +################################################################################################## +# dubhe-k8s +################################################################################################## +--- +apiVersion: v1 +kind: Service +metadata: + name: dubhe-k8s + labels: + app: dubhe-k8s + service: dubhe-k8s +spec: + type: NodePort + ports: + - port: 8960 + name: http + - port: 5005 + name: debug + selector: + app: dubhe-k8s +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: dubhe-k8s + labels: + account: dubhe-k8s +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: dubhe-k8s-v1 + labels: + app: dubhe-k8s + version: v1 +spec: + replicas: 1 + selector: + matchLabels: + app: dubhe-k8s + version: v1 + template: + metadata: + labels: + app: dubhe-k8s + version: v1 + spec: + serviceAccountName: dubhe-k8s + containers: + - name: dubhe-k8s + image: harbor.test.com/dubhe/dubhe-spring-cloud-k8s:env-value + imagePullPolicy: Always + env: + - name: JAR_BALL + value: "dubhe-k8s-0.0.1-SNAPSHOT-exec.jar --spring.profiles.active=env-value" + - name: JVM_PARAM + value: "-Xms1024m -Xmx1024m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=containerLogPath/dubhe-k8s-dump.hprof" + ports: + - containerPort: 8960 + - containerPort: 5005 + volumeMounts: + - mountPath: "fsPath" + name: "fs-volume" + readOnly: false + - mountPath: "containerLogPath" + name: "log-volume" + readOnly: false + - name: "dockersock" + mountPath: "/var/run/docker.sock" + volumes: + - name: "fs-volume" + hostPath: + path: "fsPath" + type: "Directory" + - name: "log-volume" + hostPath: + path: "hostLogPath" + type: "DirectoryOrCreate" + - name: "dockersock" + hostPath: + path: "/var/run/docker.sock" \ No newline at end of file diff --git a/dubhe-server/deploy/cloud/server-dubhe-measure.yaml b/dubhe-server/deploy/cloud/server-dubhe-measure.yaml new file mode 100644 index 0000000..a06952d --- /dev/null +++ b/dubhe-server/deploy/cloud/server-dubhe-measure.yaml @@ -0,0 +1,78 @@ +################################################################################################## +# dubhe-measure +################################################################################################## +--- +apiVersion: v1 +kind: Service +metadata: + name: dubhe-measure + labels: + app: dubhe-measure + service: dubhe-measure +spec: + type: NodePort + ports: + - port: 8821 + name: http + selector: + app: dubhe-measure +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: dubhe-measure + labels: + account: dubhe-measure +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: dubhe-measure-v1 + labels: + app: dubhe-measure + version: v1 +spec: + replicas: 1 + selector: + matchLabels: + app: dubhe-measure + version: v1 + template: + metadata: + labels: + app: dubhe-measure + version: v1 + spec: + serviceAccountName: dubhe-measure + containers: + - name: dubhe-measure + image: harbor.test.com/dubhe/dubhe-spring-cloud-k8s:env-value + imagePullPolicy: Always + env: + - name: JAR_BALL + value: "dubhe-measure-0.0.1-SNAPSHOT-exec.jar --spring.profiles.active=env-value" + - name: JVM_PARAM + value: "-Xms1024m -Xmx1024m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=containerLogPath/dubhe-measure-dump.hprof" + ports: + - containerPort: 8821 + volumeMounts: + - mountPath: "fsPath" + name: "fs-volume" + readOnly: false + - mountPath: "containerLogPath" + name: "log-volume" + readOnly: false + - name: "dockersock" + mountPath: "/var/run/docker.sock" + volumes: + - name: "fs-volume" + hostPath: + path: "fsPath" + type: "Directory" + - name: "log-volume" + hostPath: + path: "hostLogPath" + type: "DirectoryOrCreate" + - name: "dockersock" + hostPath: + path: "/var/run/docker.sock" \ No newline at end of file diff --git a/dubhe-server/deploy/cloud/server-dubhe-model.yaml b/dubhe-server/deploy/cloud/server-dubhe-model.yaml new file mode 100644 index 0000000..25a308b --- /dev/null +++ b/dubhe-server/deploy/cloud/server-dubhe-model.yaml @@ -0,0 +1,81 @@ +################################################################################################## +# dubhe-model +################################################################################################## +--- +apiVersion: v1 +kind: Service +metadata: + name: dubhe-model + labels: + app: dubhe-model + service: dubhe-model +spec: + type: NodePort + ports: + - port: 8888 + name: http + - port: 5005 + name: debug + selector: + app: dubhe-model +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: dubhe-model + labels: + account: dubhe-model +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: dubhe-model-v1 + labels: + app: dubhe-model + version: v1 +spec: + replicas: 1 + selector: + matchLabels: + app: dubhe-model + version: v1 + template: + metadata: + labels: + app: dubhe-model + version: v1 + spec: + serviceAccountName: dubhe-model + containers: + - name: dubhe-model + image: harbor.test.com/dubhe/dubhe-spring-cloud-k8s:env-value + imagePullPolicy: Always + env: + - name: JAR_BALL + value: "dubhe-model-0.0.1-SNAPSHOT-exec.jar --spring.profiles.active=env-value" + - name: JVM_PARAM + value: "-Xms1024m -Xmx1024m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=containerLogPath/dubhe-model-dump.hprof" + ports: + - containerPort: 8888 + - containerPort: 5005 + volumeMounts: + - mountPath: "fsPath" + name: "fs-volume" + readOnly: false + - mountPath: "containerLogPath" + name: "log-volume" + readOnly: false + - name: "dockersock" + mountPath: "/var/run/docker.sock" + volumes: + - name: "fs-volume" + hostPath: + path: "fsPath" + type: "Directory" + - name: "log-volume" + hostPath: + path: "hostLogPath" + type: "DirectoryOrCreate" + - name: "dockersock" + hostPath: + path: "/var/run/docker.sock" \ No newline at end of file diff --git a/dubhe-server/deploy/cloud/server-dubhe-notebook.yaml b/dubhe-server/deploy/cloud/server-dubhe-notebook.yaml new file mode 100644 index 0000000..0f62f9b --- /dev/null +++ b/dubhe-server/deploy/cloud/server-dubhe-notebook.yaml @@ -0,0 +1,81 @@ +################################################################################################## +# dubhe-notebook +################################################################################################## +--- +apiVersion: v1 +kind: Service +metadata: + name: dubhe-notebook + labels: + app: dubhe-notebook + service: dubhe-notebook +spec: + type: NodePort + ports: + - port: 8801 + name: http + - port: 5005 + name: debug + selector: + app: dubhe-notebook +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: dubhe-notebook + labels: + account: dubhe-notebook +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: dubhe-notebook-v1 + labels: + app: dubhe-notebook + version: v1 +spec: + replicas: 1 + selector: + matchLabels: + app: dubhe-notebook + version: v1 + template: + metadata: + labels: + app: dubhe-notebook + version: v1 + spec: + serviceAccountName: dubhe-notebook + containers: + - name: dubhe-notebook + image: harbor.test.com/dubhe/dubhe-spring-cloud-k8s:env-value + imagePullPolicy: Always + env: + - name: JAR_BALL + value: "dubhe-notebook-0.0.1-SNAPSHOT-exec.jar --spring.profiles.active=env-value" + - name: JVM_PARAM + value: "-Xms1024m -Xmx1024m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=containerLogPath/dubhe-notebook-dump.hprof" + ports: + - containerPort: 8801 + - containerPort: 5005 + volumeMounts: + - mountPath: "fsPath" + name: "fs-volume" + readOnly: false + - mountPath: "containerLogPath" + name: "log-volume" + readOnly: false + - name: "dockersock" + mountPath: "/var/run/docker.sock" + volumes: + - name: "fs-volume" + hostPath: + path: "fsPath" + type: "Directory" + - name: "log-volume" + hostPath: + path: "hostLogPath" + type: "DirectoryOrCreate" + - name: "dockersock" + hostPath: + path: "/var/run/docker.sock" \ No newline at end of file diff --git a/dubhe-server/deploy/cloud/server-dubhe-optimize.yaml b/dubhe-server/deploy/cloud/server-dubhe-optimize.yaml new file mode 100644 index 0000000..574e1cb --- /dev/null +++ b/dubhe-server/deploy/cloud/server-dubhe-optimize.yaml @@ -0,0 +1,81 @@ +################################################################################################## +# dubhe-optimize +################################################################################################## +--- +apiVersion: v1 +kind: Service +metadata: + name: dubhe-optimize + labels: + app: dubhe-optimize + service: dubhe-optimize +spec: + type: NodePort + ports: + - port: 8899 + name: http + - port: 5005 + name: debug + selector: + app: dubhe-optimize +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: dubhe-optimize + labels: + account: dubhe-optimize +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: dubhe-optimize-v1 + labels: + app: dubhe-optimize + version: v1 +spec: + replicas: 1 + selector: + matchLabels: + app: dubhe-optimize + version: v1 + template: + metadata: + labels: + app: dubhe-optimize + version: v1 + spec: + serviceAccountName: dubhe-optimize + containers: + - name: dubhe-optimize + image: harbor.test.com/dubhe/dubhe-spring-cloud-k8s:env-value + imagePullPolicy: Always + env: + - name: JAR_BALL + value: "dubhe-optimize-0.0.1-SNAPSHOT-exec.jar --spring.profiles.active=env-value" + - name: JVM_PARAM + value: "-Xms1024m -Xmx1024m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=containerLogPath/dubhe-optimize-dump.hprof" + ports: + - containerPort: 8899 + - containerPort: 5005 + volumeMounts: + - mountPath: "fsPath" + name: "fs-volume" + readOnly: false + - mountPath: "containerLogPath" + name: "log-volume" + readOnly: false + - name: "dockersock" + mountPath: "/var/run/docker.sock" + volumes: + - name: "fs-volume" + hostPath: + path: "fsPath" + type: "Directory" + - name: "log-volume" + hostPath: + path: "hostLogPath" + type: "DirectoryOrCreate" + - name: "dockersock" + hostPath: + path: "/var/run/docker.sock" \ No newline at end of file diff --git a/dubhe-server/deploy/cloud/server-dubhe-serving-gateway.yaml b/dubhe-server/deploy/cloud/server-dubhe-serving-gateway.yaml new file mode 100644 index 0000000..f48bba6 --- /dev/null +++ b/dubhe-server/deploy/cloud/server-dubhe-serving-gateway.yaml @@ -0,0 +1,82 @@ +################################################################################################## +# dubhe-serving-gateway +################################################################################################## +--- +apiVersion: v1 +kind: Service +metadata: + name: dubhe-serving-gateway + labels: + app: dubhe-serving-gateway + service: dubhe-serving-gateway +spec: + type: NodePort + ports: + - port: 8081 + name: http + nodePort: 30848 + - port: 5005 + name: debug + selector: + app: dubhe-serving-gateway +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: dubhe-serving-gateway + labels: + account: dubhe-serving-gateway +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: dubhe-serving-gateway-v1 + labels: + app: dubhe-serving-gateway + version: v1 +spec: + replicas: 1 + selector: + matchLabels: + app: dubhe-serving-gateway + version: v1 + template: + metadata: + labels: + app: dubhe-serving-gateway + version: v1 + spec: + serviceAccountName: dubhe-serving-gateway + containers: + - name: dubhe-serving-gateway + image: harbor.test.com/dubhe/dubhe-spring-cloud-k8s:env-value + imagePullPolicy: Always + env: + - name: JAR_BALL + value: "dubhe-serving-gateway-0.0.1-SNAPSHOT-exec.jar --spring.profiles.active=env-value" + - name: JVM_PARAM + value: "-Xms512m -Xmx512m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=containerLogPath/dubhe-serving-gateway-dump.hprof" + ports: + - containerPort: 8081 + - containerPort: 5505 + volumeMounts: + - mountPath: "fsPath" + name: "fs-volume" + readOnly: false + - mountPath: "containerLogPath" + name: "log-volume" + readOnly: false + - name: "dockersock" + mountPath: "/var/run/docker.sock" + volumes: + - name: "fs-volume" + hostPath: + path: "fsPath" + type: "Directory" + - name: "log-volume" + hostPath: + path: "hostLogPath" + type: "DirectoryOrCreate" + - name: "dockersock" + hostPath: + path: "/var/run/docker.sock" \ No newline at end of file diff --git a/dubhe-server/deploy/cloud/server-dubhe-serving.yaml b/dubhe-server/deploy/cloud/server-dubhe-serving.yaml new file mode 100644 index 0000000..5b4b819 --- /dev/null +++ b/dubhe-server/deploy/cloud/server-dubhe-serving.yaml @@ -0,0 +1,81 @@ +################################################################################################## +# dubhe-serving +################################################################################################## +--- +apiVersion: v1 +kind: Service +metadata: + name: dubhe-serving + labels: + app: dubhe-serving + service: dubhe-serving +spec: + type: NodePort + ports: + - port: 8898 + name: http + - port: 5005 + name: debug + selector: + app: dubhe-serving +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: dubhe-serving + labels: + account: dubhe-serving +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: dubhe-serving-v1 + labels: + app: dubhe-serving + version: v1 +spec: + replicas: 1 + selector: + matchLabels: + app: dubhe-serving + version: v1 + template: + metadata: + labels: + app: dubhe-serving + version: v1 + spec: + serviceAccountName: dubhe-serving + containers: + - name: dubhe-serving + image: harbor.test.com/dubhe/dubhe-spring-cloud-k8s:env-value + imagePullPolicy: Always + env: + - name: JAR_BALL + value: "dubhe-serving-0.0.1-SNAPSHOT-exec.jar --spring.profiles.active=env-value" + - name: JVM_PARAM + value: "-Xms1024m -Xmx1024m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=containerLogPath/dubhe-serving-dump.hprof" + ports: + - containerPort: 8898 + - containerPort: 5005 + volumeMounts: + - mountPath: "fsPath" + name: "fs-volume" + readOnly: false + - mountPath: "containerLogPath" + name: "log-volume" + readOnly: false + - name: "dockersock" + mountPath: "/var/run/docker.sock" + volumes: + - name: "fs-volume" + hostPath: + path: "fsPath" + type: "Directory" + - name: "log-volume" + hostPath: + path: "hostLogPath" + type: "DirectoryOrCreate" + - name: "dockersock" + hostPath: + path: "/var/run/docker.sock" \ No newline at end of file diff --git a/dubhe-server/deploy/cloud/server-dubhe-train.yaml b/dubhe-server/deploy/cloud/server-dubhe-train.yaml new file mode 100644 index 0000000..5bc190d --- /dev/null +++ b/dubhe-server/deploy/cloud/server-dubhe-train.yaml @@ -0,0 +1,78 @@ +################################################################################################## +# dubhe-train +################################################################################################## +--- +apiVersion: v1 +kind: Service +metadata: + name: dubhe-train + labels: + app: dubhe-train + service: dubhe-train +spec: + type: NodePort + ports: + - port: 8890 + name: http + selector: + app: dubhe-train +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: dubhe-train + labels: + account: dubhe-train +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: dubhe-train-v1 + labels: + app: dubhe-train + version: v1 +spec: + replicas: 1 + selector: + matchLabels: + app: dubhe-train + version: v1 + template: + metadata: + labels: + app: dubhe-train + version: v1 + spec: + serviceAccountName: dubhe-train + containers: + - name: dubhe-train + image: harbor.test.com/dubhe/dubhe-spring-cloud-k8s:env-value + imagePullPolicy: Always + env: + - name: JAR_BALL + value: "dubhe-train-0.0.1-SNAPSHOT-exec.jar --spring.profiles.active=env-value" + - name: JVM_PARAM + value: "-Xms1024m -Xmx1024m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=containerLogPath/dubhe-train-dump.hprof" + ports: + - containerPort: 8890 + volumeMounts: + - mountPath: "fsPath" + name: "fs-volume" + readOnly: false + - mountPath: "containerLogPath" + name: "log-volume" + readOnly: false + - name: "dockersock" + mountPath: "/var/run/docker.sock" + volumes: + - name: "fs-volume" + hostPath: + path: "fsPath" + type: "Directory" + - name: "log-volume" + hostPath: + path: "hostLogPath" + type: "DirectoryOrCreate" + - name: "dockersock" + hostPath: + path: "/var/run/docker.sock" \ No newline at end of file diff --git a/dubhe-server/deploy/cloud/server-dubhe.yaml b/dubhe-server/deploy/cloud/server-dubhe.yaml new file mode 100644 index 0000000..4eff9a9 --- /dev/null +++ b/dubhe-server/deploy/cloud/server-dubhe.yaml @@ -0,0 +1,1425 @@ +################################################################################################## +# admin +################################################################################################## +--- +apiVersion: v1 +kind: Service +metadata: + name: admin + labels: + app: admin + service: admin +spec: + type: NodePort + ports: + - port: 8870 + name: http + selector: + app: admin +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: admin + labels: + account: admin +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: admin-v1 + labels: + app: admin + version: v1 +spec: + replicas: 1 + selector: + matchLabels: + app: admin + version: v1 + template: + metadata: + labels: + app: admin + version: v1 + spec: + serviceAccountName: admin + containers: + - name: admin + image: harbor.test.com/dubhe/dubhe-spring-cloud-k8s:env-value + imagePullPolicy: Always + env: + - name: JAR_BALL + value: "admin-0.0.1-SNAPSHOT-exec.jar --spring.profiles.active=env-value" + - name: JVM_PARAM + value: "-Xms1024m -Xmx1024m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=containerLogPath/admin-dump.hprof" + ports: + - containerPort: 8870 + volumeMounts: + - mountPath: "fsPath" + name: "fs-volume" + readOnly: false + - mountPath: "containerLogPath" + name: "log-volume" + readOnly: false + - name: "dockersock" + mountPath: "/var/run/docker.sock" + volumes: + - name: "fs-volume" + hostPath: + path: "fsPath" + type: "Directory" + - name: "log-volume" + hostPath: + path: "hostLogPath" + type: "DirectoryOrCreate" + - name: "dockersock" + hostPath: + path: "/var/run/docker.sock" + +################################################################################################## +# auth +################################################################################################## +--- +apiVersion: v1 +kind: Service +metadata: + name: auth + labels: + app: auth + service: auth +spec: + type: NodePort + ports: + - port: 8866 + name: http + selector: + app: auth +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: auth + labels: + account: auth +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: auth-v1 + labels: + app: auth + version: v1 +spec: + replicas: 1 + selector: + matchLabels: + app: auth + version: v1 + template: + metadata: + labels: + app: auth + version: v1 + spec: + serviceAccountName: auth + containers: + - name: auth + image: harbor.test.com/dubhe/dubhe-spring-cloud-k8s:env-value + imagePullPolicy: Always + env: + - name: JAR_BALL + value: "auth-0.0.1-SNAPSHOT-exec.jar --spring.profiles.active=env-value" + - name: JVM_PARAM + value: "-Xms1024m -Xmx1024m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=containerLogPath/auth-dump.hprof" + ports: + - containerPort: 8866 + volumeMounts: + - mountPath: "fsPath" + name: "fs-volume" + readOnly: false + - mountPath: "containerLogPath" + name: "log-volume" + readOnly: false + - name: "dockersock" + mountPath: "/var/run/docker.sock" + volumes: + - name: "fs-volume" + hostPath: + path: "fsPath" + type: "Directory" + - name: "log-volume" + hostPath: + path: "hostLogPath" + type: "DirectoryOrCreate" + - name: "dockersock" + hostPath: + path: "/var/run/docker.sock" +################################################################################################## +# demo-client service +################################################################################################## +--- +apiVersion: v1 +kind: Service +metadata: + name: demo-client + labels: + app: demo-client + service: demo-client +spec: + type: NodePort + ports: + - port: 8861 + name: http + selector: + app: demo-client +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: demo-client + labels: + account: demo-client +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: demo-client-v1 + labels: + app: demo-client + version: v1 +spec: + replicas: 1 + selector: + matchLabels: + app: demo-client + version: v1 + template: + metadata: + labels: + app: demo-client + version: v1 + spec: + serviceAccountName: demo-client + containers: + - name: demo-client + image: harbor.test.com/dubhe/dubhe-spring-cloud-k8s:env-value + imagePullPolicy: Always + env: + - name: JAR_BALL + value: "demo-client-0.0.1-SNAPSHOT-exec.jar --spring.profiles.active=env-value" + - name: JVM_PARAM + value: "-Xms1024m -Xmx1024m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=containerLogPath/demo-client-dump.hprof" + ports: + - containerPort: 8861 + volumeMounts: + - mountPath: "fsPath" + name: "fs-volume" + readOnly: false + - mountPath: "containerLogPath" + name: "log-volume" + readOnly: false + - name: "dockersock" + mountPath: "/var/run/docker.sock" + volumes: + - name: "fs-volume" + hostPath: + path: "fsPath" + type: "Directory" + - name: "log-volume" + hostPath: + path: "hostLogPath" + type: "DirectoryOrCreate" + - name: "dockersock" + hostPath: + path: "/var/run/docker.sock" +################################################################################################## +# demo-provider service +################################################################################################## +--- +apiVersion: v1 +kind: Service +metadata: + name: demo-provider + labels: + app: demo-provider + service: demo-provider +spec: + type: NodePort + ports: + - port: 8860 + name: http + selector: + app: demo-provider +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: demo-provider + labels: + account: demo-provider +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: demo-provider-v1 + labels: + app: demo-provider + version: v1 +spec: + replicas: 1 + selector: + matchLabels: + app: demo-provider + version: v1 + template: + metadata: + labels: + app: demo-provider + version: v1 + spec: + serviceAccountName: demo-provider + containers: + - name: demo-provider + image: harbor.test.com/dubhe/dubhe-spring-cloud-k8s:env-value + imagePullPolicy: Always + env: + - name: JAR_BALL + value: "demo-provider-0.0.1-SNAPSHOT-exec.jar --spring.profiles.active=env-value" + - name: JVM_PARAM + value: "-Xms1024m -Xmx1024m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=containerLogPath/demo-provider-dump.hprof" + ports: + - containerPort: 8860 + volumeMounts: + - mountPath: "fsPath" + name: "fs-volume" + readOnly: false + - mountPath: "containerLogPath" + name: "log-volume" + readOnly: false + - name: "dockersock" + mountPath: "/var/run/docker.sock" + volumes: + - name: "fs-volume" + hostPath: + path: "fsPath" + type: "Directory" + - name: "log-volume" + hostPath: + path: "hostLogPath" + type: "DirectoryOrCreate" + - name: "dockersock" + hostPath: + path: "/var/run/docker.sock" +################################################################################################## +# dubhe-algorithm +################################################################################################## +--- +apiVersion: v1 +kind: Service +metadata: + name: dubhe-algorithm + labels: + app: dubhe-algorithm + service: dubhe-algorithm +spec: + type: NodePort + ports: + - port: 8889 + name: http + selector: + app: dubhe-algorithm +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: dubhe-algorithm + labels: + account: dubhe-algorithm +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: dubhe-algorithm-v1 + labels: + app: dubhe-algorithm + version: v1 +spec: + replicas: 1 + selector: + matchLabels: + app: dubhe-algorithm + version: v1 + template: + metadata: + labels: + app: dubhe-algorithm + version: v1 + spec: + serviceAccountName: dubhe-algorithm + containers: + - name: dubhe-algorithm + image: harbor.test.com/dubhe/dubhe-spring-cloud-k8s:env-value + imagePullPolicy: Always + env: + - name: JAR_BALL + value: "dubhe-algorithm-0.0.1-SNAPSHOT-exec.jar --spring.profiles.active=env-value" + - name: JVM_PARAM + value: "-Xms1024m -Xmx1024m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=containerLogPath/dubhe-algorithm-dump.hprof" + ports: + - containerPort: 8889 + volumeMounts: + - mountPath: "fsPath" + name: "fs-volume" + readOnly: false + - mountPath: "containerLogPath" + name: "log-volume" + readOnly: false + - name: "dockersock" + mountPath: "/var/run/docker.sock" + volumes: + - name: "fs-volume" + hostPath: + path: "fsPath" + type: "Directory" + - name: "log-volume" + hostPath: + path: "hostLogPath" + type: "DirectoryOrCreate" + - name: "dockersock" + hostPath: + path: "/var/run/docker.sock" +################################################################################################## +# dubhe-data +################################################################################################## +--- +apiVersion: v1 +kind: Service +metadata: + name: dubhe-data + labels: + app: dubhe-data + service: dubhe-data +spec: + type: NodePort + ports: + - port: 8823 + name: http + - port: 5005 + name: debug + selector: + app: dubhe-data +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: dubhe-data + labels: + account: dubhe-data +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: dubhe-data-v1 + labels: + app: dubhe-data + version: v1 +spec: + replicas: 1 + selector: + matchLabels: + app: dubhe-data + version: v1 + template: + metadata: + labels: + app: dubhe-data + version: v1 + spec: + serviceAccountName: dubhe-data + containers: + - name: dubhe-data + image: harbor.test.com/dubhe/dubhe-spring-cloud-k8s:env-value + imagePullPolicy: Always + env: + - name: JAR_BALL + value: "dubhe-data-0.0.1-SNAPSHOT-exec.jar --spring.profiles.active=env-value" + - name: JVM_PARAM + value: "-Xms4096m -Xmx4096m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=containerLogPath/dubhe-data-dump.hprof" + ports: + - containerPort: 8823 + - containerPort: 5005 + volumeMounts: + - mountPath: "fsPath" + name: "fs-volume" + readOnly: false + - mountPath: "containerLogPath" + name: "log-volume" + readOnly: false + - name: "dockersock" + mountPath: "/var/run/docker.sock" + volumes: + - name: "fs-volume" + hostPath: + path: "fsPath" + type: "Directory" + - name: "log-volume" + hostPath: + path: "hostLogPath" + type: "DirectoryOrCreate" + - name: "dockersock" + hostPath: + path: "/var/run/docker.sock" +################################################################################################## +# dubhe-image +################################################################################################## +--- +apiVersion: v1 +kind: Service +metadata: + name: dubhe-image + labels: + app: dubhe-image + service: dubhe-image +spec: + type: NodePort + ports: + - port: 8822 + name: http + selector: + app: dubhe-image +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: dubhe-image + labels: + account: dubhe-image +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: dubhe-image-v1 + labels: + app: dubhe-image + version: v1 +spec: + replicas: 1 + selector: + matchLabels: + app: dubhe-image + version: v1 + template: + metadata: + labels: + app: dubhe-image + version: v1 + spec: + serviceAccountName: dubhe-image + containers: + - name: dubhe-image + image: harbor.test.com/dubhe/dubhe-spring-cloud-k8s:env-value + imagePullPolicy: Always + env: + - name: JAR_BALL + value: "dubhe-image-0.0.1-SNAPSHOT-exec.jar --spring.profiles.active=env-value" + - name: JVM_PARAM + value: "-Xms1024m -Xmx1024m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=containerLogPath/dubhe-image-dump.hprof" + ports: + - containerPort: 8822 + volumeMounts: + - mountPath: "fsPath" + name: "fs-volume" + readOnly: false + - mountPath: "containerLogPath" + name: "log-volume" + readOnly: false + - name: "dockersock" + mountPath: "/var/run/docker.sock" + volumes: + - name: "fs-volume" + hostPath: + path: "fsPath" + type: "Directory" + - name: "log-volume" + hostPath: + path: "hostLogPath" + type: "DirectoryOrCreate" + - name: "dockersock" + hostPath: + path: "/var/run/docker.sock" +################################################################################################## +# dubhe-k8s +################################################################################################## +--- +apiVersion: v1 +kind: Service +metadata: + name: dubhe-k8s + labels: + app: dubhe-k8s + service: dubhe-k8s +spec: + type: NodePort + ports: + - port: 8960 + name: http + selector: + app: dubhe-k8s +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: dubhe-k8s + labels: + account: dubhe-k8s +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: dubhe-k8s-v1 + labels: + app: dubhe-k8s + version: v1 +spec: + replicas: 1 + selector: + matchLabels: + app: dubhe-k8s + version: v1 + template: + metadata: + labels: + app: dubhe-k8s + version: v1 + spec: + serviceAccountName: dubhe-k8s + containers: + - name: dubhe-k8s + image: harbor.test.com/dubhe/dubhe-spring-cloud-k8s:env-value + imagePullPolicy: Always + env: + - name: JAR_BALL + value: "dubhe-k8s-0.0.1-SNAPSHOT-exec.jar --spring.profiles.active=env-value" + - name: JVM_PARAM + value: "-Xms1024m -Xmx1024m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=containerLogPath/dubhe-k8s-dump.hprof" + ports: + - containerPort: 8960 + volumeMounts: + - mountPath: "fsPath" + name: "fs-volume" + readOnly: false + - mountPath: "containerLogPath" + name: "log-volume" + readOnly: false + - name: "dockersock" + mountPath: "/var/run/docker.sock" + volumes: + - name: "fs-volume" + hostPath: + path: "fsPath" + type: "Directory" + - name: "log-volume" + hostPath: + path: "hostLogPath" + type: "DirectoryOrCreate" + - name: "dockersock" + hostPath: + path: "/var/run/docker.sock" +################################################################################################## +# dubhe-measure +################################################################################################## +--- +apiVersion: v1 +kind: Service +metadata: + name: dubhe-measure + labels: + app: dubhe-measure + service: dubhe-measure +spec: + type: NodePort + ports: + - port: 8821 + name: http + selector: + app: dubhe-measure +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: dubhe-measure + labels: + account: dubhe-measure +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: dubhe-measure-v1 + labels: + app: dubhe-measure + version: v1 +spec: + replicas: 1 + selector: + matchLabels: + app: dubhe-measure + version: v1 + template: + metadata: + labels: + app: dubhe-measure + version: v1 + spec: + serviceAccountName: dubhe-measure + containers: + - name: dubhe-measure + image: harbor.test.com/dubhe/dubhe-spring-cloud-k8s:env-value + imagePullPolicy: Always + env: + - name: JAR_BALL + value: "dubhe-measure-0.0.1-SNAPSHOT-exec.jar --spring.profiles.active=env-value" + - name: JVM_PARAM + value: "-Xms1024m -Xmx1024m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=containerLogPath/dubhe-measure-dump.hprof" + ports: + - containerPort: 8821 + volumeMounts: + - mountPath: "fsPath" + name: "fs-volume" + readOnly: false + - mountPath: "containerLogPath" + name: "log-volume" + readOnly: false + - name: "dockersock" + mountPath: "/var/run/docker.sock" + volumes: + - name: "fs-volume" + hostPath: + path: "fsPath" + type: "Directory" + - name: "log-volume" + hostPath: + path: "hostLogPath" + type: "DirectoryOrCreate" + - name: "dockersock" + hostPath: + path: "/var/run/docker.sock" +################################################################################################## +# dubhe-model +################################################################################################## +--- +apiVersion: v1 +kind: Service +metadata: + name: dubhe-model + labels: + app: dubhe-model + service: dubhe-model +spec: + type: NodePort + ports: + - port: 8888 + name: http + - port: 5005 + name: debug + selector: + app: dubhe-model +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: dubhe-model + labels: + account: dubhe-model +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: dubhe-model-v1 + labels: + app: dubhe-model + version: v1 +spec: + replicas: 1 + selector: + matchLabels: + app: dubhe-model + version: v1 + template: + metadata: + labels: + app: dubhe-model + version: v1 + spec: + serviceAccountName: dubhe-model + containers: + - name: dubhe-model + image: harbor.test.com/dubhe/dubhe-spring-cloud-k8s:env-value + imagePullPolicy: Always + env: + - name: JAR_BALL + value: "dubhe-model-0.0.1-SNAPSHOT-exec.jar --spring.profiles.active=env-value" + - name: JVM_PARAM + value: "-Xms1024m -Xmx1024m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=containerLogPath/dubhe-model-dump.hprof" + ports: + - containerPort: 8888 + - containerPort: 5005 + volumeMounts: + - mountPath: "fsPath" + name: "fs-volume" + readOnly: false + - mountPath: "containerLogPath" + name: "log-volume" + readOnly: false + - name: "dockersock" + mountPath: "/var/run/docker.sock" + volumes: + - name: "fs-volume" + hostPath: + path: "fsPath" + type: "Directory" + - name: "log-volume" + hostPath: + path: "hostLogPath" + type: "DirectoryOrCreate" + - name: "dockersock" + hostPath: + path: "/var/run/docker.sock" +################################################################################################## +# dubhe-notebook +################################################################################################## +--- +apiVersion: v1 +kind: Service +metadata: + name: dubhe-notebook + labels: + app: dubhe-notebook + service: dubhe-notebook +spec: + type: NodePort + ports: + - port: 8863 + name: http + - port: 5005 + name: debug + selector: + app: dubhe-notebook +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: dubhe-notebook + labels: + account: dubhe-notebook +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: dubhe-notebook-v1 + labels: + app: dubhe-notebook + version: v1 +spec: + replicas: 1 + selector: + matchLabels: + app: dubhe-notebook + version: v1 + template: + metadata: + labels: + app: dubhe-notebook + version: v1 + spec: + serviceAccountName: dubhe-notebook + containers: + - name: dubhe-notebook + image: harbor.test.com/dubhe/dubhe-spring-cloud-k8s:env-value + imagePullPolicy: Always + env: + - name: JAR_BALL + value: "dubhe-notebook-0.0.1-SNAPSHOT-exec.jar --spring.profiles.active=env-value" + - name: JVM_PARAM + value: "-Xms1024m -Xmx1024m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=containerLogPath/dubhe-notebook-dump.hprof" + ports: + - containerPort: 8863 + - containerPort: 5005 + volumeMounts: + - mountPath: "fsPath" + name: "fs-volume" + readOnly: false + - mountPath: "containerLogPath" + name: "log-volume" + readOnly: false + - name: "dockersock" + mountPath: "/var/run/docker.sock" + volumes: + - name: "fs-volume" + hostPath: + path: "fsPath" + type: "Directory" + - name: "log-volume" + hostPath: + path: "hostLogPath" + type: "DirectoryOrCreate" + - name: "dockersock" + hostPath: + path: "/var/run/docker.sock" +################################################################################################## +# dubhe-data-dcm +################################################################################################## +--- +apiVersion: v1 +kind: Service +metadata: + name: dubhe-data-dcm + labels: + app: dubhe-data-dcm + service: dubhe-data-dcm +spec: + type: NodePort + ports: + - port: 8011 + name: http + selector: + app: dubhe-data-dcm +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: dubhe-data-dcm + labels: + account: dubhe-data-dcm +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: dubhe-data-dcm-v1 + labels: + app: dubhe-data-dcm + version: v1 +spec: + replicas: 1 + selector: + matchLabels: + app: dubhe-data-dcm + version: v1 + template: + metadata: + labels: + app: dubhe-data-dcm + version: v1 + spec: + serviceAccountName: dubhe-data-dcm + containers: + - name: dubhe-data-dcm + image: harbor.test.com/dubhe/dubhe-spring-cloud-k8s:env-value + imagePullPolicy: Always + env: + - name: JAR_BALL + value: "dubhe-data-dcm-0.0.1-SNAPSHOT-exec.jar --spring.profiles.active=env-value" + - name: JVM_PARAM + value: "-Xms1024m -Xmx1024m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=containerLogPath/dubhe-data-dcm-dump.hprof" + ports: + - containerPort: 8011 + volumeMounts: + - mountPath: "fsPath" + name: "fs-volume" + readOnly: false + - mountPath: "containerLogPath" + name: "log-volume" + readOnly: false + - name: "dockersock" + mountPath: "/var/run/docker.sock" + volumes: + - name: "fs-volume" + hostPath: + path: "fsPath" + type: "Directory" + - name: "log-volume" + hostPath: + path: "hostLogPath" + type: "DirectoryOrCreate" + - name: "dockersock" + hostPath: + path: "/var/run/docker.sock" +################################################################################################## +# dubhe-data-task +################################################################################################## +--- +apiVersion: v1 +kind: Service +metadata: + name: dubhe-data-task + labels: + app: dubhe-data-task + service: dubhe-data-task +spec: + type: NodePort + ports: + - port: 8801 + name: http + selector: + app: dubhe-data-task +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: dubhe-data-task + labels: + account: dubhe-data-task +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: dubhe-data-task-v1 + labels: + app: dubhe-data-task + version: v1 +spec: + replicas: 1 + selector: + matchLabels: + app: dubhe-data-task + version: v1 + template: + metadata: + labels: + app: dubhe-data-task + version: v1 + spec: + serviceAccountName: dubhe-data-task + containers: + - name: dubhe-data-task + image: harbor.test.com/dubhe/dubhe-spring-cloud-k8s:env-value + imagePullPolicy: Always + env: + - name: JAR_BALL + value: "dubhe-data-task-0.0.1-SNAPSHOT-exec.jar --spring.profiles.active=env-value" + - name: JVM_PARAM + value: "-Xms1024m -Xmx1024m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=containerLogPath/dubhe-data-task-dump.hprof" + ports: + - containerPort: 8801 + volumeMounts: + - mountPath: "fsPath" + name: "fs-volume" + readOnly: false + - mountPath: "containerLogPath" + name: "log-volume" + readOnly: false + - name: "dockersock" + mountPath: "/var/run/docker.sock" + volumes: + - name: "fs-volume" + hostPath: + path: "fsPath" + type: "Directory" + - name: "log-volume" + hostPath: + path: "hostLogPath" + type: "DirectoryOrCreate" + - name: "dockersock" + hostPath: + path: "/var/run/docker.sock" +################################################################################################## +# dubhe-train +################################################################################################## +--- +apiVersion: v1 +kind: Service +metadata: + name: dubhe-train + labels: + app: dubhe-train + service: dubhe-train +spec: + type: NodePort + ports: + - port: 8890 + name: http + selector: + app: dubhe-train +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: dubhe-train + labels: + account: dubhe-train +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: dubhe-train-v1 + labels: + app: dubhe-train + version: v1 +spec: + replicas: 1 + selector: + matchLabels: + app: dubhe-train + version: v1 + template: + metadata: + labels: + app: dubhe-train + version: v1 + spec: + serviceAccountName: dubhe-train + containers: + - name: dubhe-train + image: harbor.test.com/dubhe/dubhe-spring-cloud-k8s:env-value + imagePullPolicy: Always + env: + - name: JAR_BALL + value: "dubhe-train-0.0.1-SNAPSHOT-exec.jar --spring.profiles.active=env-value" + - name: JVM_PARAM + value: "-Xms1024m -Xmx1024m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=containerLogPath/dubhe-train-dump.hprof" + ports: + - containerPort: 8890 + volumeMounts: + - mountPath: "fsPath" + name: "fs-volume" + readOnly: false + - mountPath: "containerLogPath" + name: "log-volume" + readOnly: false + - name: "dockersock" + mountPath: "/var/run/docker.sock" + volumes: + - name: "fs-volume" + hostPath: + path: "fsPath" + type: "Directory" + - name: "log-volume" + hostPath: + path: "hostLogPath" + type: "DirectoryOrCreate" + - name: "dockersock" + hostPath: + path: "/var/run/docker.sock" +################################################################################################## +# dubhe-optimize +################################################################################################## +--- +apiVersion: v1 +kind: Service +metadata: + name: dubhe-optimize + labels: + app: dubhe-optimize + service: dubhe-optimize +spec: + type: NodePort + ports: + - port: 8899 + name: http + - port: 5005 + name: debug + selector: + app: dubhe-optimize +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: dubhe-optimize + labels: + account: dubhe-optimize +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: dubhe-optimize-v1 + labels: + app: dubhe-optimize + version: v1 +spec: + replicas: 1 + selector: + matchLabels: + app: dubhe-optimize + version: v1 + template: + metadata: + labels: + app: dubhe-optimize + version: v1 + spec: + serviceAccountName: dubhe-optimize + containers: + - name: dubhe-optimize + image: harbor.test.com/dubhe/dubhe-spring-cloud-k8s:env-value + imagePullPolicy: Always + env: + - name: JAR_BALL + value: "dubhe-optimize-0.0.1-SNAPSHOT-exec.jar --spring.profiles.active=env-value" + - name: JVM_PARAM + value: "-Xms1024m -Xmx1024m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=containerLogPath/dubhe-optimize-dump.hprof" + ports: + - containerPort: 8899 + - containerPort: 5005 + volumeMounts: + - mountPath: "fsPath" + name: "fs-volume" + readOnly: false + - mountPath: "containerLogPath" + name: "log-volume" + readOnly: false + - name: "dockersock" + mountPath: "/var/run/docker.sock" + volumes: + - name: "fs-volume" + hostPath: + path: "fsPath" + type: "Directory" + - name: "log-volume" + hostPath: + path: "hostLogPath" + type: "DirectoryOrCreate" + - name: "dockersock" + hostPath: + path: "/var/run/docker.sock" +################################################################################################## +# dubhe-serving +################################################################################################## +--- +apiVersion: v1 +kind: Service +metadata: + name: dubhe-serving + labels: + app: dubhe-serving + service: dubhe-serving +spec: + type: NodePort + ports: + - port: 8898 + name: http + - port: 5005 + name: debug + selector: + app: dubhe-serving +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: dubhe-serving + labels: + account: dubhe-serving +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: dubhe-serving-v1 + labels: + app: dubhe-serving + version: v1 +spec: + replicas: 1 + selector: + matchLabels: + app: dubhe-serving + version: v1 + template: + metadata: + labels: + app: dubhe-serving + version: v1 + spec: + serviceAccountName: dubhe-serving + containers: + - name: dubhe-serving + image: harbor.test.com/dubhe/dubhe-spring-cloud-k8s:env-value + imagePullPolicy: Always + env: + - name: JAR_BALL + value: "dubhe-serving-0.0.1-SNAPSHOT-exec.jar --spring.profiles.active=env-value" + - name: JVM_PARAM + value: "-Xms1024m -Xmx1024m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=containerLogPath/dubhe-serving-dump.hprof" + ports: + - containerPort: 8898 + - containerPort: 5005 + volumeMounts: + - mountPath: "fsPath" + name: "fs-volume" + readOnly: false + - mountPath: "containerLogPath" + name: "log-volume" + readOnly: false + - name: "dockersock" + mountPath: "/var/run/docker.sock" + volumes: + - name: "fs-volume" + hostPath: + path: "fsPath" + type: "Directory" + - name: "log-volume" + hostPath: + path: "hostLogPath" + type: "DirectoryOrCreate" + - name: "dockersock" + hostPath: + path: "/var/run/docker.sock" +################################################################################################## +# dubhe-serving-gateway +################################################################################################## +--- +apiVersion: v1 +kind: Service +metadata: + name: dubhe-serving-gateway + labels: + app: dubhe-serving-gateway + service: dubhe-serving-gateway +spec: + type: NodePort + ports: + - port: 8081 + name: http + nodePort: 30848 + - port: 5005 + name: debug + selector: + app: dubhe-serving-gateway +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: dubhe-serving-gateway + labels: + account: dubhe-serving-gateway +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: dubhe-serving-gateway-v1 + labels: + app: dubhe-serving-gateway + version: v1 +spec: + replicas: 1 + selector: + matchLabels: + app: dubhe-serving-gateway + version: v1 + template: + metadata: + labels: + app: dubhe-serving-gateway + version: v1 + spec: + serviceAccountName: dubhe-serving-gateway + containers: + - name: dubhe-serving-gateway + image: harbor.test.com/dubhe/dubhe-spring-cloud-k8s:env-value + imagePullPolicy: Always + env: + - name: JAR_BALL + value: "dubhe-serving-gateway-0.0.1-SNAPSHOT-exec.jar --spring.profiles.active=env-value" + - name: JVM_PARAM + value: "-Xms512m -Xmx512m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=containerLogPath/dubhe-serving-gateway-dump.hprof" + ports: + - containerPort: 8081 + - containerPort: 5505 + volumeMounts: + - mountPath: "fsPath" + name: "fs-volume" + readOnly: false + - mountPath: "containerLogPath" + name: "log-volume" + readOnly: false + - name: "dockersock" + mountPath: "/var/run/docker.sock" + volumes: + - name: "fs-volume" + hostPath: + path: "fsPath" + type: "Directory" + - name: "log-volume" + hostPath: + path: "hostLogPath" + type: "DirectoryOrCreate" + - name: "dockersock" + hostPath: + path: "/var/run/docker.sock" +################################################################################################## +# gateway +################################################################################################## +--- +apiVersion: v1 +kind: Service +metadata: + name: gateway + labels: + app: gateway + service: gateway +spec: + type: NodePort + ports: + - port: 8800 + name: http + nodePort: gatewayNodePort + selector: + app: gateway +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: gateway + labels: + account: gateway +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: gateway-v1 + labels: + app: gateway + version: v1 +spec: + replicas: 1 + selector: + matchLabels: + app: gateway + version: v1 + template: + metadata: + labels: + app: gateway + version: v1 + spec: + serviceAccountName: gateway + containers: + - name: gateway + image: harbor.test.com/dubhe/dubhe-spring-cloud-k8s:env-value + imagePullPolicy: Always + env: + - name: JAR_BALL + value: "gateway-0.0.1-SNAPSHOT-exec.jar --spring.profiles.active=env-value" + - name: JVM_PARAM + value: "-Xms1024m -Xmx1024m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=containerLogPath/gateway-dump.hprof" + ports: + - containerPort: 8800 + volumeMounts: + - mountPath: "fsPath" + name: "fs-volume" + readOnly: false + - mountPath: "containerLogPath" + name: "log-volume" + readOnly: false + - name: "dockersock" + mountPath: "/var/run/docker.sock" + volumes: + - name: "fs-volume" + hostPath: + path: "fsPath" + type: "Directory" + - name: "log-volume" + hostPath: + path: "hostLogPath" + type: "DirectoryOrCreate" + - name: "dockersock" + hostPath: + path: "/var/run/docker.sock" \ No newline at end of file diff --git a/dubhe-server/deploy/cloud/server-gateway.yaml b/dubhe-server/deploy/cloud/server-gateway.yaml new file mode 100644 index 0000000..6b598eb --- /dev/null +++ b/dubhe-server/deploy/cloud/server-gateway.yaml @@ -0,0 +1,79 @@ +################################################################################################## +# gateway +################################################################################################## +--- +apiVersion: v1 +kind: Service +metadata: + name: gateway + labels: + app: gateway + service: gateway +spec: + type: NodePort + ports: + - port: 8800 + name: http + nodePort: gatewayNodePort + selector: + app: gateway +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: gateway + labels: + account: gateway +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: gateway-v1 + labels: + app: gateway + version: v1 +spec: + replicas: 1 + selector: + matchLabels: + app: gateway + version: v1 + template: + metadata: + labels: + app: gateway + version: v1 + spec: + serviceAccountName: gateway + containers: + - name: gateway + image: harbor.test.com/dubhe/dubhe-spring-cloud-k8s:env-value + imagePullPolicy: Always + env: + - name: JAR_BALL + value: "gateway-0.0.1-SNAPSHOT-exec.jar --spring.profiles.active=env-value" + - name: JVM_PARAM + value: "-Xms1024m -Xmx1024m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=containerLogPath/gateway-dump.hprof" + ports: + - containerPort: 8800 + volumeMounts: + - mountPath: "fsPath" + name: "fs-volume" + readOnly: false + - mountPath: "containerLogPath" + name: "log-volume" + readOnly: false + - name: "dockersock" + mountPath: "/var/run/docker.sock" + volumes: + - name: "fs-volume" + hostPath: + path: "fsPath" + type: "Directory" + - name: "log-volume" + hostPath: + path: "hostLogPath" + type: "DirectoryOrCreate" + - name: "dockersock" + hostPath: + path: "/var/run/docker.sock" \ No newline at end of file diff --git a/dubhe-server/dubhe-algorithm/pom.xml b/dubhe-server/dubhe-algorithm/pom.xml new file mode 100644 index 0000000..966a761 --- /dev/null +++ b/dubhe-server/dubhe-algorithm/pom.xml @@ -0,0 +1,125 @@ + + + + server + org.dubhe + 0.0.1-SNAPSHOT + + 4.0.0 + dubhe-algorithm + 0.0.1-SNAPSHOT + algorithm 算法管理 + Dubhe algorithm + + + + org.dubhe.biz + base + ${org.dubhe.biz.base.version} + + + org.dubhe.biz + data-permission + ${org.dubhe.biz.data-permission.version} + + + org.dubhe.biz + data-permission + ${org.dubhe.biz.data-permission.version} + + + org.dubhe.biz + log + ${org.dubhe.biz.log.version} + + + org.dubhe.biz + file + ${org.dubhe.biz.file.version} + + + + org.dubhe.cloud + swagger + ${org.dubhe.cloud.swagger.version} + + + + org.dubhe.cloud + auth-config + ${org.dubhe.cloud.auth-config.version} + + + + org.dubhe.cloud + remote-call + ${org.dubhe.cloud.remote-call.version} + + + + org.dubhe.cloud + registration + ${org.dubhe.cloud.registration.version} + + + + org.dubhe.cloud + configuration + ${org.dubhe.cloud.configuration.version} + + + + org.dubhe + common-k8s + ${org.dubhe.common-k8s.version} + + + + org.dubhe + common-recycle + ${org.dubhe.common-recycle.version} + + + + org.dubhe.cloud + unit-test + ${org.dubhe.cloud.unit-test.version} + test + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + org.springframework.boot + spring-boot-maven-plugin + + false + true + exec + + + + + org.apache.maven.plugins + maven-surefire-plugin + + true + + + + + + true + src/main/resources + + + + + \ No newline at end of file diff --git a/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/AlgorithmApplication.java b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/AlgorithmApplication.java new file mode 100644 index 0000000..ae0e7a2 --- /dev/null +++ b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/AlgorithmApplication.java @@ -0,0 +1,37 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.algorithm; + +import org.mybatis.spring.annotation.MapperScan; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.scheduling.annotation.EnableAsync; +import org.springframework.scheduling.annotation.EnableScheduling; + +/** + * @description alrigothm启动类 + * @date 2020-12-18 + */ +@SpringBootApplication(scanBasePackages = "org.dubhe") +@MapperScan(basePackages = {"org.dubhe.**.dao"}) +@EnableScheduling +@EnableAsync +public class AlgorithmApplication { + public static void main(String[] args) { + SpringApplication.run(AlgorithmApplication.class, args); + } +} \ No newline at end of file diff --git a/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/async/TrainAlgorithmUploadAsync.java b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/async/TrainAlgorithmUploadAsync.java new file mode 100644 index 0000000..9f66d51 --- /dev/null +++ b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/async/TrainAlgorithmUploadAsync.java @@ -0,0 +1,119 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.algorithm.async; + +import org.dubhe.algorithm.client.NoteBookClient; +import org.dubhe.algorithm.constant.AlgorithmConstant; +import org.dubhe.algorithm.dao.PtTrainAlgorithmMapper; +import org.dubhe.algorithm.domain.dto.PtTrainAlgorithmCreateDTO; +import org.dubhe.algorithm.domain.entity.PtTrainAlgorithm; +import org.dubhe.biz.base.context.UserContext; +import org.dubhe.biz.base.dto.NoteBookAlgorithmUpdateDTO; +import org.dubhe.biz.base.enums.AlgorithmStatusEnum; +import org.dubhe.biz.base.exception.BusinessException; +import org.dubhe.biz.file.api.FileStoreApi; +import org.dubhe.biz.file.enums.BizPathEnum; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.dubhe.k8s.utils.K8sNameTool; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Component; + +import javax.annotation.Resource; +import java.util.Arrays; + +/** + * @description 异步上传算法 + * @date 2020-08-10 + */ +@Component +public class TrainAlgorithmUploadAsync { + + @Autowired + private K8sNameTool k8sNameTool; + + @Autowired + private NoteBookClient noteBookClient; + + @Autowired + private PtTrainAlgorithmMapper trainAlgorithmMapper; + + @Resource(name = "hostFileStoreApiImpl") + private FileStoreApi fileStoreApi; + + /** + * 异步任务创建算法 + * + * @param user 当前登录用户信息 + * @param ptTrainAlgorithm 算法信息 + * @param trainAlgorithmCreateDTO 创建算法条件 + */ + @Async(AlgorithmConstant.ALGORITHM_EXECUTOR) + public void createTrainAlgorithm(UserContext user, PtTrainAlgorithm ptTrainAlgorithm, PtTrainAlgorithmCreateDTO trainAlgorithmCreateDTO) { + String path = fileStoreApi.getBucket() + trainAlgorithmCreateDTO.getCodeDir(); + //校验创建算法来源(true:由fork创建算法,false:其它创建算法方式),若为true则拷贝预置算法文件至新路径 + if (trainAlgorithmCreateDTO.getFork()) { + //生成算法相对路径 + String algorithmPath = k8sNameTool.getPath(BizPathEnum.ALGORITHM, user.getId()); + //拷贝预置算法文件夹 + boolean copyResult = fileStoreApi.copyPath(fileStoreApi.getRootDir() + path, fileStoreApi.getRootDir() + fileStoreApi.getBucket() + algorithmPath); + if (!copyResult) { + LogUtil.error(LogEnum.BIZ_ALGORITHM, "The user {} copied the preset algorithm path {} successfully", user.getUsername(), path); + updateTrainAlgorithm(ptTrainAlgorithm, trainAlgorithmCreateDTO, false); + throw new BusinessException("内部错误"); + } + + ptTrainAlgorithm.setCodeDir(algorithmPath); + + //修改算法上传状态 + updateTrainAlgorithm(ptTrainAlgorithm, trainAlgorithmCreateDTO, true); + + } else { + updateTrainAlgorithm(ptTrainAlgorithm, trainAlgorithmCreateDTO, true); + } + } + + + /** + * 更新上传算法状态 + * + * @param ptTrainAlgorithm 算法信息 + * @param trainAlgorithmCreateDTO 创建算法的条件 + * @param flag 创建算法是否成功(true:成功,false:失败) + */ + public void updateTrainAlgorithm(PtTrainAlgorithm ptTrainAlgorithm, PtTrainAlgorithmCreateDTO trainAlgorithmCreateDTO, boolean flag) { + + LogUtil.info(LogEnum.BIZ_ALGORITHM, "async update algorithmPath by algorithmId:{} and update noteBook by noteBookId:{}", ptTrainAlgorithm.getId(), trainAlgorithmCreateDTO.getNoteBookId()); + if (flag) { + ptTrainAlgorithm.setAlgorithmStatus(AlgorithmStatusEnum.SUCCESS.getCode()); + //更新fork算法新路径 + trainAlgorithmMapper.updateById(ptTrainAlgorithm); + //保存算法根据notbookId更新算法id + if (trainAlgorithmCreateDTO.getNoteBookId() != null) { + LogUtil.info(LogEnum.BIZ_ALGORITHM, "Save algorithm Update algorithm ID :{} according to notBookId:{}", trainAlgorithmCreateDTO.getNoteBookId(), ptTrainAlgorithm.getId()); + NoteBookAlgorithmUpdateDTO noteBookAlgorithmUpdateDTO = new NoteBookAlgorithmUpdateDTO(); + noteBookAlgorithmUpdateDTO.setAlgorithmId(ptTrainAlgorithm.getId()); + noteBookAlgorithmUpdateDTO.setNotebookIdList(Arrays.asList(trainAlgorithmCreateDTO.getNoteBookId())); + noteBookClient.updateNoteBookAlgorithm(noteBookAlgorithmUpdateDTO); + } + } else { + ptTrainAlgorithm.setAlgorithmStatus(AlgorithmStatusEnum.FAIL.getCode()); + trainAlgorithmMapper.updateById(ptTrainAlgorithm); + } + } +} diff --git a/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/client/ImageClient.java b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/client/ImageClient.java new file mode 100644 index 0000000..490c9eb --- /dev/null +++ b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/client/ImageClient.java @@ -0,0 +1,42 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.algorithm.client; + +import org.dubhe.algorithm.client.fallback.ImageClientFallback; +import org.dubhe.biz.base.constant.ApplicationNameConst; +import org.dubhe.biz.base.dto.PtImageQueryUrlDTO; +import org.dubhe.biz.base.vo.DataResponseBody; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.cloud.openfeign.SpringQueryMap; +import org.springframework.web.bind.annotation.GetMapping; + +/** + * @description image远程服务调用接口 + * @date 2020-12-14 + */ +@FeignClient(value = ApplicationNameConst.SERVER_IMAGE, contextId = "imageClient", fallback = ImageClientFallback.class) +public interface ImageClient { + + /** + * 远程获取镜像URL + * + * @param ptImageQueryUrlDTO 查询镜像路径DTO + * @return string 镜像url + */ + @GetMapping(value = "/ptImage/imageUrl") + DataResponseBody getImageUrl(@SpringQueryMap PtImageQueryUrlDTO ptImageQueryUrlDTO); +} diff --git a/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/client/NoteBookClient.java b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/client/NoteBookClient.java new file mode 100644 index 0000000..ed33ffe --- /dev/null +++ b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/client/NoteBookClient.java @@ -0,0 +1,54 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.algorithm.client; + +import org.dubhe.algorithm.client.fallback.NoteBookClientFallback; +import org.dubhe.biz.base.constant.ApplicationNameConst; +import org.dubhe.biz.base.dto.NoteBookAlgorithmQueryDTO; +import org.dubhe.biz.base.dto.NoteBookAlgorithmUpdateDTO; +import org.dubhe.biz.base.vo.DataResponseBody; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.cloud.openfeign.SpringQueryMap; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PutMapping; + +import java.util.List; + +/** + * @description notebook远程服务调用接口 + * @date 2020-12-14 + */ +@FeignClient(value = ApplicationNameConst.SERVER_NOTEBOOK, contextId = "noteBookClient", fallback = NoteBookClientFallback.class) +public interface NoteBookClient { + + /** + * 更新notebook算法ID + * + * @param noteBookAlgorithmUpdateDTO 更新notebook算法ID DTO + */ + @PutMapping(value = "/notebooks/algorithm") + void updateNoteBookAlgorithm(NoteBookAlgorithmUpdateDTO noteBookAlgorithmUpdateDTO); + + /** + * 获取notebook算法ID + * + * @param noteBookAlgorithmQueryDTO 获取notebook算法ID DTO + * @return 算法ID + */ + @GetMapping(value = "/notebooks/algorithm") + DataResponseBody> getNoteBookIdByAlgorithm(@SpringQueryMap NoteBookAlgorithmQueryDTO noteBookAlgorithmQueryDTO); +} diff --git a/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/client/fallback/ImageClientFallback.java b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/client/fallback/ImageClientFallback.java new file mode 100644 index 0000000..595d8a8 --- /dev/null +++ b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/client/fallback/ImageClientFallback.java @@ -0,0 +1,37 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.algorithm.client.fallback; + + +import org.dubhe.algorithm.client.ImageClient; +import org.dubhe.biz.base.dto.PtImageQueryUrlDTO; +import org.dubhe.biz.base.vo.DataResponseBody; +import org.dubhe.biz.dataresponse.factory.DataResponseFactory; +import org.springframework.stereotype.Component; + +/** + * @description image远程服务调用类熔断 + * @date 2020-12-14 + */ +@Component +public class ImageClientFallback implements ImageClient { + + @Override + public DataResponseBody getImageUrl(PtImageQueryUrlDTO ptImageQueryUrlDTO) { + return DataResponseFactory.failed("call image server getImageUrl error"); + } +} diff --git a/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/client/fallback/NoteBookClientFallback.java b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/client/fallback/NoteBookClientFallback.java new file mode 100644 index 0000000..4d60941 --- /dev/null +++ b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/client/fallback/NoteBookClientFallback.java @@ -0,0 +1,42 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.algorithm.client.fallback; + +import org.dubhe.algorithm.client.NoteBookClient; +import org.dubhe.biz.base.dto.NoteBookAlgorithmQueryDTO; +import org.dubhe.biz.base.dto.NoteBookAlgorithmUpdateDTO; +import org.dubhe.biz.base.vo.DataResponseBody; +import org.dubhe.biz.dataresponse.factory.DataResponseFactory; +import org.springframework.stereotype.Component; + +/** + * @description notebook远程服务调用类熔断 + * @date 2020-12-14 + */ +@Component +public class NoteBookClientFallback implements NoteBookClient { + + @Override + public void updateNoteBookAlgorithm(NoteBookAlgorithmUpdateDTO noteBookAlgorithmUpdateDTO) { + DataResponseFactory.failed("call notebook server updateNoteBookAlgorithm error"); + } + + @Override + public DataResponseBody getNoteBookIdByAlgorithm(NoteBookAlgorithmQueryDTO noteBookAlgorithmQueryDTO) { + return DataResponseFactory.failed("call notebook server getNoteBookIdByAlgorithm error"); + } +} diff --git a/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/config/AlgorithmPoolConfig.java b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/config/AlgorithmPoolConfig.java new file mode 100644 index 0000000..aac88eb --- /dev/null +++ b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/config/AlgorithmPoolConfig.java @@ -0,0 +1,80 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.algorithm.config; + +import org.dubhe.algorithm.constant.AlgorithmConstant; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.scheduling.annotation.AsyncConfigurer; +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; + +import java.util.concurrent.Executor; +import java.util.concurrent.ThreadPoolExecutor; + +/** + * @description 线程池配置类 + * @date 2020-07-17 + */ +@Configuration +public class AlgorithmPoolConfig implements AsyncConfigurer { + + @Value("${basepool.corePoolSize:40}") + private Integer corePoolSize; + @Value("${basepool.maximumPoolSize:60}") + private Integer maximumPoolSize; + @Value("${basepool.keepAliveTime:120}") + private Integer keepAliveTime; + @Value("${basepool.blockQueueSize:20}") + private Integer blockQueueSize; + + /** + * 算法任务异步处理线程池 + * @return Executor 线程实例 + */ + @Bean(AlgorithmConstant.ALGORITHM_EXECUTOR) + @Override + public Executor getAsyncExecutor() { + ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); + //核心线程数 + taskExecutor.setCorePoolSize(corePoolSize); + taskExecutor.setAllowCoreThreadTimeOut(true); + //最大线程数 + taskExecutor.setMaxPoolSize(maximumPoolSize); + //超时时间 + taskExecutor.setKeepAliveSeconds(keepAliveTime); + //配置队列大小 + taskExecutor.setQueueCapacity(blockQueueSize); + //配置线程池前缀 + taskExecutor.setThreadNamePrefix("async-algorithm-"); + //拒绝策略 + taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy()); + taskExecutor.initialize(); + return taskExecutor; + } + + @Override + public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { + LogUtil.error(LogEnum.BIZ_ALGORITHM, "开始捕获算法管理异步任务异常信息-----》》》"); + return (ex, method, params) -> { + LogUtil.error(LogEnum.BIZ_ALGORITHM, "算法管理方法名{}的异步任务执行失败,参数信息:{},异常信息:{}", method.getName(), params, ex); + }; + } +} diff --git a/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/constant/AlgorithmConstant.java b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/constant/AlgorithmConstant.java new file mode 100644 index 0000000..3405fb5 --- /dev/null +++ b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/constant/AlgorithmConstant.java @@ -0,0 +1,52 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.algorithm.constant; + +/** + * @description 常量 + * @date 2020-04-10 + */ +public class AlgorithmConstant { + + + /** + * 排序规则 + */ + public static final String SORT_ASC = "asc"; + + public static final String SORT_DESC = "desc"; + + /** + * ZIP压缩文件后缀 + */ + public static final String COMPRESS_ZIP = ".zip"; + + /** + * 可推理文件后缀 + */ + public static final String COMPRESS_PY = ".py"; + + + /** + * id + **/ + public static final String ID = "id"; + + public final static String ALGORITHM_EXECUTOR = "algorithmExecutor"; + +} diff --git a/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/constant/TrainAlgorithmConfig.java b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/constant/TrainAlgorithmConfig.java new file mode 100644 index 0000000..960205c --- /dev/null +++ b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/constant/TrainAlgorithmConfig.java @@ -0,0 +1,62 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.algorithm.constant; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +/** + * @description 算法常量 + * @date 2020-06-02 + */ +@Data +@Component +@ConfigurationProperties(prefix = "train-algorithm") +public class TrainAlgorithmConfig { + + /** + * 是否输出训练结果 + */ + private Boolean isTrainModelOut; + + /** + * 是否输出训练信息 + */ + private Boolean isTrainOut; + + /** + * 是否输出可视化日志 + */ + private Boolean isVisualizedLog; + + /** + * 设置默认算法来源(1为我的算法,2为预置算法) + */ + private Integer algorithmSource; + + /** + * 设置fork默认值(fork:创建算法来源) + */ + private Boolean fork; + + /** + * 设置inference默认值(inference:上传算法是否支持推理) + */ + private Boolean inference; +} diff --git a/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/constant/UserAuxiliaryInfoConstant.java b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/constant/UserAuxiliaryInfoConstant.java new file mode 100644 index 0000000..c59c7d7 --- /dev/null +++ b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/constant/UserAuxiliaryInfoConstant.java @@ -0,0 +1,31 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.algorithm.constant; + +import lombok.Data; + +/** + * @description 算法用途 + * @date 2020-06-23 + */ +@Data +public class UserAuxiliaryInfoConstant { + + public static final String ALGORITHM_USAGE = "algorithem_usage"; + +} diff --git a/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/dao/PtTrainAlgorithmMapper.java b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/dao/PtTrainAlgorithmMapper.java new file mode 100644 index 0000000..ba59c52 --- /dev/null +++ b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/dao/PtTrainAlgorithmMapper.java @@ -0,0 +1,70 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.algorithm.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; +import org.apache.ibatis.annotations.Update; +import org.dubhe.biz.base.annotation.DataPermission; +import org.dubhe.algorithm.domain.entity.PtTrainAlgorithm; + +import java.util.List; +import java.util.Set; + +/** + * @description 训练算法Mapper + * @date 2020-04-27 + */ +@DataPermission(ignoresMethod = {"insert"}) +public interface PtTrainAlgorithmMapper extends BaseMapper { + + /** + * 根据算法id查询算法信息 + * @param id 算法id + * @return PtTrainAlgorithm 算法信息 + */ + @Select("select * from pt_train_algorithm where id= #{id}") + PtTrainAlgorithm selectAllById(@Param("id") Long id); + + /** + * 根据算法id集合查询对应的算法信息 + * @param ids 算法集合id + * @return List 算法信息集合 + */ + @Select({ + "" + }) + List selectAllBatchIds(@Param("ids") Set ids); + + /** + * 算法还原 + * @param id 算法id + * @param deleteFlag 删除状态 + * @return 数量 + */ + @Update("update pt_train_algorithm set deleted = #{deleteFlag} where id = #{id}") + int updateStatusById(@Param("id") Long id, @Param("deleteFlag") boolean deleteFlag); +} diff --git a/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/dao/PtTrainAlgorithmUsageMapper.java b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/dao/PtTrainAlgorithmUsageMapper.java new file mode 100644 index 0000000..58e3e8a --- /dev/null +++ b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/dao/PtTrainAlgorithmUsageMapper.java @@ -0,0 +1,32 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.algorithm.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.dubhe.algorithm.domain.entity.PtTrainAlgorithmUsage; +import org.dubhe.biz.base.annotation.DataPermission; + +/** + * + * @description 用户辅助信息Mapper 接口 + * @date 2020-06-23 + */ +@DataPermission(ignoresMethod = "insert") +public interface PtTrainAlgorithmUsageMapper extends BaseMapper { + +} diff --git a/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/domain/dto/PtModelAlgorithmCreateDTO.java b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/domain/dto/PtModelAlgorithmCreateDTO.java new file mode 100644 index 0000000..88cac6a --- /dev/null +++ b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/domain/dto/PtModelAlgorithmCreateDTO.java @@ -0,0 +1,51 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.algorithm.domain.dto; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import lombok.experimental.Accessors; +import org.dubhe.algorithm.utils.TrainUtil; +import org.dubhe.biz.base.constant.MagicNumConstant; +import org.hibernate.validator.constraints.Length; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Pattern; +import java.io.Serializable; + +/** + * @description 模型优化上传算法入参 + * @date 2021-01-06 + */ +@Data +@Accessors(chain = true) +public class PtModelAlgorithmCreateDTO implements Serializable { + + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "算法名称,输入长度不能超过32个字符", required = true) + @NotBlank(message = "算法名称不能为空") + @Length(max = MagicNumConstant.THIRTY_TWO, message = "算法名称-输入长度不能超过32个字符") + @Pattern(regexp = TrainUtil.REGEXP, message = "算法名称支持字母、数字、汉字、英文横杠和下划线") + private String name; + + @ApiModelProperty(value = "代码目录(路径规则:/algorithm-manage/{userId}/{YYYYMMDDhhmmssSSS+四位随机数}/用户上传的算法具体文件(zip文件)名称或从notebook跳转时为/notebook/{userId}/{YYYYMMDDhhmmssSSS+四位随机数}/)", required = true) + @NotBlank(message = "代码目录不能为空") + @Length(max = MagicNumConstant.ONE_HUNDRED_TWENTY_EIGHT, message = "代码目录-输入长度不能超过128个字符") + private String path; + +} \ No newline at end of file diff --git a/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/domain/dto/PtTrainAlgorithmCreateDTO.java b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/domain/dto/PtTrainAlgorithmCreateDTO.java new file mode 100644 index 0000000..f1dc9dd --- /dev/null +++ b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/domain/dto/PtTrainAlgorithmCreateDTO.java @@ -0,0 +1,98 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.algorithm.domain.dto; + +import com.alibaba.fastjson.JSONObject; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import lombok.experimental.Accessors; +import org.dubhe.algorithm.utils.TrainUtil; +import org.dubhe.biz.base.constant.MagicNumConstant; +import org.hibernate.validator.constraints.Length; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Pattern; +import java.io.Serializable; + +/** + * @desciption 创建算法条件 + * @date 2020-04-29 + */ +@Data +@Accessors(chain = true) +public class PtTrainAlgorithmCreateDTO implements Serializable { + + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "算法名称,输入长度不能超过32个字符", required = true) + @NotBlank(message = "算法名称不能为空") + @Length(max = MagicNumConstant.THIRTY_TWO, message = "算法名称-输入长度不能超过32个字符") + @Pattern(regexp = TrainUtil.REGEXP, message = "算法名称支持字母、数字、汉字、英文横杠和下划线") + private String algorithmName; + + @ApiModelProperty("算法描述,输入长度不能超过256个字符") + @Length(max = MagicNumConstant.INTEGER_TWO_HUNDRED_AND_FIFTY_FIVE, message = "算法描述-输入长度不能超过256个字符") + private String description; + + @ApiModelProperty(value = "镜像版本") + private String imageTag; + + @ApiModelProperty(value = "镜像名称") + private String imageName; + + @ApiModelProperty(value = "创建算法来源(true:由fork创建算法,false:其它创建算法方式,null:默认false)") + private Boolean fork; + + @ApiModelProperty(value = "上传算法是否支持推理(true:可推理,false:不可推理,null:默认false)") + private Boolean inference; + + @ApiModelProperty(value = "代码目录(路径规则:/algorithm-manage/{userId}/{YYYYMMDDhhmmssSSS+四位随机数}/用户上传的算法具体文件(zip文件)名称或从notebook跳转时为/notebook/{userId}/{YYYYMMDDhhmmssSSS+四位随机数}/)", required = true) + @NotBlank(message = "代码目录不能为空") + @Length(max = MagicNumConstant.ONE_HUNDRED_TWENTY_EIGHT, message = "代码目录-输入长度不能超过128个字符") + private String codeDir; + + @ApiModelProperty(value = "运行命令,管理员使用") + @Length(max = MagicNumConstant.ONE_HUNDRED_TWENTY_EIGHT, message = "运行命令-输入长度不能超过128个字符") + private String runCommand; + + @ApiModelProperty("运行参数(算法来源为我的算法时为调优参数,算法来源为预置算法时为运行参数),管理员使用") + private JSONObject runParams; + + @ApiModelProperty("算法来源(1为我的算法,2为预置算法),管理员使用") + private Integer algorithmSource; + + @ApiModelProperty("算法用途,输入长度不能超过128个字符") + @Length(max = MagicNumConstant.ONE_HUNDRED_TWENTY_EIGHT, message = "算法用途-输入长度不能超过128个字符") + private String algorithmUsage; + + @ApiModelProperty("是否输出训练结果,不填则默认为true") + private Boolean isTrainModelOut; + + @ApiModelProperty("是否输出训练信息,不填则默认为true") + private Boolean isTrainOut; + + @ApiModelProperty("是否输出可视化日志,不填则默认为false") + private Boolean isVisualizedLog; + + @ApiModelProperty("noteBookId") + private Long noteBookId; + + @ApiModelProperty("资源拥有者ID") + private Long originUserId; + +} diff --git a/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/domain/dto/PtTrainAlgorithmDeleteDTO.java b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/domain/dto/PtTrainAlgorithmDeleteDTO.java new file mode 100644 index 0000000..4ffc4d2 --- /dev/null +++ b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/domain/dto/PtTrainAlgorithmDeleteDTO.java @@ -0,0 +1,42 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.algorithm.domain.dto; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import lombok.experimental.Accessors; + +import javax.validation.constraints.NotNull; +import java.io.Serializable; +import java.util.Set; + +/** + * @description 算法删除 + * @date 2020-07-02 + */ +@Data +@Accessors(chain = true) +public class PtTrainAlgorithmDeleteDTO implements Serializable { + + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "id", required = true) + @NotNull(message = "id不能为空") + private Set ids; + +} \ No newline at end of file diff --git a/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/domain/dto/PtTrainAlgorithmQueryDTO.java b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/domain/dto/PtTrainAlgorithmQueryDTO.java new file mode 100644 index 0000000..6f5e9d7 --- /dev/null +++ b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/domain/dto/PtTrainAlgorithmQueryDTO.java @@ -0,0 +1,60 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.algorithm.domain.dto; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.experimental.Accessors; +import org.dubhe.algorithm.utils.TrainUtil; +import org.dubhe.biz.base.constant.MagicNumConstant; +import org.dubhe.biz.db.annotation.Query; +import org.dubhe.biz.db.base.PageQueryBase; +import org.hibernate.validator.constraints.Length; + +import javax.validation.constraints.Max; +import javax.validation.constraints.Min; +import java.io.Serializable; + +/** + * @description 查询算法条件 + * @date 2020-04-29 + */ +@EqualsAndHashCode(callSuper = true) +@Data +@Accessors(chain = true) +public class PtTrainAlgorithmQueryDTO extends PageQueryBase implements Serializable { + + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "算法来源(1为我的算法, 2为预置算法)") + @Min(value = TrainUtil.NUMBER_ONE, message = "算法来源错误") + @Max(value = TrainUtil.NUMBER_TWO, message = "算法来源错误") + @Query(propName = "algorithm_source", type = Query.Type.EQ) + private Integer algorithmSource; + + @ApiModelProperty(value = "算法名称或者id") + @Length(max = MagicNumConstant.THIRTY_TWO, message = "算法名称或者id有误") + private String algorithmName; + + @ApiModelProperty(value = "算法用途") + private String algorithmUsage; + + @ApiModelProperty(value = "上传算法是否支持推理(true:可推理,false:不可推理)") + private Boolean inference; +} diff --git a/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/domain/dto/PtTrainAlgorithmUpdateDTO.java b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/domain/dto/PtTrainAlgorithmUpdateDTO.java new file mode 100644 index 0000000..adc57ff --- /dev/null +++ b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/domain/dto/PtTrainAlgorithmUpdateDTO.java @@ -0,0 +1,65 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.algorithm.domain.dto; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import lombok.experimental.Accessors; +import org.dubhe.algorithm.utils.TrainUtil; +import org.dubhe.biz.base.constant.MagicNumConstant; +import org.hibernate.validator.constraints.Length; + +import javax.validation.constraints.Min; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Pattern; +import java.io.Serializable; + +/** + * @description 修改算法 + * @date 2020-06-19 + */ +@Data +@Accessors(chain = true) +public class PtTrainAlgorithmUpdateDTO implements Serializable { + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "id", required = true) + @NotNull(message = "id不能为null") + @Min(value = TrainUtil.NUMBER_ONE, message = "id必须大于1") + private Long id; + + @ApiModelProperty(value = "算法名称,输入长度不能超过32个字符") + @Length(max = MagicNumConstant.THIRTY_TWO, message = "算法名称-输入长度不能超过32个字符") + @Pattern(regexp = TrainUtil.REGEXP, message = "算法名称支持字母、数字、汉字、英文横杠和下划线") + private String algorithmName; + + @ApiModelProperty("算法描述,输入长度不能超过256个字符") + @Length(max = MagicNumConstant.INTEGER_TWO_HUNDRED_AND_FIFTY_FIVE, message = "算法描述-输入长度不能超过256个字符") + private String description; + + @ApiModelProperty("算法用途,输入长度不能超过128个字符") + @Length(max = MagicNumConstant.ONE_HUNDRED_TWENTY_EIGHT, message = "算法用途-输入长度不能超过128个字符") + private String algorithmUsage; + + @ApiModelProperty("是否输出训练信息") + private Boolean isTrainOut; + + @ApiModelProperty("是否输出可视化日志") + private Boolean isVisualizedLog; + +} diff --git a/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/domain/dto/PtTrainAlgorithmUsageCreateDTO.java b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/domain/dto/PtTrainAlgorithmUsageCreateDTO.java new file mode 100644 index 0000000..7096c4a --- /dev/null +++ b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/domain/dto/PtTrainAlgorithmUsageCreateDTO.java @@ -0,0 +1,50 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.algorithm.domain.dto; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import lombok.experimental.Accessors; +import org.dubhe.algorithm.utils.TrainUtil; +import org.dubhe.biz.base.constant.MagicNumConstant; +import org.hibernate.validator.constraints.Length; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Pattern; +import java.io.Serializable; + +/** + * @description 创建算法用途条件 + * @date 2020-06-23 + */ +@Data +@Accessors(chain = true) +public class PtTrainAlgorithmUsageCreateDTO implements Serializable { + + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "名称输入长度不能超过32个字符", required = true) + @NotBlank(message = "名称不能为空") + @Length(max = MagicNumConstant.THIRTY_TWO, message = "名称-输入长度不能超过32个字符") + @Pattern(regexp = TrainUtil.REGEXP, message = "名称支持字母、数字、汉字、英文横杠和下划线") + private String auxInfo; + + @ApiModelProperty(value = "类型", hidden = true) + private String type; + +} diff --git a/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/domain/dto/PtTrainAlgorithmUsageDeleteDTO.java b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/domain/dto/PtTrainAlgorithmUsageDeleteDTO.java new file mode 100644 index 0000000..d6f04b6 --- /dev/null +++ b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/domain/dto/PtTrainAlgorithmUsageDeleteDTO.java @@ -0,0 +1,40 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.algorithm.domain.dto; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import lombok.experimental.Accessors; + +import javax.validation.constraints.NotNull; +import java.io.Serializable; + +/** + * @description 算法用途删除 + * @date 2020-07-02 + */ +@Data +@Accessors(chain = true) +public class PtTrainAlgorithmUsageDeleteDTO implements Serializable { + + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "id", required = true) + @NotNull(message = "id不能为空") + private Long[] ids; + +} \ No newline at end of file diff --git a/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/domain/dto/PtTrainAlgorithmUsageQueryDTO.java b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/domain/dto/PtTrainAlgorithmUsageQueryDTO.java new file mode 100644 index 0000000..e6cd4a2 --- /dev/null +++ b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/domain/dto/PtTrainAlgorithmUsageQueryDTO.java @@ -0,0 +1,44 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.algorithm.domain.dto; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.experimental.Accessors; +import org.dubhe.biz.db.base.PageQueryBase; + +import javax.validation.constraints.NotNull; + +/** + * @description 查询算法用途条件 + * @date 2020-06-23 + */ +@EqualsAndHashCode(callSuper = true) +@Data +@Accessors(chain = true) +public class PtTrainAlgorithmUsageQueryDTO extends PageQueryBase { + + @ApiModelProperty(value = "类型", hidden = true) + private String type; + + @ApiModelProperty(value = "是否包含默认值 0:不包含 1包含", required = true) + @NotNull + private Boolean isContainDefault; + +} diff --git a/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/domain/dto/PtTrainAlgorithmUsageUpdateDTO.java b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/domain/dto/PtTrainAlgorithmUsageUpdateDTO.java new file mode 100644 index 0000000..2483ac3 --- /dev/null +++ b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/domain/dto/PtTrainAlgorithmUsageUpdateDTO.java @@ -0,0 +1,49 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.algorithm.domain.dto; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import lombok.experimental.Accessors; +import org.dubhe.algorithm.utils.TrainUtil; +import org.hibernate.validator.constraints.Length; + +import javax.validation.constraints.Min; +import javax.validation.constraints.NotNull; +import java.io.Serializable; + +/** + * @description 算法用途修改 + * @date 2020-06-23 + */ +@Data +@Accessors(chain = true) +public class PtTrainAlgorithmUsageUpdateDTO implements Serializable { + + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "id", required = true) + @NotNull(message = "id不能为null") + @Min(value = TrainUtil.NUMBER_ONE, message = "id必须大于1") + private Long id; + + @ApiModelProperty("描述, 长度不能超过20个字符") + @Length(max = TrainUtil.NUMBER_TWENTY, message = "名称长度不能超过20个字符") + private String auxInfo; + +} diff --git a/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/domain/entity/PtTrainAlgorithm.java b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/domain/entity/PtTrainAlgorithm.java new file mode 100644 index 0000000..cb55ccf --- /dev/null +++ b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/domain/entity/PtTrainAlgorithm.java @@ -0,0 +1,147 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.algorithm.domain.entity; + +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.baomidou.mybatisplus.extension.handlers.FastjsonTypeHandler; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.experimental.Accessors; +import org.dubhe.biz.db.entity.BaseEntity; + +import javax.validation.constraints.NotNull; + +/** + * @description 算法 + * @date 2020-04-29 + */ + +@EqualsAndHashCode(callSuper = true) +@Data +@TableName(value = "pt_train_algorithm", autoResultMap = true) +@Accessors(chain = true) +public class PtTrainAlgorithm extends BaseEntity { + + /** + * 主键 + */ + @TableId(value = "id", type = IdType.AUTO) + @NotNull(groups = {Update.class}) + private Long id; + + /** + * 算法名称 + */ + @TableField(value = "algorithm_name") + private String algorithmName; + + /** + * 算法描述 + */ + @TableField(value = "description") + private String description; + + /** + * 算法来源(1为我的算法,2为预置算法) + */ + @TableField(value = "algorithm_source") + private Integer algorithmSource; + + /** + * 环境镜像名称 + */ + @TableField(value = "image_name") + private String imageName; + + /** + * 代码目录 + */ + @TableField(value = "code_dir") + private String codeDir; + + /** + * 运行命令 + */ + @TableField(value = "run_command") + private String runCommand; + + /** + * 运行参数 + */ + @TableField(value = "run_params", typeHandler = FastjsonTypeHandler.class) + private JSONObject runParams; + + /** + * 算法用途 + */ + @TableField(value = "algorithm_usage") + private String algorithmUsage; + + /** + * 算法精度 + */ + @TableField(value = "accuracy") + private String accuracy; + + /** + * P4推理速度(ms) + */ + @TableField(value = "p4_inference_speed") + private Integer p4InferenceSpeed; + + /** + * 算法是否支持推理(1可推理,0不可推理) + */ + @TableField(value = "inference") + private Boolean inference; + + /** + * 训练结果输出(1是,0否) + */ + @TableField(value = "is_train_model_out") + private Boolean isTrainModelOut; + + /** + * 训练输出(1是,0否) + */ + @TableField(value = "is_train_out") + private Boolean isTrainOut; + + /** + * 可视化日志(1是,0否) + */ + @TableField(value = "is_visualized_log") + private Boolean isVisualizedLog; + + /** + * 算法状态 + */ + @TableField(value = "algorithm_status") + private Integer algorithmStatus; + + /** + * 资源拥有者ID + */ + @TableField(value = "origin_user_id",fill = FieldFill.INSERT) + private Long originUserId; +} diff --git a/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/domain/entity/PtTrainAlgorithmUsage.java b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/domain/entity/PtTrainAlgorithmUsage.java new file mode 100644 index 0000000..8b9449d --- /dev/null +++ b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/domain/entity/PtTrainAlgorithmUsage.java @@ -0,0 +1,68 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.algorithm.domain.entity; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.experimental.Accessors; +import org.dubhe.biz.db.entity.BaseEntity; + +import javax.validation.constraints.NotNull; + +/** + * @description 算法 + * @date 2020-06-23 + */ + +@EqualsAndHashCode(callSuper = true) +@Data +@TableName("pt_auxiliary_info") +@Accessors(chain = true) +public class PtTrainAlgorithmUsage extends BaseEntity { + + /** + * 主键 + */ + @TableId(value = "id", type = IdType.AUTO) + @NotNull(groups = {Update.class}) + private Long id; + + /** + * 用户id + */ + @TableField(value = "origin_user_id",fill = FieldFill.INSERT) + private Long originUserId; + + /** + * 类型 + */ + @TableField(value = "type") + private String type; + + /** + * 算法来源(1为我的算法,2为预置算法) + */ + @TableField(value = "aux_info") + private String auxInfo; + +} diff --git a/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/domain/vo/PtTrainAlgorithmQueryVO.java b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/domain/vo/PtTrainAlgorithmQueryVO.java new file mode 100644 index 0000000..4593b62 --- /dev/null +++ b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/domain/vo/PtTrainAlgorithmQueryVO.java @@ -0,0 +1,101 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.algorithm.domain.vo; + +import com.alibaba.fastjson.JSONObject; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.io.Serializable; +import java.sql.Timestamp; + +/** + * @description 训练算法返回列表 + * @date 2020-04-27 + */ +@Data +public class PtTrainAlgorithmQueryVO implements Serializable { + + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "算法ID") + private Long id; + + @ApiModelProperty(value = "算法名称") + private String algorithmName; + + @ApiModelProperty(value = "描述信息") + private String description; + + @ApiModelProperty(value = "算法来源") + private Integer algorithmSource; + + @ApiModelProperty(value = "镜像名称") + private String imageName; + + @ApiModelProperty(value = "算法文件大小") + private String algorithmFileSize; + + @ApiModelProperty(value = "镜像版本") + private String imageTag; + + @ApiModelProperty(value = "代码目录") + private String codeDir; + + @ApiModelProperty(value = "运行命令") + private String runCommand; + + @ApiModelProperty(value = "运行参数") + private JSONObject runParams; + + @ApiModelProperty(value = "算法用途") + private String algorithmUsage; + + @ApiModelProperty(value = "精度") + private String accuracy; + + @ApiModelProperty(value = "P4推理速度") + private Integer p4InferenceSpeed; + + @ApiModelProperty(value = "输出结果(1是,0否)") + private Boolean isTrainModelOut; + + @ApiModelProperty(value = "输出信息(1是,0否)") + private Boolean isTrainOut; + + @ApiModelProperty(value = "可视化日志(1是,0否)") + private Boolean isVisualizedLog; + + @ApiModelProperty(value = "算法是否支持推理(1可推理,0不可推理)") + private Boolean inference; + + @ApiModelProperty(value = "创建人") + private Long createUserId; + + @ApiModelProperty(value = "创建时间") + private Timestamp createTime; + + @ApiModelProperty(value = "更新人") + private Long updateUserId; + + @ApiModelProperty(value = "更新时间") + private Timestamp updateTime; + + @ApiModelProperty(value = "资源拥有者ID") + private Long originUserId; +} diff --git a/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/domain/vo/PtTrainAlgorithmUsageQueryVO.java b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/domain/vo/PtTrainAlgorithmUsageQueryVO.java new file mode 100644 index 0000000..52c84c6 --- /dev/null +++ b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/domain/vo/PtTrainAlgorithmUsageQueryVO.java @@ -0,0 +1,62 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.algorithm.domain.vo; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.io.Serializable; +import java.sql.Timestamp; + +/** + * @description 算法用途返回列表 + * @date 2020-06-23 + */ +@Data +public class PtTrainAlgorithmUsageQueryVO implements Serializable { + + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "ID") + private Long id; + + @ApiModelProperty(value = "类型") + private String type; + + @ApiModelProperty(value = "辅助信息") + private String auxInfo; + + @ApiModelProperty(value = "创建人") + private Long createUserId; + + @ApiModelProperty(value = "创建时间") + private Timestamp createTime; + + @ApiModelProperty(value = "更新人") + private Long updateUserId; + + @ApiModelProperty(value = "更新时间") + private Timestamp updateTime; + + @ApiModelProperty(value = "资源拥有者ID") + private Long originUserId; + + @ApiModelProperty(value = "是否为默认值") + private Boolean isDefault; + +} diff --git a/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/enums/AlgorithmSourceEnum.java b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/enums/AlgorithmSourceEnum.java new file mode 100644 index 0000000..2df6ac7 --- /dev/null +++ b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/enums/AlgorithmSourceEnum.java @@ -0,0 +1,46 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.algorithm.enums; + +import lombok.Getter; + +/** + * @description 算法枚举类 + * @date 2020-05-12 + */ +@Getter +public enum AlgorithmSourceEnum { + + /** + * MINE 算法来源 我的算法 + */ + MINE(1, "MINE"), + /** + * PRE 算法来源 预置算法 + */ + PRE(2,"PRE"); + + private Integer status; + + private String message; + + AlgorithmSourceEnum(Integer status, String message) { + this.status = status; + this.message = message; + } +} diff --git a/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/enums/AlgorithmStatusEnum.java b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/enums/AlgorithmStatusEnum.java new file mode 100644 index 0000000..dfdd78e --- /dev/null +++ b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/enums/AlgorithmStatusEnum.java @@ -0,0 +1,63 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.algorithm.enums; + +/** + * @description 算法状态枚举 + * @date 2020-08-19 + */ +public enum AlgorithmStatusEnum { + + + /** + * 创建中 + */ + MAKING(0, "创建中"), + /** + * 创建成功 + */ + SUCCESS(1, "创建成功"), + /** + * 创建失败 + */ + FAIL(2, "创建失败"); + + + /** + * 编码 + */ + private Integer code; + + /** + * 描述 + */ + private String description; + + AlgorithmStatusEnum(int code, String description) { + this.code = code; + this.description = description; + } + + public Integer getCode() { + return code; + } + + public String getDescription() { + return description; + } +} + diff --git a/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/rest/PtTrainAlgorithmController.java b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/rest/PtTrainAlgorithmController.java new file mode 100644 index 0000000..72ed003 --- /dev/null +++ b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/rest/PtTrainAlgorithmController.java @@ -0,0 +1,124 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.algorithm.rest; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.dubhe.algorithm.domain.dto.PtTrainAlgorithmCreateDTO; +import org.dubhe.algorithm.domain.dto.PtTrainAlgorithmDeleteDTO; +import org.dubhe.algorithm.domain.dto.PtTrainAlgorithmQueryDTO; +import org.dubhe.algorithm.domain.dto.PtTrainAlgorithmUpdateDTO; +import org.dubhe.algorithm.service.PtTrainAlgorithmService; +import org.dubhe.biz.base.annotation.ApiVersion; +import org.dubhe.biz.base.constant.Permissions; +import org.dubhe.biz.base.dto.ModelOptAlgorithmCreateDTO; +import org.dubhe.biz.base.dto.TrainAlgorithmSelectAllBatchIdDTO; +import org.dubhe.biz.base.dto.TrainAlgorithmSelectAllByIdDTO; +import org.dubhe.biz.base.dto.TrainAlgorithmSelectByIdDTO; +import org.dubhe.biz.base.vo.DataResponseBody; +import org.dubhe.biz.base.vo.TrainAlgorithmQureyVO; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +/** + * @description 训练算法 + * @date 2020-04-27 + */ +@Api(tags = "训练:算法管理") +@RestController +@RequestMapping("/algorithms") +public class PtTrainAlgorithmController { + + @Autowired + private PtTrainAlgorithmService ptTrainAlgorithmService; + + @GetMapping + @ApiOperation("查询算法") + @PreAuthorize(Permissions.DEVELOPMENT_ALGORITHM) + public DataResponseBody getAlgorithms(@Validated PtTrainAlgorithmQueryDTO ptTrainAlgorithmQueryDTO) { + return new DataResponseBody(ptTrainAlgorithmService.queryAll(ptTrainAlgorithmQueryDTO)); + } + + @GetMapping("/myAlgorithmCount") + @ApiOperation("查询当前用户的算法个数") + @PreAuthorize(Permissions.DEVELOPMENT_ALGORITHM) + public DataResponseBody getAlgorithmCount() { + return new DataResponseBody(ptTrainAlgorithmService.getAlgorithmCount()); + } + + @PostMapping + @ApiOperation("新增算法") + @PreAuthorize(Permissions.DEVELOPMENT_ALGORITHM_CREATE) + public DataResponseBody create(@Validated @RequestBody PtTrainAlgorithmCreateDTO ptTrainAlgorithmCreateDTO) { + return new DataResponseBody(ptTrainAlgorithmService.create(ptTrainAlgorithmCreateDTO)); + } + + @PutMapping + @ApiOperation("修改算法") + @PreAuthorize(Permissions.DEVELOPMENT_ALGORITHM_EDIT) + public DataResponseBody update(@Validated @RequestBody PtTrainAlgorithmUpdateDTO ptTrainAlgorithmUpdateDTO) { + return new DataResponseBody(ptTrainAlgorithmService.update(ptTrainAlgorithmUpdateDTO)); + } + + @DeleteMapping + @ApiOperation("删除算法") + @PreAuthorize(Permissions.DEVELOPMENT_ALGORITHM_DELETE) + public DataResponseBody deleteAll(@Validated @RequestBody PtTrainAlgorithmDeleteDTO ptTrainAlgorithmDeleteDTO) { + ptTrainAlgorithmService.deleteAll(ptTrainAlgorithmDeleteDTO); + return new DataResponseBody(); + } + + @GetMapping("/selectAllById") + @ApiOperation("根据Id查询所有数据") + @PreAuthorize(Permissions.DEVELOPMENT_ALGORITHM) + public DataResponseBody selectAllById(@Validated TrainAlgorithmSelectAllByIdDTO trainAlgorithmSelectAllByIdDTO) { + return new DataResponseBody(ptTrainAlgorithmService.selectAllById(trainAlgorithmSelectAllByIdDTO)); + } + + @GetMapping("/selectById") + @ApiOperation("根据Id查询") + @PreAuthorize(Permissions.DEVELOPMENT_ALGORITHM) + public DataResponseBody selectById(@Validated TrainAlgorithmSelectByIdDTO trainAlgorithmSelectByIdDTO) { + return new DataResponseBody(ptTrainAlgorithmService.selectById(trainAlgorithmSelectByIdDTO)); + } + + @GetMapping("/selectAllBatchIds") + @ApiOperation("批量查询") + @PreAuthorize(Permissions.DEVELOPMENT_ALGORITHM) + public DataResponseBody> selectAllBatchIds(@Validated TrainAlgorithmSelectAllBatchIdDTO trainAlgorithmSelectAllBatchIdDTO) { + return new DataResponseBody(ptTrainAlgorithmService.selectAllBatchIds(trainAlgorithmSelectAllBatchIdDTO)); + } + + @PostMapping("/uploadAlgorithm") + @ApiOperation("模型优化上传算法") + @PreAuthorize(Permissions.DEVELOPMENT_ALGORITHM_CREATE) + public DataResponseBody modelOptimizationUploadAlgorithm(@Validated @RequestBody ModelOptAlgorithmCreateDTO modelOptAlgorithmCreateDTO) { + return new DataResponseBody(ptTrainAlgorithmService.modelOptimizationUploadAlgorithm(modelOptAlgorithmCreateDTO)); + } + + @GetMapping("/getInferenceAlgorithm") + @ApiOperation("查询可推理算法") + @PreAuthorize(Permissions.DEVELOPMENT_ALGORITHM) + public DataResponseBody getInferenceAlgorithm() { + return new DataResponseBody(ptTrainAlgorithmService.getInferenceAlgorithm()); + } +} diff --git a/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/rest/PtTrainAlgorithmUsageController.java b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/rest/PtTrainAlgorithmUsageController.java new file mode 100644 index 0000000..daede87 --- /dev/null +++ b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/rest/PtTrainAlgorithmUsageController.java @@ -0,0 +1,84 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.algorithm.rest; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.dubhe.algorithm.constant.UserAuxiliaryInfoConstant; +import org.dubhe.algorithm.domain.dto.PtTrainAlgorithmUsageCreateDTO; +import org.dubhe.algorithm.domain.dto.PtTrainAlgorithmUsageDeleteDTO; +import org.dubhe.algorithm.domain.dto.PtTrainAlgorithmUsageQueryDTO; +import org.dubhe.algorithm.domain.dto.PtTrainAlgorithmUsageUpdateDTO; +import org.dubhe.algorithm.service.PtTrainAlgorithmUsageService; +import org.dubhe.biz.base.annotation.ApiVersion; +import org.dubhe.biz.base.constant.Permissions; +import org.dubhe.biz.base.vo.DataResponseBody; +import org.dubhe.biz.dataresponse.factory.DataResponseFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +/** + * @description 算法用途管理 + * @date 2020-06-19 + */ +@Api(tags = "训练:算法用途管理") +@RestController +@RequestMapping("/algorithmUsage") +public class PtTrainAlgorithmUsageController { + + @Autowired + private PtTrainAlgorithmUsageService ptTrainAlgorithmUsageService; + + @GetMapping + @ApiOperation("算法用途列表展示") + @PreAuthorize(Permissions.DEVELOPMENT_ALGORITHM) + public DataResponseBody queryAll(@Validated PtTrainAlgorithmUsageQueryDTO ptTrainAlgorithmUsageQueryDTO) { + ptTrainAlgorithmUsageQueryDTO.setType(UserAuxiliaryInfoConstant.ALGORITHM_USAGE); + return DataResponseFactory + .success(ptTrainAlgorithmUsageService.queryAll(ptTrainAlgorithmUsageQueryDTO)); + } + + @PostMapping + @ApiOperation("新增算法用途") + @PreAuthorize(Permissions.DEVELOPMENT_ALGORITHM_CREATE) + public DataResponseBody create( + @Validated @RequestBody PtTrainAlgorithmUsageCreateDTO ptTrainAlgorithmUsageCreateDTO) { + ptTrainAlgorithmUsageCreateDTO.setType(UserAuxiliaryInfoConstant.ALGORITHM_USAGE); + return DataResponseFactory.success(ptTrainAlgorithmUsageService.create(ptTrainAlgorithmUsageCreateDTO)); + } + + @DeleteMapping + @ApiOperation("删除算法用途") + @PreAuthorize(Permissions.DEVELOPMENT_ALGORITHM_DELETE) + public DataResponseBody deleteAll(@Validated @RequestBody PtTrainAlgorithmUsageDeleteDTO ptTrainAlgorithmUsageDeleteDTO) { + ptTrainAlgorithmUsageService.deleteAll(ptTrainAlgorithmUsageDeleteDTO); + return new DataResponseBody(); + } + + @PutMapping + @ApiOperation("修改算法用途") + @PreAuthorize(Permissions.DEVELOPMENT_ALGORITHM_EDIT) + public DataResponseBody update( + @Validated @RequestBody PtTrainAlgorithmUsageUpdateDTO ptTrainAlgorithmUsageUpdateDTO) { + ptTrainAlgorithmUsageService.update(ptTrainAlgorithmUsageUpdateDTO); + return new DataResponseBody(); + } + +} diff --git a/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/service/PtTrainAlgorithmService.java b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/service/PtTrainAlgorithmService.java new file mode 100644 index 0000000..95bb9c7 --- /dev/null +++ b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/service/PtTrainAlgorithmService.java @@ -0,0 +1,121 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.algorithm.service; + +import org.dubhe.algorithm.domain.dto.PtTrainAlgorithmCreateDTO; +import org.dubhe.algorithm.domain.dto.PtTrainAlgorithmDeleteDTO; +import org.dubhe.algorithm.domain.dto.PtTrainAlgorithmQueryDTO; +import org.dubhe.algorithm.domain.dto.PtTrainAlgorithmUpdateDTO; +import org.dubhe.algorithm.domain.vo.PtTrainAlgorithmQueryVO; +import org.dubhe.biz.base.dto.ModelOptAlgorithmCreateDTO; +import org.dubhe.biz.base.dto.TrainAlgorithmSelectAllBatchIdDTO; +import org.dubhe.biz.base.dto.TrainAlgorithmSelectAllByIdDTO; +import org.dubhe.biz.base.dto.TrainAlgorithmSelectByIdDTO; +import org.dubhe.biz.base.vo.ModelOptAlgorithmQureyVO; +import org.dubhe.biz.base.vo.TrainAlgorithmQureyVO; +import org.dubhe.recycle.domain.dto.RecycleCreateDTO; + +import java.util.List; +import java.util.Map; + +/** + * @description 训练算法 服务类 + * @date 2020-04-27 + */ +public interface PtTrainAlgorithmService { + + /** + * 查询数据分页 + * + * @param ptTrainAlgorithmQueryDTO 分页参数条件 + * @return Map map + */ + Map queryAll(PtTrainAlgorithmQueryDTO ptTrainAlgorithmQueryDTO); + + /** + * 新增算法 + * + * @param ptTrainAlgorithmCreateDTO 新增算法条件 + * @return PtTrainAlgorithmCreateVO 新建训练算法 + */ + List create(PtTrainAlgorithmCreateDTO ptTrainAlgorithmCreateDTO); + + /** + * 修改算法 + * + * @param ptTrainAlgorithmUpdateDTO 修改算法条件 + * @return PtTrainAlgorithmUpdateVO 修改训练算法 + */ + List update(PtTrainAlgorithmUpdateDTO ptTrainAlgorithmUpdateDTO); + + /** + * 删除算法 + * + * @param ptTrainAlgorithmDeleteDTO 删除算法条件 + */ + void deleteAll(PtTrainAlgorithmDeleteDTO ptTrainAlgorithmDeleteDTO); + + /** + * 查询当前用户的算法个数 + */ + Map getAlgorithmCount(); + + /** + * 根据Id查询所有数据(包含已被软删除的数据) + * + * @param trainAlgorithmSelectAllByIdDTO 算法id + * @return PtTrainAlgorithm 根据Id查询所有数据 + */ + TrainAlgorithmQureyVO selectAllById(TrainAlgorithmSelectAllByIdDTO trainAlgorithmSelectAllByIdDTO); + + /** + * 根据Id查询 + * + * @param trainAlgorithmSelectByIdDTO 算法id + * @return PtTrainAlgorithm 根据Id查询 + */ + TrainAlgorithmQureyVO selectById(TrainAlgorithmSelectByIdDTO trainAlgorithmSelectByIdDTO); + + /** + * 批量查询 + * + * @param trainAlgorithmSelectAllBatchIdDTO 算法ids + * @return List 批量查询 + */ + List selectAllBatchIds(TrainAlgorithmSelectAllBatchIdDTO trainAlgorithmSelectAllBatchIdDTO); + + /** + * 模型优化上传算法 + * + * @param modelOptAlgorithmCreateDTO 模型优化上传算法入参 + * @return ModelOptAlgorithmQureyVO 新增算法信息 + */ + ModelOptAlgorithmQureyVO modelOptimizationUploadAlgorithm(ModelOptAlgorithmCreateDTO modelOptAlgorithmCreateDTO); + + /** + * 算法删除文件还原 + * @param dto 还原实体 + */ + void algorithmRecycleFileRollback(RecycleCreateDTO dto); + + /** + * 查询可推理算法 + * @return List 返回可推理算法集合 + */ + List getInferenceAlgorithm(); +} diff --git a/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/service/PtTrainAlgorithmUsageService.java b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/service/PtTrainAlgorithmUsageService.java new file mode 100644 index 0000000..ea48a91 --- /dev/null +++ b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/service/PtTrainAlgorithmUsageService.java @@ -0,0 +1,62 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.algorithm.service; + +import org.dubhe.algorithm.domain.dto.PtTrainAlgorithmUsageCreateDTO; +import org.dubhe.algorithm.domain.dto.PtTrainAlgorithmUsageDeleteDTO; +import org.dubhe.algorithm.domain.dto.PtTrainAlgorithmUsageQueryDTO; +import org.dubhe.algorithm.domain.dto.PtTrainAlgorithmUsageUpdateDTO; + +import java.util.List; +import java.util.Map; + +/** + * @description 算法用途 服务类 + * @date 2020-06-23 + */ +public interface PtTrainAlgorithmUsageService { + + /** + * 查询算法用途 + * + * @param ptTrainAlgorithmUsageQueryDTO 查询算法用途参数 + */ + Map queryAll(PtTrainAlgorithmUsageQueryDTO ptTrainAlgorithmUsageQueryDTO); + + /** + * 新增算法用途 + * + * @param ptTrainAlgorithmUsageCreateDTO 新增算法用途参数 + */ + List create(PtTrainAlgorithmUsageCreateDTO ptTrainAlgorithmUsageCreateDTO); + + /** + * 删除算法用途 + * + * @param ptTrainAlgorithmUsageDeleteDTO 删除算法用途参数 + */ + void deleteAll(PtTrainAlgorithmUsageDeleteDTO ptTrainAlgorithmUsageDeleteDTO); + + /** + * 更新算法用途 + * + * @param ptTrainAlgorithmUsageUpdateDTO 更新算法用途参数 + */ + void update(PtTrainAlgorithmUsageUpdateDTO ptTrainAlgorithmUsageUpdateDTO); + +} diff --git a/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/service/RecycleFileService/AlgorithmRecycleFileServiceImpl.java b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/service/RecycleFileService/AlgorithmRecycleFileServiceImpl.java new file mode 100644 index 0000000..4d14809 --- /dev/null +++ b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/service/RecycleFileService/AlgorithmRecycleFileServiceImpl.java @@ -0,0 +1,63 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.algorithm.service.RecycleFileService; + +import org.dubhe.algorithm.service.PtTrainAlgorithmService; +import org.dubhe.recycle.domain.dto.RecycleCreateDTO; +import org.dubhe.recycle.domain.dto.RecycleDetailCreateDTO; +import org.dubhe.recycle.global.AbstractGlobalRecycle; +import org.springframework.cloud.context.config.annotation.RefreshScope; +import org.springframework.stereotype.Component; + +import javax.annotation.Resource; + +/** + * @description 算法文件自定义还原 + * @date 2021-03-22 + */ +@RefreshScope +@Component(value = "algorithmRecycleFile") +public class AlgorithmRecycleFileServiceImpl extends AbstractGlobalRecycle { + + /** + * 算法 service + */ + @Resource + private PtTrainAlgorithmService ptTrainAlgorithmService; + + /** + * 此方法不用,算法文件使用回收默认方法 + * + * @param detail 数据清理详情参数 + * @param dto 资源回收创建对象 + * @return + * @throws Exception + */ + @Override + protected boolean clearDetail(RecycleDetailCreateDTO detail, RecycleCreateDTO dto) throws Exception { + return false; + } + + /** + * 算法文件自定义还原方法 + * @param dto 还原实体 + */ + @Override + protected void rollback(RecycleCreateDTO dto) { + ptTrainAlgorithmService.algorithmRecycleFileRollback(dto); + } +} \ No newline at end of file diff --git a/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/service/impl/PtTrainAlgorithmServiceImpl.java b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/service/impl/PtTrainAlgorithmServiceImpl.java new file mode 100644 index 0000000..89a9af1 --- /dev/null +++ b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/service/impl/PtTrainAlgorithmServiceImpl.java @@ -0,0 +1,640 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.algorithm.service.impl; + +import cn.hutool.core.util.RandomUtil; +import cn.hutool.core.util.StrUtil; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.collections4.map.HashedMap; +import org.dubhe.algorithm.async.TrainAlgorithmUploadAsync; +import org.dubhe.algorithm.client.ImageClient; +import org.dubhe.algorithm.client.NoteBookClient; +import org.dubhe.algorithm.constant.AlgorithmConstant; +import org.dubhe.algorithm.constant.TrainAlgorithmConfig; +import org.dubhe.algorithm.dao.PtTrainAlgorithmMapper; +import org.dubhe.algorithm.domain.dto.PtTrainAlgorithmCreateDTO; +import org.dubhe.algorithm.domain.dto.PtTrainAlgorithmDeleteDTO; +import org.dubhe.algorithm.domain.dto.PtTrainAlgorithmQueryDTO; +import org.dubhe.algorithm.domain.dto.PtTrainAlgorithmUpdateDTO; +import org.dubhe.algorithm.domain.entity.PtTrainAlgorithm; +import org.dubhe.algorithm.domain.vo.PtTrainAlgorithmQueryVO; +import org.dubhe.algorithm.service.PtTrainAlgorithmService; +import org.dubhe.biz.base.constant.MagicNumConstant; +import org.dubhe.biz.base.constant.NumberConstant; +import org.dubhe.biz.base.context.UserContext; +import org.dubhe.biz.base.dto.*; +import org.dubhe.biz.base.enums.AlgorithmSourceEnum; +import org.dubhe.biz.base.enums.DatasetTypeEnum; +import org.dubhe.biz.base.enums.ImageTypeEnum; +import org.dubhe.biz.base.exception.BusinessException; +import org.dubhe.biz.base.service.UserContextService; +import org.dubhe.biz.base.utils.ReflectionUtils; +import org.dubhe.biz.base.utils.StringUtils; +import org.dubhe.biz.base.vo.DataResponseBody; +import org.dubhe.biz.base.vo.ModelOptAlgorithmQureyVO; +import org.dubhe.biz.base.vo.TrainAlgorithmQureyVO; +import org.dubhe.biz.db.utils.PageUtil; +import org.dubhe.biz.file.api.FileStoreApi; +import org.dubhe.biz.file.enums.BizPathEnum; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.dubhe.biz.permission.annotation.DataPermissionMethod; +import org.dubhe.biz.permission.base.BaseService; +import org.dubhe.k8s.utils.K8sNameTool; +import org.dubhe.recycle.config.RecycleConfig; +import org.dubhe.recycle.domain.dto.RecycleCreateDTO; +import org.dubhe.recycle.domain.dto.RecycleDetailCreateDTO; +import org.dubhe.recycle.enums.RecycleModuleEnum; +import org.dubhe.recycle.enums.RecycleResourceEnum; +import org.dubhe.recycle.enums.RecycleTypeEnum; +import org.dubhe.recycle.service.RecycleService; +import org.dubhe.recycle.utils.RecycleTool; +import org.springframework.beans.BeanUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import javax.annotation.Resource; +import java.util.*; +import java.util.stream.Collectors; + + +/** + * @description 训练算法 服务实现类 + * @date 2020-04-27 + */ +@Service +public class PtTrainAlgorithmServiceImpl implements PtTrainAlgorithmService { + + @Autowired + private PtTrainAlgorithmMapper ptTrainAlgorithmMapper; + + @Autowired + private ImageClient imageClient; + + @Autowired + private K8sNameTool k8sNameTool; + + @Autowired + private TrainAlgorithmConfig trainAlgorithmConstant; + + @Autowired + private NoteBookClient noteBookClient; + + @Autowired + private TrainAlgorithmUploadAsync algorithmUpdateAsync; + + @Autowired + private RecycleService recycleService; + + @Autowired + private RecycleConfig recycleConfig; + + @Autowired + private UserContextService userContext; + + @Resource(name = "hostFileStoreApiImpl") + private FileStoreApi fileStoreApi; + + public final static List FIELD_NAMES; + + static { + FIELD_NAMES = ReflectionUtils.getFieldNames(PtTrainAlgorithmQueryVO.class); + } + + /** + * 查询数据分页 + * + * @param ptTrainAlgorithmQueryDTO 条件 + * @return Map 返回查询数据 + */ + @Override + @DataPermissionMethod(dataType = DatasetTypeEnum.PUBLIC) + public Map queryAll(PtTrainAlgorithmQueryDTO ptTrainAlgorithmQueryDTO) { + //获取用户信息 + UserContext user = userContext.getCurUser(); + //当算法来源为空时,设置默认算法来源 + if (ptTrainAlgorithmQueryDTO.getAlgorithmSource() == null) { + ptTrainAlgorithmQueryDTO.setAlgorithmSource(trainAlgorithmConstant.getAlgorithmSource()); + } + QueryWrapper wrapper = new QueryWrapper<>(); + wrapper.eq("algorithm_source", ptTrainAlgorithmQueryDTO.getAlgorithmSource()); + //判断算法来源 + if (AlgorithmSourceEnum.MINE.getStatus().equals(ptTrainAlgorithmQueryDTO.getAlgorithmSource())) { + if (!BaseService.isAdmin(user)) { + wrapper.eq("create_user_id", userContext.getCurUserId()); + } + } + //根据算法用途筛选 + if (ptTrainAlgorithmQueryDTO.getAlgorithmUsage() != null) { + wrapper.like("algorithm_usage", ptTrainAlgorithmQueryDTO.getAlgorithmUsage()); + } + //根据算法是否可推理筛选 + if (ptTrainAlgorithmQueryDTO.getInference() != null) { + wrapper.eq("inference", ptTrainAlgorithmQueryDTO.getInference()); + } + if (!StringUtils.isEmpty(ptTrainAlgorithmQueryDTO.getAlgorithmName())) { + wrapper.and(qw -> qw.eq("id", ptTrainAlgorithmQueryDTO.getAlgorithmName()).or().like("algorithm_name", + ptTrainAlgorithmQueryDTO.getAlgorithmName())); + } + + Page page = ptTrainAlgorithmQueryDTO.toPage(); + IPage ptTrainAlgorithms; + try { + if (ptTrainAlgorithmQueryDTO.getSort() != null && FIELD_NAMES.contains(ptTrainAlgorithmQueryDTO.getSort())) { + if (AlgorithmConstant.SORT_ASC.equalsIgnoreCase(ptTrainAlgorithmQueryDTO.getOrder())) { + wrapper.orderByAsc(StringUtils.humpToLine(ptTrainAlgorithmQueryDTO.getSort())); + } else { + wrapper.orderByDesc(StringUtils.humpToLine(ptTrainAlgorithmQueryDTO.getSort())); + } + } else { + wrapper.orderByDesc(AlgorithmConstant.ID); + } + ptTrainAlgorithms = ptTrainAlgorithmMapper.selectPage(page, wrapper); + } catch (Exception e) { + LogUtil.error(LogEnum.BIZ_ALGORITHM, "Query training algorithm list display exceptions :{}, request information :{}", e, + ptTrainAlgorithmQueryDTO); + throw new BusinessException("查询训练算法列表展示异常"); + } + List ptTrainAlgorithmQueryResult = ptTrainAlgorithms.getRecords().stream().map(x -> { + PtTrainAlgorithmQueryVO ptTrainAlgorithmQueryVO = new PtTrainAlgorithmQueryVO(); + BeanUtils.copyProperties(x, ptTrainAlgorithmQueryVO); + //获取镜像名称与版本 + getImageNameAndImageTag(x, ptTrainAlgorithmQueryVO); + return ptTrainAlgorithmQueryVO; + }).collect(Collectors.toList()); + return PageUtil.toPage(page, ptTrainAlgorithmQueryResult); + } + + /** + * 新增算法 + * + * @param ptTrainAlgorithmCreateDTO 新增算法条件 + * @return idList 返回新增算法 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public List create(PtTrainAlgorithmCreateDTO ptTrainAlgorithmCreateDTO) { + //获取用户信息 + UserContext user = userContext.getCurUser(); + //获取镜像url + BaseImageDTO baseImageDTO = new BaseImageDTO(); + BeanUtils.copyProperties(ptTrainAlgorithmCreateDTO, baseImageDTO); + if (StringUtils.isNotBlank(ptTrainAlgorithmCreateDTO.getImageName()) && StringUtils.isNotBlank(ptTrainAlgorithmCreateDTO.getImageTag())) { + ptTrainAlgorithmCreateDTO.setImageName(getImageUrl(baseImageDTO, user)); + } + //创建算法校验DTO并设置默认值 + setAlgorithmDtoDefault(ptTrainAlgorithmCreateDTO); + //算法路径 + String path = fileStoreApi.getBucket() + ptTrainAlgorithmCreateDTO.getCodeDir(); + if (!fileStoreApi.fileOrDirIsExist(fileStoreApi.getRootDir() + path)) { + LogUtil.error(LogEnum.BIZ_ALGORITHM, "The user {} upload path {} does not exist", user.getUsername(), path); + throw new BusinessException("算法文件或路径不存在"); + } + //保存算法 + PtTrainAlgorithm ptTrainAlgorithm = new PtTrainAlgorithm(); + BeanUtils.copyProperties(ptTrainAlgorithmCreateDTO, ptTrainAlgorithm); + //创建我的算法 + if (BaseService.isAdmin(user) && AlgorithmSourceEnum.PRE.getStatus().equals(ptTrainAlgorithmCreateDTO.getAlgorithmSource())) { + ptTrainAlgorithm.setAlgorithmSource(AlgorithmSourceEnum.PRE.getStatus()); + ptTrainAlgorithm.setOriginUserId(0L); + } else { + ptTrainAlgorithm.setAlgorithmSource(AlgorithmSourceEnum.MINE.getStatus()); + } + ptTrainAlgorithm.setCreateUserId(user.getId()); + + //算法名称校验 + QueryWrapper queryWrapper = new QueryWrapper<>(); + queryWrapper.eq("algorithm_name", ptTrainAlgorithmCreateDTO.getAlgorithmName()).and(wrapper -> wrapper.eq("create_user_id", user.getId()).or().eq("origin_user_id", 0L)); + Integer countResult = ptTrainAlgorithmMapper.selectCount(queryWrapper); + //如果是通过【保存至算法】接口创建算法,名称重复可用随机数生成新算法名,待后续客户自主修改 + if (countResult > 0) { + if (ptTrainAlgorithmCreateDTO.getNoteBookId() != null) { + String randomStr = RandomUtil.randomNumbers(MagicNumConstant.FOUR); + ptTrainAlgorithm.setAlgorithmName(ptTrainAlgorithmCreateDTO.getAlgorithmName() + randomStr); + } else { + LogUtil.error(LogEnum.BIZ_ALGORITHM, "The algorithm name ({}) already exists", ptTrainAlgorithmCreateDTO.getAlgorithmName()); + throw new BusinessException("算法名称已存在,请重新输入"); + } + } + //校验path是否带有压缩文件,如有,则解压至算法文件夹下并删除压缩文件 + if (path.toLowerCase().endsWith(AlgorithmConstant.COMPRESS_ZIP)) { + unZip(user, path, ptTrainAlgorithm, ptTrainAlgorithmCreateDTO); + } + + //校验上传算法是否支持推理,如有,则拷贝至算法文件夹下 + if (ptTrainAlgorithmCreateDTO.getInference()) { + //可推理的算法文件拷贝 + copyFile(user, path, ptTrainAlgorithm, ptTrainAlgorithmCreateDTO); + } + + try { + //算法未保存成功,抛出异常,并返回失败信息 + ptTrainAlgorithmMapper.insert(ptTrainAlgorithm); + //设置子线程共享 + ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); + RequestContextHolder.setRequestAttributes(servletRequestAttributes, true); + //上传算法异步处理 + algorithmUpdateAsync.createTrainAlgorithm(userContext.getCurUser(), ptTrainAlgorithm, ptTrainAlgorithmCreateDTO); + } catch (Exception e) { + LogUtil.error(LogEnum.BIZ_ALGORITHM, "The user {} saving algorithm was not successful. Failure reason :{}", user.getUsername(), e.getMessage()); + throw new BusinessException("算法未保存成功"); + } + return Collections.singletonList(ptTrainAlgorithm.getId()); + } + + /** + * 修改算法 + * + * @param ptTrainAlgorithmUpdateDTO 修改算法条件 + * @return PtTrainAlgorithmUpdateVO 返回修改算法 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public List update(PtTrainAlgorithmUpdateDTO ptTrainAlgorithmUpdateDTO) { + //获取用户信息 + UserContext user = userContext.getCurUser(); + //权限校验 + PtTrainAlgorithm ptTrainAlgorithm = ptTrainAlgorithmMapper.selectById(ptTrainAlgorithmUpdateDTO.getId()); + if (null == ptTrainAlgorithm) { + LogUtil.error(LogEnum.BIZ_ALGORITHM, "It is illegal for the user {} to modify the algorithm with id {}", user.getUsername(), ptTrainAlgorithmUpdateDTO.getId()); + throw new BusinessException("您修改的算法不存在或已被删除"); + } + PtTrainAlgorithm updatePtAlgorithm = new PtTrainAlgorithm(); + updatePtAlgorithm.setId(ptTrainAlgorithm.getId()).setUpdateUserId(user.getId()); + //判断是否修改算法名称 + if (StringUtils.isNotBlank(ptTrainAlgorithmUpdateDTO.getAlgorithmName())) { + //算法名称校验 + QueryWrapper queryWrapper = new QueryWrapper<>(); + queryWrapper.eq("algorithm_name", ptTrainAlgorithmUpdateDTO.getAlgorithmName()) + .ne("id", ptTrainAlgorithmUpdateDTO.getId()); + Integer countResult = ptTrainAlgorithmMapper.selectCount(queryWrapper); + if (countResult > 0) { + LogUtil.error(LogEnum.BIZ_ALGORITHM, "The algorithm name ({}) already exists", ptTrainAlgorithmUpdateDTO.getAlgorithmName()); + throw new BusinessException("算法名称已存在,请重新输入"); + } + updatePtAlgorithm.setAlgorithmName(ptTrainAlgorithmUpdateDTO.getAlgorithmName()); + } + //判断是否修改算法描述 + if (ptTrainAlgorithmUpdateDTO.getDescription() != null) { + updatePtAlgorithm.setDescription(ptTrainAlgorithmUpdateDTO.getDescription()); + } + //判断是否修改算法用途 + if (ptTrainAlgorithmUpdateDTO.getAlgorithmUsage() != null) { + updatePtAlgorithm.setAlgorithmUsage(ptTrainAlgorithmUpdateDTO.getAlgorithmUsage()); + } + //判断是否修改训练输出 + if (ptTrainAlgorithmUpdateDTO.getIsTrainOut() != null) { + updatePtAlgorithm.setIsTrainOut(ptTrainAlgorithmUpdateDTO.getIsTrainOut()); + } + //判断是否修改可视化日志 + if (ptTrainAlgorithmUpdateDTO.getIsVisualizedLog() != null) { + updatePtAlgorithm.setIsVisualizedLog(ptTrainAlgorithmUpdateDTO.getIsVisualizedLog()); + } + try { + //算法未修改成功,抛出异常,并返回失败信息 + ptTrainAlgorithmMapper.updateById(updatePtAlgorithm); + } catch (Exception e) { + LogUtil.error(LogEnum.BIZ_ALGORITHM, "User {} failed to modify the algorithm. Pt_train_algorithm table modification operation failed. Failure reason :{}", user.getUsername(), e.getMessage()); + throw new BusinessException("修改失败"); + } + return Collections.singletonList(ptTrainAlgorithm.getId()); + } + + /** + * 可推理的算法文件拷贝 + * + * @param user 用户 + * @param path 文件路径 + * @param ptTrainAlgorithm 算法参数 + */ + private void copyFile(UserContext user, String path, PtTrainAlgorithm ptTrainAlgorithm, PtTrainAlgorithmCreateDTO ptTrainAlgorithmCreateDTO) { + //目标路径 + String targetPath = null; + if (BaseService.isAdmin(user) && AlgorithmSourceEnum.PRE.getStatus().equals(ptTrainAlgorithmCreateDTO.getAlgorithmSource())) { + targetPath = k8sNameTool.getPrePath(BizPathEnum.ALGORITHM, user.getId()); + } else { + targetPath = k8sNameTool.getPath(BizPathEnum.ALGORITHM, user.getId()); + } + boolean copyFile; + if (fileStoreApi.isDirectory(fileStoreApi.getRootDir() + path)) { + copyFile = fileStoreApi.copyPath(fileStoreApi.getRootDir() + path, fileStoreApi.getRootDir() + fileStoreApi.getBucket() + targetPath); + } else { + copyFile = fileStoreApi.copyFile(fileStoreApi.getRootDir() + path, fileStoreApi.getRootDir() + fileStoreApi.getBucket() + targetPath); + } + if (!copyFile) { + LogUtil.error(LogEnum.BIZ_ALGORITHM, "User {} failed to inference copyFile", user.getUsername()); + throw new BusinessException("文件拷贝失败"); + } + //算法路径 + ptTrainAlgorithm.setCodeDir(targetPath); + //算法文件可推理 + ptTrainAlgorithm.setInference(true); + } + + /** + * 解压缩zip压缩包 + * + * @param user 用户 + * @param path 文件路径 + * @param ptTrainAlgorithm 算法参数 + */ + private void unZip(UserContext user, String path, PtTrainAlgorithm ptTrainAlgorithm, PtTrainAlgorithmCreateDTO ptTrainAlgorithmCreateDTO) { + //目标路径 + String targetPath = null; + if (BaseService.isAdmin(user) && AlgorithmSourceEnum.PRE.getStatus().equals(ptTrainAlgorithmCreateDTO.getAlgorithmSource())) { + targetPath = k8sNameTool.getPrePath(BizPathEnum.ALGORITHM, user.getId()); + } else { + targetPath = k8sNameTool.getPath(BizPathEnum.ALGORITHM, user.getId()); + } + boolean unzip = fileStoreApi.unzip(path, fileStoreApi.getBucket() + targetPath); + if (!unzip) { + LogUtil.error(LogEnum.BIZ_ALGORITHM, "User {} failed to unzip", user.getUsername()); + throw new BusinessException("内部错误"); + } + //算法路径 + ptTrainAlgorithm.setCodeDir(targetPath); + } + + /** + * 删除算法 + * + * @param ptTrainAlgorithmDeleteDTO 删除算法条件 + */ + @Override + @Transactional(rollbackFor = Exception.class) + @DataPermissionMethod(dataType = DatasetTypeEnum.PUBLIC) + public void deleteAll(PtTrainAlgorithmDeleteDTO ptTrainAlgorithmDeleteDTO) { + //获取用户信息 + UserContext user = userContext.getCurUser(); + Set idList = ptTrainAlgorithmDeleteDTO.getIds(); + //权限校验 + QueryWrapper query = new QueryWrapper<>(); + //非管理员不可删除预置算法 + if (!BaseService.isAdmin(user)) { + query.eq("algorithm_source", 1); + } + query.in("id", idList); + List algorithmList = ptTrainAlgorithmMapper.selectList(query); + if (algorithmList.size() < idList.size()) { + LogUtil.error(LogEnum.BIZ_ALGORITHM, "User {} delete algorithm failed, no permission to delete the corresponding data in the algorithm table", user.getUsername()); + throw new BusinessException("您删除的ID不存在或已被删除"); + } + int deleteCountResult = ptTrainAlgorithmMapper.deleteBatchIds(idList); + if (deleteCountResult < idList.size()) { + LogUtil.error(LogEnum.BIZ_ALGORITHM, "The user {} deletion algorithm failed, and the algorithm table deletion operation based on the ID array {} failed", user.getUsername(), ptTrainAlgorithmDeleteDTO.getIds()); + throw new BusinessException("删除算法未成功"); + } + //同步更新noteBook表中algorithmId=0 + NoteBookAlgorithmQueryDTO noteBookAlgorithmQueryDTO = new NoteBookAlgorithmQueryDTO(); + List ids = new ArrayList<>(); + idList.stream().forEach(id -> { + ids.add(id); + }); + noteBookAlgorithmQueryDTO.setAlgorithmIdList(ids); + DataResponseBody> dataResponseBody = noteBookClient.getNoteBookIdByAlgorithm(noteBookAlgorithmQueryDTO); + if (dataResponseBody.succeed()) { + List noteBookIdList = dataResponseBody.getData(); + if (!CollectionUtils.isEmpty(noteBookIdList)) { + //根据算法 + NoteBookAlgorithmUpdateDTO noteBookAlgorithmUpdateDTO = new NoteBookAlgorithmUpdateDTO(); + noteBookAlgorithmUpdateDTO.setNotebookIdList(noteBookIdList); + noteBookAlgorithmUpdateDTO.setAlgorithmId(0L); + noteBookClient.updateNoteBookAlgorithm(noteBookAlgorithmUpdateDTO); + } + } + //定时任务删除相应的算法文件 + for (PtTrainAlgorithm algorithm : algorithmList) { + RecycleCreateDTO recycleCreateDTO = new RecycleCreateDTO(); + recycleCreateDTO.setRecycleModule(RecycleModuleEnum.BIZ_ALGORITHM.getValue()) + .setRecycleDelayDate(recycleConfig.getAlgorithmValid()) + .setRecycleNote(RecycleTool.generateRecycleNote("删除算法文件", algorithm.getAlgorithmName(), algorithm.getId())) + .setRemark(algorithm.getId().toString()) + .setRestoreCustom(RecycleResourceEnum.ALGORITHM_RECYCLE_FILE.getClassName()); + RecycleDetailCreateDTO detail = new RecycleDetailCreateDTO(); + detail.setRecycleType(RecycleTypeEnum.FILE.getCode()) + .setRecycleCondition(fileStoreApi.formatPath(fileStoreApi.getRootDir() + fileStoreApi.getBucket() + algorithm.getCodeDir())); + recycleCreateDTO.addRecycleDetailCreateDTO(detail); + recycleService.createRecycleTask(recycleCreateDTO); + } + } + + /** + * 查询算法个数 + * + * @return count 返回个数 + */ + @Override + @DataPermissionMethod(dataType = DatasetTypeEnum.PUBLIC) + public Map getAlgorithmCount() { + QueryWrapper wrapper = new QueryWrapper(); + wrapper.eq("algorithm_source", AlgorithmSourceEnum.MINE.getStatus()); + Integer countResult = ptTrainAlgorithmMapper.selectCount(wrapper); + return new HashedMap() {{ + put("count", countResult); + }}; + } + + /** + * 根据Id查询所有数据(包含已被软删除的数据) + * @param trainAlgorithmSelectAllByIdDTO 算法id + * @return TrainAlgorithmQureyVO返回查询数据(包含已被软删除的数据) + */ + @Override + @DataPermissionMethod(dataType = DatasetTypeEnum.PUBLIC) + public TrainAlgorithmQureyVO selectAllById(TrainAlgorithmSelectAllByIdDTO trainAlgorithmSelectAllByIdDTO) { + PtTrainAlgorithm ptTrainAlgorithm = ptTrainAlgorithmMapper.selectAllById(trainAlgorithmSelectAllByIdDTO.getId()); + TrainAlgorithmQureyVO trainAlgorithmQureyVO = new TrainAlgorithmQureyVO(); + BeanUtils.copyProperties(ptTrainAlgorithm, trainAlgorithmQureyVO); + return trainAlgorithmQureyVO; + } + + /** + * 根据Id查询 + * @param trainAlgorithmSelectByIdDTO 算法id + * @return TrainAlgorithmQureyVO 返回查询数据 + */ + @Override + @DataPermissionMethod(dataType = DatasetTypeEnum.PUBLIC) + public TrainAlgorithmQureyVO selectById(TrainAlgorithmSelectByIdDTO trainAlgorithmSelectByIdDTO) { + PtTrainAlgorithm ptTrainAlgorithm = ptTrainAlgorithmMapper.selectById(trainAlgorithmSelectByIdDTO.getId()); + TrainAlgorithmQureyVO trainAlgorithmQureyVO = new TrainAlgorithmQureyVO(); + BeanUtils.copyProperties(ptTrainAlgorithm, trainAlgorithmQureyVO); + return trainAlgorithmQureyVO; + } + + /** + * 根据Id批量查询 + * @param trainAlgorithmSelectAllBatchIdDTO 算法ids + * @return List 返回查询数据 + */ + @Override + @DataPermissionMethod(dataType = DatasetTypeEnum.PUBLIC) + public List selectAllBatchIds(TrainAlgorithmSelectAllBatchIdDTO trainAlgorithmSelectAllBatchIdDTO) { + List ptTrainAlgorithms = ptTrainAlgorithmMapper.selectAllBatchIds(trainAlgorithmSelectAllBatchIdDTO.getIds()); + List trainAlgorithmQureyVOS = ptTrainAlgorithms.stream().map(x -> { + TrainAlgorithmQureyVO trainAlgorithmQureyVO = new TrainAlgorithmQureyVO(); + BeanUtils.copyProperties(x, trainAlgorithmQureyVO); + return trainAlgorithmQureyVO; + }).collect(Collectors.toList()); + return trainAlgorithmQureyVOS; + } + + /** + * 获取镜像名称与版本 + * + * @param trainAlgorithm 镜像URL + * @param ptTrainAlgorithmQueryVO 镜像名称与版本 + */ + private void getImageNameAndImageTag(PtTrainAlgorithm trainAlgorithm, PtTrainAlgorithmQueryVO ptTrainAlgorithmQueryVO) { + if (StringUtils.isNotBlank(trainAlgorithm.getImageName())) { + String imageNameSuffix = trainAlgorithm.getImageName().substring(trainAlgorithm.getImageName().lastIndexOf(StrUtil.SLASH) + MagicNumConstant.ONE); + String[] imageNameSuffixArray = imageNameSuffix.split(StrUtil.COLON); + ptTrainAlgorithmQueryVO.setImageName(imageNameSuffixArray[0]); + ptTrainAlgorithmQueryVO.setImageTag(imageNameSuffixArray[1]); + } + } + + + /** + * 创建算法DTO校验并设置默认值 + * + * @param dto 校验DTO + **/ + private void setAlgorithmDtoDefault(PtTrainAlgorithmCreateDTO dto) { + + //设置fork默认值(fork:创建算法来源) + if (dto.getFork() == null) { + dto.setFork(trainAlgorithmConstant.getFork()); + } + //设置inference默认值(inference:上传算法是否支持推理) + if (dto.getInference() == null) { + dto.setInference(trainAlgorithmConstant.getInference()); + } + //设置是否输出训练信息 + if (dto.getIsTrainOut() == null) { + dto.setIsTrainOut(trainAlgorithmConstant.getIsTrainOut()); + } + //设置是否输出训练结果 + if (dto.getIsTrainModelOut() == null) { + dto.setIsTrainModelOut(trainAlgorithmConstant.getIsTrainModelOut()); + } + //设置是否输出可视化日志 + if (dto.getIsVisualizedLog() == null) { + dto.setIsVisualizedLog(trainAlgorithmConstant.getIsVisualizedLog()); + } + } + + /** + * 获取镜像url + * + * @param baseImageDto 镜像参数 + * @return BaseImageDTO 镜像url + **/ + private String getImageUrl(BaseImageDTO baseImageDto, UserContext user) { + + PtImageQueryUrlDTO ptImageQueryUrlDTO = new PtImageQueryUrlDTO(); + ptImageQueryUrlDTO.setImageTag(baseImageDto.getImageTag()); + ptImageQueryUrlDTO.setImageName(baseImageDto.getImageName()); + ptImageQueryUrlDTO.setProjectType(ImageTypeEnum.TRAIN.getType()); + DataResponseBody dataResponseBody = imageClient.getImageUrl(ptImageQueryUrlDTO); + if (!dataResponseBody.succeed()) { + LogUtil.error(LogEnum.BIZ_TRAIN, " User {} gets image ,the imageName is {}, the imageTag is {}, and the result of dubhe-image service call failed", user.getUsername(), baseImageDto.getImageName(), baseImageDto.getImageTag()); + throw new BusinessException("镜像服务调用失败"); + } + String ptImage = dataResponseBody.getData(); + // 镜像路径 + if (StringUtils.isBlank(ptImage)) { + LogUtil.error(LogEnum.BIZ_ALGORITHM, "User {} gets image ,the imageName is {}, the imageTag is {}, and the result of query image table (PT_image) is empty", user.getUsername(), baseImageDto.getImageName(), baseImageDto.getImageTag()); + throw new BusinessException("镜像不存在"); + } + return ptImage; + } + + /** + * + * @param modelOptAlgorithmCreateDTO 模型优化上传算法入参 + * @return PtTrainAlgorithm 新增算法信息 + */ + @Override + public ModelOptAlgorithmQureyVO modelOptimizationUploadAlgorithm(ModelOptAlgorithmCreateDTO modelOptAlgorithmCreateDTO) { + PtTrainAlgorithmCreateDTO ptTrainAlgorithmCreateDTO = new PtTrainAlgorithmCreateDTO(); + ptTrainAlgorithmCreateDTO.setAlgorithmName(modelOptAlgorithmCreateDTO.getName()).setCodeDir(modelOptAlgorithmCreateDTO.getPath()).setAlgorithmUsage("模型优化").setIsTrainModelOut(false).setIsTrainOut(false).setIsVisualizedLog(false); + List ids = create(ptTrainAlgorithmCreateDTO); + PtTrainAlgorithm ptTrainAlgorithm = ptTrainAlgorithmMapper.selectById(ids.get(NumberConstant.NUMBER_0)); + ModelOptAlgorithmQureyVO modelOptAlgorithmQureyVO = new ModelOptAlgorithmQureyVO(); + BeanUtils.copyProperties(ptTrainAlgorithm, modelOptAlgorithmQureyVO); + return modelOptAlgorithmQureyVO; + } + + /** + * 算法删除文件还原 + * @param dto 还原实体 + */ + @Override + public void algorithmRecycleFileRollback(RecycleCreateDTO dto) { + //获取用户信息 + UserContext user = userContext.getCurUser(); + if (dto == null) { + LogUtil.error(LogEnum.BIZ_ALGORITHM, "User {} restore algorithm failed to delete the file because RecycleCreateDTO is null", user.getUsername()); + throw new BusinessException("非法入参"); + } + Long algorithmId = Long.valueOf(dto.getRemark()); + PtTrainAlgorithm ptTrainAlgorithm = ptTrainAlgorithmMapper.selectAllById(algorithmId); + QueryWrapper wrapper = new QueryWrapper<>(); + wrapper.eq("algorithm_name", ptTrainAlgorithm.getAlgorithmName()); + if (ptTrainAlgorithmMapper.selectCount(wrapper) > 0) { + throw new BusinessException("算法已存在"); + } + try { + ptTrainAlgorithmMapper.updateStatusById(algorithmId, false); + } catch (Exception e) { + LogUtil.error(LogEnum.BIZ_ALGORITHM, "User {} restore algorithm failed to delete the file because:{}", user.getUsername(), e); + throw new BusinessException("还原失败"); + } + } + + /** + * 查询可推理算法 + * @return List 返回可推理算法集合 + */ + @Override + public List getInferenceAlgorithm() { + QueryWrapper wrapper = new QueryWrapper<>(); + wrapper.eq("inference", true).orderByDesc("id"); + List ptTrainAlgorithms = ptTrainAlgorithmMapper.selectList(wrapper); + if (CollectionUtils.isEmpty(ptTrainAlgorithms)) { + return null; + } + List ptTrainAlgorithmQueryResult = ptTrainAlgorithms.stream().map(x -> { + PtTrainAlgorithmQueryVO ptTrainAlgorithmQueryVO = new PtTrainAlgorithmQueryVO(); + BeanUtils.copyProperties(x, ptTrainAlgorithmQueryVO); + //获取镜像名称与版本 + getImageNameAndImageTag(x, ptTrainAlgorithmQueryVO); + return ptTrainAlgorithmQueryVO; + }).collect(Collectors.toList()); + return ptTrainAlgorithmQueryResult; + } + + +} diff --git a/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/service/impl/PtTrainAlgorithmUsageServiceImpl.java b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/service/impl/PtTrainAlgorithmUsageServiceImpl.java new file mode 100644 index 0000000..24e2e54 --- /dev/null +++ b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/service/impl/PtTrainAlgorithmUsageServiceImpl.java @@ -0,0 +1,186 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.algorithm.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.dubhe.algorithm.dao.PtTrainAlgorithmUsageMapper; +import org.dubhe.algorithm.domain.dto.PtTrainAlgorithmUsageCreateDTO; +import org.dubhe.algorithm.domain.dto.PtTrainAlgorithmUsageDeleteDTO; +import org.dubhe.algorithm.domain.dto.PtTrainAlgorithmUsageQueryDTO; +import org.dubhe.algorithm.domain.dto.PtTrainAlgorithmUsageUpdateDTO; +import org.dubhe.algorithm.domain.entity.PtTrainAlgorithmUsage; +import org.dubhe.algorithm.domain.vo.PtTrainAlgorithmUsageQueryVO; +import org.dubhe.algorithm.service.PtTrainAlgorithmUsageService; +import org.dubhe.biz.base.constant.MagicNumConstant; +import org.dubhe.biz.base.constant.ResponseCode; +import org.dubhe.biz.base.context.DataContext; +import org.dubhe.biz.base.context.UserContext; +import org.dubhe.biz.base.dto.CommonPermissionDataDTO; +import org.dubhe.biz.base.enums.DatasetTypeEnum; +import org.dubhe.biz.base.exception.BusinessException; +import org.dubhe.biz.base.service.UserContextService; +import org.dubhe.biz.db.utils.PageUtil; +import org.dubhe.biz.db.utils.WrapperHelp; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.dubhe.biz.permission.annotation.DataPermissionMethod; +import org.dubhe.biz.permission.aspect.PermissionAspect; +import org.springframework.beans.BeanUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.*; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * @description 用途管理 服务实现类 + * @date 2020-06-23 + */ +@Service +public class PtTrainAlgorithmUsageServiceImpl implements PtTrainAlgorithmUsageService { + + @Autowired + private PtTrainAlgorithmUsageMapper ptTrainAlgorithUsagemMapper; + + @Autowired + private UserContextService userContextService; + + /** + * 算法用途 + * + * @param ptTrainAlgorithmUsageQueryDTO 查询算法用途参数 + * @return Map 返回查询算法用途分页 + */ + @Override + @DataPermissionMethod(dataType = DatasetTypeEnum.PUBLIC) + public Map queryAll(PtTrainAlgorithmUsageQueryDTO ptTrainAlgorithmUsageQueryDTO) { + //获取用户信息 + UserContext user = userContextService.getCurUser(); + QueryWrapper wrapper = WrapperHelp.getWrapper(ptTrainAlgorithmUsageQueryDTO); + + Page page = ptTrainAlgorithmUsageQueryDTO.toPage(); + IPage ptTrainAlgorithms = null; + + if (ptTrainAlgorithmUsageQueryDTO.getIsContainDefault()) { + wrapper.in("origin_user_id", user.getId(), PermissionAspect.PUBLIC_DATA_USER_ID); + } else { + wrapper.eq("origin_user_id", user.getId()); + } + + wrapper.eq("type", ptTrainAlgorithmUsageQueryDTO.getType()); + + DataContext.set(CommonPermissionDataDTO.builder().type(true).build()); + ptTrainAlgorithms = ptTrainAlgorithUsagemMapper.selectPage(page, wrapper); + DataContext.remove(); + + List ptTrainAlgorithmUsageQueryResult = ptTrainAlgorithms.getRecords().stream() + .map(x -> { + PtTrainAlgorithmUsageQueryVO ptTrainAlgorithmUsageQueryVO = new PtTrainAlgorithmUsageQueryVO(); + BeanUtils.copyProperties(x, ptTrainAlgorithmUsageQueryVO); + ptTrainAlgorithmUsageQueryVO.setIsDefault(Objects.equals(x.getOriginUserId(), PermissionAspect.PUBLIC_DATA_USER_ID)); + return ptTrainAlgorithmUsageQueryVO; + }).collect(Collectors.toList()); + return PageUtil.toPage(page, ptTrainAlgorithmUsageQueryResult); + } + + /** + * 新增算法用途 + * + * @param ptTrainAlgorithmUsageCreateDTO 新增算法用途参数 + * @return List 返回新增算法用途 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public List create(PtTrainAlgorithmUsageCreateDTO ptTrainAlgorithmUsageCreateDTO) { + //获取用户信息 + UserContext user = userContextService.getCurUser(); + PtTrainAlgorithmUsage ptTrainAlgorithmUsage = new PtTrainAlgorithmUsage(); + ptTrainAlgorithmUsage.setAuxInfo(ptTrainAlgorithmUsageCreateDTO.getAuxInfo()) + .setType(ptTrainAlgorithmUsageCreateDTO.getType()); + + int insertResult = ptTrainAlgorithUsagemMapper.insert(ptTrainAlgorithmUsage); + + if (insertResult < 1) { + LogUtil.error(LogEnum.BIZ_ALGORITHM, "User {} secondary information was not saved successfully", user.getUsername()); + throw new BusinessException("用户辅助信息未保存成功"); + } + return Collections.singletonList(ptTrainAlgorithmUsage.getId()); + } + + /** + * 删除算法用途 + * + * @param ptTrainAlgorithmUsageDeleteDTO 删除算法用途参数 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public void deleteAll(PtTrainAlgorithmUsageDeleteDTO ptTrainAlgorithmUsageDeleteDTO) { + //获取用户信息 + UserContext user = userContextService.getCurUser(); + Set idList = Stream.of(ptTrainAlgorithmUsageDeleteDTO.getIds()).collect(Collectors.toSet()); + QueryWrapper query = new QueryWrapper<>(); + query.in("id", idList); + Integer queryCountResult = ptTrainAlgorithUsagemMapper.selectCount(query); + + if (queryCountResult < idList.size()) { + LogUtil.error(LogEnum.BIZ_ALGORITHM, "User {} failed to delete user secondary. No permissions to delete corresponding data in user secondary table", user.getUsername()); + throw new BusinessException("您删除的ID不存在或已被删除"); + } + int deleteCountResult = ptTrainAlgorithUsagemMapper.deleteBatchIds(idList); + + if (deleteCountResult < idList.size()) { + LogUtil.error(LogEnum.BIZ_ALGORITHM, "User {} failed to delete user assistance information. User service deletion based on id array {} failed", user.getUsername(), ptTrainAlgorithmUsageDeleteDTO.getIds()); + throw new BusinessException("内部错误"); + } + } + + /** + *更新算法用途 + * + * @param ptTrainAlgorithmUsageUpdateDTO 更新算法用途参数 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public void update(PtTrainAlgorithmUsageUpdateDTO ptTrainAlgorithmUsageUpdateDTO) { + //获取用户信息 + UserContext user = userContextService.getCurUser(); + QueryWrapper query = new QueryWrapper<>(); + query.in("id", ptTrainAlgorithmUsageUpdateDTO.getId()); + Integer queryIntResult = ptTrainAlgorithUsagemMapper.selectCount(query); + + if (queryIntResult < MagicNumConstant.ONE) { + LogUtil.error(LogEnum.BIZ_ALGORITHM, "User {} failed to modify user auxiliary information and has no permission to modify the corresponding data in the algorithm table", user.getUsername()); + throw new BusinessException("您修改的ID不存在或已被删除,请重新输入"); + } + PtTrainAlgorithmUsage ptTrainAlgorithmUsage = new PtTrainAlgorithmUsage(); + ptTrainAlgorithmUsage.setId(ptTrainAlgorithmUsageUpdateDTO.getId()); + ptTrainAlgorithmUsage.setAuxInfo(ptTrainAlgorithmUsageUpdateDTO.getAuxInfo()); + + int updateResult = ptTrainAlgorithUsagemMapper.updateById(ptTrainAlgorithmUsage); + if (updateResult < 1) { + LogUtil.error(LogEnum.BIZ_ALGORITHM, "User {} failed to modify user assistance information", user.getUsername()); + throw new BusinessException("内部错误"); + } + + } + +} diff --git a/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/utils/TrainUtil.java b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/utils/TrainUtil.java new file mode 100644 index 0000000..3e4e55d --- /dev/null +++ b/dubhe-server/dubhe-algorithm/src/main/java/org/dubhe/algorithm/utils/TrainUtil.java @@ -0,0 +1,80 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.algorithm.utils; + +import org.dubhe.biz.base.constant.MagicNumConstant; +import org.dubhe.biz.base.constant.SymbolConstant; + +import java.sql.Timestamp; + +/** + * @description 训练任务工具类 + * @date 2020-07-14 + */ +public class TrainUtil { + + + private TrainUtil() { + + } + + public static final String REGEXP = "^[a-zA-Z0-9\\-\\_\\u4e00-\\u9fa5]+$"; + public static final String REGEXP_NAME = "^[a-zA-Z0-9\\-\\_]+$"; + public static final String REGEXP_TAG = "^[a-zA-Z0-9\\-\\_\\.]+$"; + + public static final String RUNTIME = "%02d:%02d:%02d"; + public static final String FOUR_DECIMAL = "%04d"; + public static final String FOUR_TWO = "%.2f"; + + public static final int NUMBER_ZERO = 0; + public static final int NUMBER_ONE = 1; + public static final int NUMBER_TWO = 2; + public static final int NUMBER_SEVEN = 7; + public static final int NUMBER_EIGHT = 8; + public static final int NUMBER_TWENTY = 20; + public static final int NUMBER_THIRTY_TWO = 32; + public static final int NUMBER_SIXTY_FOUR = 64; + public static final int NUMBER_ONE_HUNDRED_AND_TWENTY_SEVEN = 127; + public static final int NUMBER_ONE_HUNDRED_AND_TWENTY_EIGHT = 128; + public static final int NUMBER_ONE_HUNDRED_AND_SIXTY_EIGHT = 168; + public static final int NUMBER_TWO_HUNDRED_AND_FIFTY_FIVE = 255; + public static final int NUMBER_ONE_THOUSAND = 1000; + public static final int NUMBER_ONE_THOUSAND_AND_TWENTY_FOUR = 1024; + + // 初始化训练时间 + public static final String INIT_RUNTIME = SymbolConstant.BLANK; + + /** + * 获取延时时间 + * @param delayTime 延时时间(单位为小时) + * @return 延时时间 + */ + public static Timestamp getDelayTime(Integer delayTime) { + return new Timestamp(System.currentTimeMillis() + delayTime * MagicNumConstant.SIXTY * MagicNumConstant.SIXTY * MagicNumConstant.ONE_THOUSAND); + } + + /** + * 获取倒计时 + * @param delayTime 延时时间(单位为毫秒) + * @return 倒计时(单位为分钟) + */ + public static Integer getCountDown(Long delayTime) { + return (int) ((delayTime - System.currentTimeMillis()) / (MagicNumConstant.SIXTY * MagicNumConstant.ONE_THOUSAND)); + } + +} diff --git a/dubhe-server/dubhe-algorithm/src/main/resources/banner.txt b/dubhe-server/dubhe-algorithm/src/main/resources/banner.txt new file mode 100644 index 0000000..0d9784a --- /dev/null +++ b/dubhe-server/dubhe-algorithm/src/main/resources/banner.txt @@ -0,0 +1,14 @@ + + + + _____ _ _ _ _ _ _ + | __ \ | | | | /\ | | (_) | | | + | | | |_ _| |__ | |__ ___ / \ | | __ _ ___ _ __ _| |_| |__ _ __ ___ + | | | | | | | '_ \| '_ \ / _ \ / /\ \ | |/ _` |/ _ \| '__| | __| '_ \| '_ ` _ \ + | |__| | |_| | |_) | | | | __/ / ____ \| | (_| | (_) | | | | |_| | | | | | | | | + |_____/ \__,_|_.__/|_| |_|\___| /_/ \_\_|\__, |\___/|_| |_|\__|_| |_|_| |_| |_| + __/ | + |___/ + + + :: Dubhe Algorithm :: 0.0.1-SNAPSHOT diff --git a/dubhe-server/dubhe-algorithm/src/main/resources/bootstrap.yml b/dubhe-server/dubhe-algorithm/src/main/resources/bootstrap.yml new file mode 100644 index 0000000..0824216 --- /dev/null +++ b/dubhe-server/dubhe-algorithm/src/main/resources/bootstrap.yml @@ -0,0 +1,37 @@ +server: + port: 8889 + +spring: + application: + name: dubhe-algorithm + profiles: + active: dev + cloud: + nacos: + config: + enabled: true + namespace: dubhe-server-cloud-prod + server-addr: 127.0.0.1:8848 + shared-configs[0]: + data-id: common-biz.yaml + group: dubhe + refresh: true # 是否动态刷新,默认为false + + shared-configs[1]: + data-id: common-k8s.yaml + group: dubhe + refresh: true + shared-configs[2]: + data-id: common-recycle.yaml + group: dubhe + refresh: true + shared-configs[3]: + data-id: dubhe-algorithm.yaml + group: dubhe + refresh: true + discovery: + enabled: true + namespace: dubhe-server-cloud-prod + group: dubhe + server-addr: 127.0.0.1:8848 + diff --git a/dubhe-server/dubhe-algorithm/src/test/java/org/dubhe/algorithm/PtTrainAlgorithmUsageTest.java b/dubhe-server/dubhe-algorithm/src/test/java/org/dubhe/algorithm/PtTrainAlgorithmUsageTest.java new file mode 100644 index 0000000..196bb6b --- /dev/null +++ b/dubhe-server/dubhe-algorithm/src/test/java/org/dubhe/algorithm/PtTrainAlgorithmUsageTest.java @@ -0,0 +1,96 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.algorithm; + +import com.alibaba.fastjson.JSON; +import org.dubhe.algorithm.domain.dto.PtTrainAlgorithmUsageCreateDTO; +import org.dubhe.algorithm.domain.dto.PtTrainAlgorithmUsageDeleteDTO; +import org.dubhe.algorithm.domain.dto.PtTrainAlgorithmUsageUpdateDTO; +import org.dubhe.biz.base.constant.AuthConst; +import org.dubhe.cloud.unittest.base.BaseTest; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; + +/** + * @description 算法用途单元测试 + * @date 2020-06-23 + */ + +@RunWith(SpringRunner.class) +@SpringBootTest +public class PtTrainAlgorithmUsageTest extends BaseTest { + + /** + * 修改任务参数 算法id=2在算法表中runcommand为空 + */ + @Test + public void queryAllTest() throws Exception { + String accessToken = obtainAccessToken(); + mockMvcWithNoRequestBody(mockMvc.perform(MockMvcRequestBuilders.get("/algorithmUsage").param("isContainDefault", "1").header(AuthConst.AUTHORIZATION, AuthConst.ACCESS_TOKEN_PREFIX + accessToken)) + .andExpect(MockMvcResultMatchers.status().isOk()).andReturn().getResponse(), 200); + } + + @Test + public void queryAllTest2() throws Exception { + String accessToken = obtainAccessToken(); + mockMvcWithNoRequestBody(mockMvc.perform(MockMvcRequestBuilders.get("/algorithmUsage").param("isContainDefault", "0").header(AuthConst.AUTHORIZATION, AuthConst.ACCESS_TOKEN_PREFIX + accessToken)) + .andExpect(MockMvcResultMatchers.status().isOk()).andReturn().getResponse(), 200); + } + + @Test + public void createTest() throws Exception { + + PtTrainAlgorithmUsageCreateDTO ptTrainAlgorithmUsageCreateDTO = new PtTrainAlgorithmUsageCreateDTO(); + ptTrainAlgorithmUsageCreateDTO.setAuxInfo("untilTesting"); + + mockMvcTest(MockMvcRequestBuilders.post("/algorithmUsage"), + JSON.toJSONString(ptTrainAlgorithmUsageCreateDTO), MockMvcResultMatchers.status().is2xxSuccessful(), + 200); + + } + + + @Test + public void deleteTest() throws Exception { + Long[] longs = new Long[1]; + longs[0] = 38L; + PtTrainAlgorithmUsageDeleteDTO ptTrainAlgorithmUsageDeleteDTO = new PtTrainAlgorithmUsageDeleteDTO(); + ptTrainAlgorithmUsageDeleteDTO.setIds(longs); + mockMvcTest(MockMvcRequestBuilders.delete("/algorithmUsage"), JSON.toJSONString(ptTrainAlgorithmUsageDeleteDTO), + MockMvcResultMatchers.status().is2xxSuccessful(), 200); + + } + + @Test + public void updateTest() throws Exception { + PtTrainAlgorithmUsageUpdateDTO ptTrainAlgorithmUsageUpdateDTO = new PtTrainAlgorithmUsageUpdateDTO(); + + ptTrainAlgorithmUsageUpdateDTO.setId(38L); + ptTrainAlgorithmUsageUpdateDTO.setAuxInfo("更新测试"); + + mockMvcTest(MockMvcRequestBuilders.put("/algorithmUsage"), + JSON.toJSONString(ptTrainAlgorithmUsageUpdateDTO), MockMvcResultMatchers.status().is2xxSuccessful(), + 200); + } + + +} diff --git a/dubhe-server/dubhe-algorithm/src/test/java/org/dubhe/algorithm/TrainAlgorithmTest.java b/dubhe-server/dubhe-algorithm/src/test/java/org/dubhe/algorithm/TrainAlgorithmTest.java new file mode 100644 index 0000000..7fac932 --- /dev/null +++ b/dubhe-server/dubhe-algorithm/src/test/java/org/dubhe/algorithm/TrainAlgorithmTest.java @@ -0,0 +1,99 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.algorithm; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import org.dubhe.algorithm.domain.dto.PtTrainAlgorithmCreateDTO; +import org.dubhe.algorithm.domain.dto.PtTrainAlgorithmDeleteDTO; +import org.dubhe.algorithm.domain.dto.PtTrainAlgorithmUpdateDTO; +import org.dubhe.biz.base.constant.AuthConst; +import org.dubhe.cloud.unittest.base.BaseTest; +import org.junit.Test; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; + +import java.util.HashSet; +import java.util.Set; + +/** + * @description 算法管理模块算法管理单元测试 + * @date 2020-06-18 + */ +public class TrainAlgorithmTest extends BaseTest { + + /** + * 查询算法列表 + */ + @Test + public void ptTrainAlgorithmQueryTest() throws Exception { + String accessToken = obtainAccessToken(); + mockMvcWithNoRequestBody(mockMvc.perform(MockMvcRequestBuilders.get("/algorithms").param("algorithmSource", "2").header(AuthConst.AUTHORIZATION, AuthConst.ACCESS_TOKEN_PREFIX + accessToken)) + .andExpect(MockMvcResultMatchers.status().isOk()).andReturn().getResponse(), 200); + } + + /** + * 查询当前用户的算法个数 + */ + @Test + public void getAlgorithmCountTest() throws Exception { + String accessToken = obtainAccessToken(); + mockMvcWithNoRequestBody(mockMvc.perform(MockMvcRequestBuilders.get("/algorithms/myAlgorithmCount").header(AuthConst.AUTHORIZATION, AuthConst.ACCESS_TOKEN_PREFIX + accessToken)) + .andExpect(MockMvcResultMatchers.status().isOk()).andReturn().getResponse(), 200); + } + + + /** + * 新增算法 + */ + @Test + public void ptTrainAlgorithmCreateTest() throws Exception { + PtTrainAlgorithmCreateDTO ptTrainAlgorithmCreateDTO = new PtTrainAlgorithmCreateDTO(); + JSONObject jsonObject = new JSONObject(); + ptTrainAlgorithmCreateDTO.setAlgorithmName("untilTesting") + .setDescription("untilTesting") + .setCodeDir("upload-temp/1/20201202135732212Bp8F/OneFlow算法.zip"); + mockMvcTest(MockMvcRequestBuilders.post("/algorithms"), JSON.toJSONString(ptTrainAlgorithmCreateDTO), MockMvcResultMatchers.status().isOk(), 200); + } + + /** + * 修改算法 + */ + @Test + public void ptTrainAlgorithmUpdateTest() throws Exception { + PtTrainAlgorithmUpdateDTO ptTrainAlgorithmUpdateDTO = new PtTrainAlgorithmUpdateDTO(); + ptTrainAlgorithmUpdateDTO.setId(138L) + .setAlgorithmName("untilTesting" + System.currentTimeMillis()) + .setDescription("untilTesting"); + mockMvcTest(MockMvcRequestBuilders.put("/algorithms"), JSON.toJSONString(ptTrainAlgorithmUpdateDTO), MockMvcResultMatchers.status().isOk(), 200); + } + + + /** + * 删除算法 + */ + @Test + public void ptTrainAlgorithmDeleteTest() throws Exception { + Set ids = new HashSet<>(); + ids.add(138L); + PtTrainAlgorithmDeleteDTO ptTrainAlgorithmDeleteDTO = new PtTrainAlgorithmDeleteDTO(); + ptTrainAlgorithmDeleteDTO.setIds(ids); + mockMvcTest(MockMvcRequestBuilders.delete("/algorithms"), JSON.toJSONString(ptTrainAlgorithmDeleteDTO), MockMvcResultMatchers.status().isOk(), 200); + } + +} diff --git a/dubhe-server/dubhe-data-dcm/lib/LICENSE.txt b/dubhe-server/dubhe-data-dcm/lib/LICENSE.txt new file mode 100644 index 0000000..7714141 --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/lib/LICENSE.txt @@ -0,0 +1,470 @@ + MOZILLA PUBLIC LICENSE + Version 1.1 + + --------------- + +1. Definitions. + + 1.0.1. "Commercial Use" means distribution or otherwise making the + Covered Code available to a third party. + + 1.1. "Contributor" means each entity that creates or contributes to + the creation of Modifications. + + 1.2. "Contributor Version" means the combination of the Original + Code, prior Modifications used by a Contributor, and the Modifications + made by that particular Contributor. + + 1.3. "Covered Code" means the Original Code or Modifications or the + combination of the Original Code and Modifications, in each case + including portions thereof. + + 1.4. "Electronic Distribution Mechanism" means a mechanism generally + accepted in the software development community for the electronic + transfer of data. + + 1.5. "Executable" means Covered Code in any form other than Source + Code. + + 1.6. "Initial Developer" means the individual or entity identified + as the Initial Developer in the Source Code notice required by Exhibit + A. + + 1.7. "Larger Work" means a work which combines Covered Code or + portions thereof with code not governed by the terms of this License. + + 1.8. "License" means this document. + + 1.8.1. "Licensable" means having the right to grant, to the maximum + extent possible, whether at the time of the initial grant or + subsequently acquired, any and all of the rights conveyed herein. + + 1.9. "Modifications" means any addition to or deletion from the + substance or structure of either the Original Code or any previous + Modifications. When Covered Code is released as a series of files, a + Modification is: + A. Any addition to or deletion from the contents of a file + containing Original Code or previous Modifications. + + B. Any new file that contains any part of the Original Code or + previous Modifications. + + 1.10. "Original Code" means Source Code of computer software code + which is described in the Source Code notice required by Exhibit A as + Original Code, and which, at the time of its release under this + License is not already Covered Code governed by this License. + + 1.10.1. "Patent Claims" means any patent claim(s), now owned or + hereafter acquired, including without limitation, method, process, + and apparatus claims, in any patent Licensable by grantor. + + 1.11. "Source Code" means the preferred form of the Covered Code for + making modifications to it, including all modules it contains, plus + any associated interface definition files, scripts used to control + compilation and installation of an Executable, or source code + differential comparisons against either the Original Code or another + well known, available Covered Code of the Contributor's choice. The + Source Code can be in a compressed or archival form, provided the + appropriate decompression or de-archiving software is widely available + for no charge. + + 1.12. "You" (or "Your") means an individual or a legal entity + exercising rights under, and complying with all of the terms of, this + License or a future version of this License issued under Section 6.1. + For legal entities, "You" includes any entity which controls, is + controlled by, or is under common control with You. For purposes of + this definition, "control" means (a) the power, direct or indirect, + to cause the direction or management of such entity, whether by + contract or otherwise, or (b) ownership of more than fifty percent + (50%) of the outstanding shares or beneficial ownership of such + entity. + +2. Source Code License. + + 2.1. The Initial Developer Grant. + The Initial Developer hereby grants You a world-wide, royalty-free, + non-exclusive license, subject to third party intellectual property + claims: + (a) under intellectual property rights (other than patent or + trademark) Licensable by Initial Developer to use, reproduce, + modify, display, perform, sublicense and distribute the Original + Code (or portions thereof) with or without Modifications, and/or + as part of a Larger Work; and + + (b) under Patents Claims infringed by the making, using or + selling of Original Code, to make, have made, use, practice, + sell, and offer for sale, and/or otherwise dispose of the + Original Code (or portions thereof). + + (c) the licenses granted in this Section 2.1(a) and (b) are + effective on the date Initial Developer first distributes + Original Code under the terms of this License. + + (d) Notwithstanding Section 2.1(b) above, no patent license is + granted: 1) for code that You delete from the Original Code; 2) + separate from the Original Code; or 3) for infringements caused + by: i) the modification of the Original Code or ii) the + combination of the Original Code with other software or devices. + + 2.2. Contributor Grant. + Subject to third party intellectual property claims, each Contributor + hereby grants You a world-wide, royalty-free, non-exclusive license + + (a) under intellectual property rights (other than patent or + trademark) Licensable by Contributor, to use, reproduce, modify, + display, perform, sublicense and distribute the Modifications + created by such Contributor (or portions thereof) either on an + unmodified basis, with other Modifications, as Covered Code + and/or as part of a Larger Work; and + + (b) under Patent Claims infringed by the making, using, or + selling of Modifications made by that Contributor either alone + and/or in combination with its Contributor Version (or portions + of such combination), to make, use, sell, offer for sale, have + made, and/or otherwise dispose of: 1) Modifications made by that + Contributor (or portions thereof); and 2) the combination of + Modifications made by that Contributor with its Contributor + Version (or portions of such combination). + + (c) the licenses granted in Sections 2.2(a) and 2.2(b) are + effective on the date Contributor first makes Commercial Use of + the Covered Code. + + (d) Notwithstanding Section 2.2(b) above, no patent license is + granted: 1) for any code that Contributor has deleted from the + Contributor Version; 2) separate from the Contributor Version; + 3) for infringements caused by: i) third party modifications of + Contributor Version or ii) the combination of Modifications made + by that Contributor with other software (except as part of the + Contributor Version) or other devices; or 4) under Patent Claims + infringed by Covered Code in the absence of Modifications made by + that Contributor. + +3. Distribution Obligations. + + 3.1. Application of License. + The Modifications which You create or to which You contribute are + governed by the terms of this License, including without limitation + Section 2.2. The Source Code version of Covered Code may be + distributed only under the terms of this License or a future version + of this License released under Section 6.1, and You must include a + copy of this License with every copy of the Source Code You + distribute. You may not offer or impose any terms on any Source Code + version that alters or restricts the applicable version of this + License or the recipients' rights hereunder. However, You may include + an additional document offering the additional rights described in + Section 3.5. + + 3.2. Availability of Source Code. + Any Modification which You create or to which You contribute must be + made available in Source Code form under the terms of this License + either on the same media as an Executable version or via an accepted + Electronic Distribution Mechanism to anyone to whom you made an + Executable version available; and if made available via Electronic + Distribution Mechanism, must remain available for at least twelve (12) + months after the date it initially became available, or at least six + (6) months after a subsequent version of that particular Modification + has been made available to such recipients. You are responsible for + ensuring that the Source Code version remains available even if the + Electronic Distribution Mechanism is maintained by a third party. + + 3.3. Description of Modifications. + You must cause all Covered Code to which You contribute to contain a + file documenting the changes You made to create that Covered Code and + the date of any change. You must include a prominent statement that + the Modification is derived, directly or indirectly, from Original + Code provided by the Initial Developer and including the name of the + Initial Developer in (a) the Source Code, and (b) in any notice in an + Executable version or related documentation in which You describe the + origin or ownership of the Covered Code. + + 3.4. Intellectual Property Matters + (a) Third Party Claims. + If Contributor has knowledge that a license under a third party's + intellectual property rights is required to exercise the rights + granted by such Contributor under Sections 2.1 or 2.2, + Contributor must include a text file with the Source Code + distribution titled "LEGAL" which describes the claim and the + party making the claim in sufficient detail that a recipient will + know whom to contact. If Contributor obtains such knowledge after + the Modification is made available as described in Section 3.2, + Contributor shall promptly modify the LEGAL file in all copies + Contributor makes available thereafter and shall take other steps + (such as notifying appropriate mailing lists or newsgroups) + reasonably calculated to inform those who received the Covered + Code that new knowledge has been obtained. + + (b) Contributor APIs. + If Contributor's Modifications include an application programming + interface and Contributor has knowledge of patent licenses which + are reasonably necessary to implement that API, Contributor must + also include this information in the LEGAL file. + + (c) Representations. + Contributor represents that, except as disclosed pursuant to + Section 3.4(a) above, Contributor believes that Contributor's + Modifications are Contributor's original creation(s) and/or + Contributor has sufficient rights to grant the rights conveyed by + this License. + + 3.5. Required Notices. + You must duplicate the notice in Exhibit A in each file of the Source + Code. If it is not possible to put such notice in a particular Source + Code file due to its structure, then You must include such notice in a + location (such as a relevant directory) where a user would be likely + to look for such a notice. If You created one or more Modification(s) + You may add your name as a Contributor to the notice described in + Exhibit A. You must also duplicate this License in any documentation + for the Source Code where You describe recipients' rights or ownership + rights relating to Covered Code. You may choose to offer, and to + charge a fee for, warranty, support, indemnity or liability + obligations to one or more recipients of Covered Code. However, You + may do so only on Your own behalf, and not on behalf of the Initial + Developer or any Contributor. You must make it absolutely clear than + any such warranty, support, indemnity or liability obligation is + offered by You alone, and You hereby agree to indemnify the Initial + Developer and every Contributor for any liability incurred by the + Initial Developer or such Contributor as a result of warranty, + support, indemnity or liability terms You offer. + + 3.6. Distribution of Executable Versions. + You may distribute Covered Code in Executable form only if the + requirements of Section 3.1-3.5 have been met for that Covered Code, + and if You include a notice stating that the Source Code version of + the Covered Code is available under the terms of this License, + including a description of how and where You have fulfilled the + obligations of Section 3.2. The notice must be conspicuously included + in any notice in an Executable version, related documentation or + collateral in which You describe recipients' rights relating to the + Covered Code. You may distribute the Executable version of Covered + Code or ownership rights under a license of Your choice, which may + contain terms different from this License, provided that You are in + compliance with the terms of this License and that the license for the + Executable version does not attempt to limit or alter the recipient's + rights in the Source Code version from the rights set forth in this + License. If You distribute the Executable version under a different + license You must make it absolutely clear that any terms which differ + from this License are offered by You alone, not by the Initial + Developer or any Contributor. You hereby agree to indemnify the + Initial Developer and every Contributor for any liability incurred by + the Initial Developer or such Contributor as a result of any such + terms You offer. + + 3.7. Larger Works. + You may create a Larger Work by combining Covered Code with other code + not governed by the terms of this License and distribute the Larger + Work as a single product. In such a case, You must make sure the + requirements of this License are fulfilled for the Covered Code. + +4. Inability to Comply Due to Statute or Regulation. + + If it is impossible for You to comply with any of the terms of this + License with respect to some or all of the Covered Code due to + statute, judicial order, or regulation then You must: (a) comply with + the terms of this License to the maximum extent possible; and (b) + describe the limitations and the code they affect. Such description + must be included in the LEGAL file described in Section 3.4 and must + be included with all distributions of the Source Code. Except to the + extent prohibited by statute or regulation, such description must be + sufficiently detailed for a recipient of ordinary skill to be able to + understand it. + +5. Application of this License. + + This License applies to code to which the Initial Developer has + attached the notice in Exhibit A and to related Covered Code. + +6. Versions of the License. + + 6.1. New Versions. + Netscape Communications Corporation ("Netscape") may publish revised + and/or new versions of the License from time to time. Each version + will be given a distinguishing version number. + + 6.2. Effect of New Versions. + Once Covered Code has been published under a particular version of the + License, You may always continue to use it under the terms of that + version. You may also choose to use such Covered Code under the terms + of any subsequent version of the License published by Netscape. No one + other than Netscape has the right to modify the terms applicable to + Covered Code created under this License. + + 6.3. Derivative Works. + If You create or use a modified version of this License (which you may + only do in order to apply it to code which is not already Covered Code + governed by this License), You must (a) rename Your license so that + the phrases "Mozilla", "MOZILLAPL", "MOZPL", "Netscape", + "MPL", "NPL" or any confusingly similar phrase do not appear in your + license (except to note that your license differs from this License) + and (b) otherwise make it clear that Your version of the license + contains terms which differ from the Mozilla Public License and + Netscape Public License. (Filling in the name of the Initial + Developer, Original Code or Contributor in the notice described in + Exhibit A shall not of themselves be deemed to be modifications of + this License.) + +7. DISCLAIMER OF WARRANTY. + + COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS, + WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, + WITHOUT LIMITATION, WARRANTIES THAT THE COVERED CODE IS FREE OF + DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE OR NON-INFRINGING. + THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED CODE + IS WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT, + YOU (NOT THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE + COST OF ANY NECESSARY SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER + OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO USE OF + ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER. + +8. TERMINATION. + + 8.1. This License and the rights granted hereunder will terminate + automatically if You fail to comply with terms herein and fail to cure + such breach within 30 days of becoming aware of the breach. All + sublicenses to the Covered Code which are properly granted shall + survive any termination of this License. Provisions which, by their + nature, must remain in effect beyond the termination of this License + shall survive. + + 8.2. If You initiate litigation by asserting a patent infringement + claim (excluding declatory judgment actions) against Initial Developer + or a Contributor (the Initial Developer or Contributor against whom + You file such action is referred to as "Participant") alleging that: + + (a) such Participant's Contributor Version directly or indirectly + infringes any patent, then any and all rights granted by such + Participant to You under Sections 2.1 and/or 2.2 of this License + shall, upon 60 days notice from Participant terminate prospectively, + unless if within 60 days after receipt of notice You either: (i) + agree in writing to pay Participant a mutually agreeable reasonable + royalty for Your past and future use of Modifications made by such + Participant, or (ii) withdraw Your litigation claim with respect to + the Contributor Version against such Participant. If within 60 days + of notice, a reasonable royalty and payment arrangement are not + mutually agreed upon in writing by the parties or the litigation claim + is not withdrawn, the rights granted by Participant to You under + Sections 2.1 and/or 2.2 automatically terminate at the expiration of + the 60 day notice period specified above. + + (b) any software, hardware, or device, other than such Participant's + Contributor Version, directly or indirectly infringes any patent, then + any rights granted to You by such Participant under Sections 2.1(b) + and 2.2(b) are revoked effective as of the date You first made, used, + sold, distributed, or had made, Modifications made by that + Participant. + + 8.3. If You assert a patent infringement claim against Participant + alleging that such Participant's Contributor Version directly or + indirectly infringes any patent where such claim is resolved (such as + by license or settlement) prior to the initiation of patent + infringement litigation, then the reasonable value of the licenses + granted by such Participant under Sections 2.1 or 2.2 shall be taken + into account in determining the amount or value of any payment or + license. + + 8.4. In the event of termination under Sections 8.1 or 8.2 above, + all end user license agreements (excluding distributors and resellers) + which have been validly granted by You or any distributor hereunder + prior to termination shall survive termination. + +9. LIMITATION OF LIABILITY. + + UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER TORT + (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL YOU, THE INITIAL + DEVELOPER, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF COVERED CODE, + OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO ANY PERSON FOR + ANY INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY + CHARACTER INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF GOODWILL, + WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER + COMMERCIAL DAMAGES OR LOSSES, EVEN IF SUCH PARTY SHALL HAVE BEEN + INFORMED OF THE POSSIBILITY OF SUCH DAMAGES. THIS LIMITATION OF + LIABILITY SHALL NOT APPLY TO LIABILITY FOR DEATH OR PERSONAL INJURY + RESULTING FROM SUCH PARTY'S NEGLIGENCE TO THE EXTENT APPLICABLE LAW + PROHIBITS SUCH LIMITATION. SOME JURISDICTIONS DO NOT ALLOW THE + EXCLUSION OR LIMITATION OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO + THIS EXCLUSION AND LIMITATION MAY NOT APPLY TO YOU. + +10. U.S. GOVERNMENT END USERS. + + The Covered Code is a "commercial item," as that term is defined in + 48 C.F.R. 2.101 (Oct. 1995), consisting of "commercial computer + software" and "commercial computer software documentation," as such + terms are used in 48 C.F.R. 12.212 (Sept. 1995). Consistent with 48 + C.F.R. 12.212 and 48 C.F.R. 227.7202-1 through 227.7202-4 (June 1995), + all U.S. Government End Users acquire Covered Code with only those + rights set forth herein. + +11. MISCELLANEOUS. + + This License represents the complete agreement concerning subject + matter hereof. If any provision of this License is held to be + unenforceable, such provision shall be reformed only to the extent + necessary to make it enforceable. This License shall be governed by + California law provisions (except to the extent applicable law, if + any, provides otherwise), excluding its conflict-of-law provisions. + With respect to disputes in which at least one party is a citizen of, + or an entity chartered or registered to do business in the United + States of America, any litigation relating to this License shall be + subject to the jurisdiction of the Federal Courts of the Northern + District of California, with venue lying in Santa Clara County, + California, with the losing party responsible for costs, including + without limitation, court costs and reasonable attorneys' fees and + expenses. The application of the United Nations Convention on + Contracts for the International Sale of Goods is expressly excluded. + Any law or regulation which provides that the language of a contract + shall be construed against the drafter shall not apply to this + License. + +12. RESPONSIBILITY FOR CLAIMS. + + As between Initial Developer and the Contributors, each party is + responsible for claims and damages arising, directly or indirectly, + out of its utilization of rights under this License and You agree to + work with Initial Developer and Contributors to distribute such + responsibility on an equitable basis. Nothing herein is intended or + shall be deemed to constitute any admission of liability. + +13. MULTIPLE-LICENSED CODE. + + Initial Developer may designate portions of the Covered Code as + "Multiple-Licensed". "Multiple-Licensed" means that the Initial + Developer permits you to utilize portions of the Covered Code under + Your choice of the NPL or the alternative licenses, if any, specified + by the Initial Developer in the file described in Exhibit A. + +EXHIBIT A -Mozilla Public License. + + ``The contents of this file are subject to the Mozilla Public License + Version 1.1 (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.mozilla.org/MPL/ + + Software distributed under the License is distributed on an "AS IS" + basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the + License for the specific language governing rights and limitations + under the License. + + The Original Code is ______________________________________. + + The Initial Developer of the Original Code is ________________________. + Portions created by ______________________ are Copyright (C) ______ + _______________________. All Rights Reserved. + + Contributor(s): ______________________________________. + + Alternatively, the contents of this file may be used under the terms + of the _____ license (the "[___] License"), in which case the + provisions of [______] License are applicable instead of those + above. If you wish to allow use of your version of this file only + under the terms of the [____] License and not to allow others to use + your version of this file under the MPL, indicate your decision by + deleting the provisions above and replace them with the notice and + other provisions required by the [___] License. If you do not delete + the provisions above, a recipient may use your version of this file + under either the MPL or the [___] License." + + [NOTE: The text of this Exhibit A may differ slightly from the text of + the notices in the Source Code files of the Original Code. You should + use the text of this Exhibit A rather than the text found in the + Original Code Source Code for Your Modifications.] + diff --git a/dubhe-server/dubhe-data-dcm/lib/dcm4che-core-5.19.1.jar b/dubhe-server/dubhe-data-dcm/lib/dcm4che-core-5.19.1.jar new file mode 100644 index 0000000..db86d92 Binary files /dev/null and b/dubhe-server/dubhe-data-dcm/lib/dcm4che-core-5.19.1.jar differ diff --git a/dubhe-server/dubhe-data-dcm/pom.xml b/dubhe-server/dubhe-data-dcm/pom.xml new file mode 100644 index 0000000..8d5e84b --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/pom.xml @@ -0,0 +1,112 @@ + + + + server + org.dubhe + 0.0.1-SNAPSHOT + + 4.0.0 + + dubhe-data-dcm + 医学影像 + + 1.8 + 5.19.1 + + + + + + org.dubhe.biz + base + ${org.dubhe.biz.base.version} + + + org.dubhe.biz + file + ${org.dubhe.biz.file.version} + + + org.dubhe.biz + data-permission + ${org.dubhe.biz.data-permission.version} + + + org.dubhe.biz + redis + ${org.dubhe.biz.redis.version} + + + + org.dubhe.cloud + registration + ${org.dubhe.cloud.registration.version} + + + + org.dubhe.cloud + configuration + ${org.dubhe.cloud.configuration.version} + + + + org.dubhe.cloud + swagger + ${org.dubhe.cloud.swagger.version} + + + + org.dubhe.biz + log + ${org.dubhe.biz.log.version} + + + org.springframework.boot + spring-boot-starter-web + + + org.dubhe + dubhe-data + ${org.dubhe.dubhe-data.version} + + + org.dcm4che + dcm4che-core + ${dcm4che.version} + system + ${project.basedir}/lib/dcm4che-core-5.19.1.jar + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + false + true + exec + true + + + + + org.apache.maven.plugins + maven-surefire-plugin + + true + + + + + + true + src/main/resources + + + + + \ No newline at end of file diff --git a/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/DubheDcmApplication.java b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/DubheDcmApplication.java new file mode 100644 index 0000000..025f20f --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/DubheDcmApplication.java @@ -0,0 +1,37 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.dcm; + +import org.mybatis.spring.annotation.MapperScan; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +/** + * @description 医学模块服务启动类 + * @date 2020-12-16 + */ +@SpringBootApplication(scanBasePackages = "org.dubhe") +@MapperScan(basePackages = {"org.dubhe.dcm.**.dao"}) +public class DubheDcmApplication { + + public static void main(String[] args) { + System.setProperty("es.set.netty.runtime.available.processors", "false"); + SpringApplication.run(DubheDcmApplication.class, args); + } + +} diff --git a/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/constant/DcmConstant.java b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/constant/DcmConstant.java new file mode 100644 index 0000000..b11e872 --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/constant/DcmConstant.java @@ -0,0 +1,83 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.dcm.constant; + +/** + * @description 常量 + * @date 2020-04-10 + */ +public class DcmConstant { + + public static final String MODULE_URL_PREFIX = "/"; + + /** + * medicineId + */ + public static final String MEDICINE_ID = "medicineId"; + + /** + * count + */ + public static final String COUNT ="count"; + + /** + * status + */ + public static final String STATUS ="status"; + + /** + * dcm文件路径 + */ + public static final String DCM_ANNOTATION_PATH = "dataset/dcm/"; + + /** + * dcm自动标注文件名 + */ + public static final String DCM_ANNOTATION = "/annotation/finished_annotation.json"; + + /** + * dcm自动合并标注文件名 + */ + public static final String DCM_MERGE_ANNOTATION = "/annotation/merge_annotation.json"; + + /** + * 文件分隔符 + */ + public static final String DCM_FILE_SEPARATOR = "/"; + + /** + * seriesInstanceUID + */ + public static final String SERIES_INSTABCE_UID = "seriesInstanceUID"; + + /** + * StudyInstanceUID + */ + public static final String STUDY_INSTANCE_UID = "StudyInstanceUID"; + + /** + * annotation + */ + public static final String ANNOTATION = "annotation"; + + /** + * dcm文件上传 + */ + public static final String DCM_UPLOAD = "ssh %s@%s \"docker run --rm -v %s:/nfs dcm4che/dcm4che-tools:5.10.5 storescu -c DCM4CHEE@%s:%s %s\""; + +} diff --git a/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/dao/DataLesionSliceMapper.java b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/dao/DataLesionSliceMapper.java new file mode 100644 index 0000000..ee1daf6 --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/dao/DataLesionSliceMapper.java @@ -0,0 +1,48 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.dcm.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.apache.ibatis.annotations.Delete; +import org.apache.ibatis.annotations.Param; +import org.dubhe.biz.base.annotation.DataPermission; +import org.dubhe.dcm.domain.entity.DataLesionSlice; + +/** + * @description 病灶信息 Mapper 接口 + * @date 2020-12-22 + */ +@DataPermission(ignoresMethod = {"insert"}) +public interface DataLesionSliceMapper extends BaseMapper { + + /** + * 根据数据集ID和病灶序号删除 + * + * @param id 病灶id + */ + @Delete("DELETE FROM data_lesion_slice WHERE id = #{id}") + void deleteByMedicineIdAndOrder(@Param("id") Long id); + + /** + * 根据数据集ID删除 + * + * @param medicineId 数据集ID + */ + @Delete("DELETE FROM data_lesion_slice WHERE medicine_id= #{medicineId}") + void deleteByMedicineId(@Param("medicineId") Long medicineId); + +} diff --git a/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/dao/DataMedicineFileMapper.java b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/dao/DataMedicineFileMapper.java new file mode 100644 index 0000000..9668b6e --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/dao/DataMedicineFileMapper.java @@ -0,0 +1,123 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.dcm.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.apache.ibatis.annotations.Delete; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; +import org.apache.ibatis.annotations.Update; +import org.dubhe.biz.base.annotation.DataPermission; +import org.dubhe.dcm.domain.entity.DataMedicineFile; + +import java.util.List; +import java.util.Map; + +/** + * @description 医学数据集文件管理 Mapper 接口 + * @date 2020-11-12 + */ +@DataPermission(ignoresMethod = {"insert","saveBatch"}) +public interface DataMedicineFileMapper extends BaseMapper { + + /** + * 根据医学数据集ID获取文件url列表 + * + * @param medicineId 数据集ID + * @return List 文件url列表 + */ + @Select("select url from data_medicine_file where medicine_id = #{medicineId} and deleted = 0") + List listMedicineFilesUrls(@Param("medicineId")Long medicineId); + + + + + + + /** + * 查询文件状态取并集 + * + * @param medicalIds 数据集ID + * @return 文件状态列表 + */ + List> getFileStatusCount(@Param("medicalIds")List medicalIds); + + /** + * 批量更新 文件状态 + * + * @param fileIds 文件ID集合 + * @param status 文件状态 + * @return int 更新数量 + */ + @Update("") + int updateStatusByIds(@Param("fileIds") List fileIds, @Param("status") Integer status); + + /** + * 查询文件集合 + * + * @param fileIds 文件ID集合 + * @return List 文件集合 + */ + @Select("") + List selectByIds(@Param("fileIds")List fileIds); + + + /** + * 批量插入医学数据集文件中间表 + * + * @param dataMedicineFiles 医学数据集文件中间表数据 + */ + void saveBatch(@Param("dataMedicineFiles") List dataMedicineFiles); + + /** + * 更新修改人ID + * + * @param medicineId 医学数据集id + * @param userId 当前操作人id + */ + @Update("update data_medicine_file set update_user_id = #{userId} where medicine_id = #{medicineId}") + void updateUserIdByMedicineId(@Param("medicineId") Long medicineId, @Param("userId") Long userId); + + + /** + * 更新数据集删除状态 + * + * @param id 数据集ID + * @param deleteFlag 数据集状态 + */ + @Update("update data_medicine_file set deleted = #{deleteFlag} where id = #{id}") + void updateStatusById(@Param("id") Long id, @Param("deleteFlag") Boolean deleteFlag); + + + /** + * 根据医学数据集id删除医学数据集文件数据 + * + * @param id 医学数据集ID + */ + @Delete("DELETE FROM data_medicine_file WHERE medicine_id= #{id} ") + void deleteByDatasetId(@Param("id") Long id); +} diff --git a/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/dao/DataMedicineMapper.java b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/dao/DataMedicineMapper.java new file mode 100644 index 0000000..bc15f85 --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/dao/DataMedicineMapper.java @@ -0,0 +1,89 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.dcm.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.apache.ibatis.annotations.Delete; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; +import org.apache.ibatis.annotations.Update; +import org.dubhe.biz.base.annotation.DataPermission; +import org.dubhe.dcm.domain.entity.DataMedicine; + +/** + * @description 医学数据集管理 Mapper 接口 + * @date 2020-11-11 + */ +@DataPermission(ignoresMethod = {"insert"}) +public interface DataMedicineMapper extends BaseMapper { + + /** + * 根据序列实例UID查询医学数据集 + * + * @param seriesUid 序列实例UID + * @param originUserId 资源拥有人 + * @return DataMedicine 医学数据集 + */ + @Select("select * from data_medicine where series_instance_uid = #{seriesUid} and origin_user_id = #{originUserId} and deleted = 0") + DataMedicine findBySeriesUidAndNotId(@Param("seriesUid") String seriesUid, @Param("originUserId") Long originUserId); + + + /** + * 更新数据集状态 + * + * @param id 数据集ID + * @param status 数据集状态 + */ + @Update("update data_medicine set status = #{status} where id = #{id}") + void updateStatus(@Param("id") Long id, @Param("status") Integer status); + + + /** + * 更新数据集删除状态 + * + * @param id 数据集ID + * @param deleteFlag 数据集状态 + */ + @Update("update data_medicine set deleted = #{deleteFlag} where id = #{id}") + void updateStatusById(@Param("id") Long id, @Param("deleteFlag") Boolean deleteFlag); + + /** + * 根据id删除数据集 + * + * @param id 医学数据集id + */ + @Delete("DELETE FROM data_medicine WHERE id= #{id} ") + void deleteByDatasetId(@Param("id")Long id); + + /** + * 根据序列实例UID查询医学数据集 + * + * @param seriesInstanceUid 序列实例UID + * @return DataMedicine 医学数据集 + */ + @Select("select * from data_medicine where series_instance_uid = #{seriesUid} and deleted = 0") + DataMedicine findDataMedicineBySeriesUid(@Param("seriesUid") String seriesInstanceUid); + + /** + * 根据医学数据集ID查询被回收的医学数据集 + * + * @param datasetId 医学数据集ID + * @return DataMedicine 医学数据集 + */ + @Select("select * from data_medicine where id = #{id} and deleted = 1") + DataMedicine findDataMedicineByIdAndDeleteIsFalse(@Param("id") Long datasetId); +} diff --git a/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/domain/dto/DataLesionDrawInfoDTO.java b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/domain/dto/DataLesionDrawInfoDTO.java new file mode 100644 index 0000000..a1e1fa0 --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/domain/dto/DataLesionDrawInfoDTO.java @@ -0,0 +1,39 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.dcm.domain.dto; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.io.Serializable; + +/** + * @description 数据病损提取信息 + * @date 2020-12-28 + */ +@Data +public class DataLesionDrawInfoDTO implements Serializable { + + private static final long serialVersionUID = 1L; + + @ApiModelProperty("标注信息id") + private String drawId; + + @ApiModelProperty("所在层面") + private Integer sliceNumber; +} diff --git a/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/domain/dto/DataLesionSliceCreateDTO.java b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/domain/dto/DataLesionSliceCreateDTO.java new file mode 100644 index 0000000..502f32d --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/domain/dto/DataLesionSliceCreateDTO.java @@ -0,0 +1,43 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.dcm.domain.dto; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.io.Serializable; +import java.util.List; + +/** + * @description 病灶层面信息CreateDTO + * @date 2020-12-22 + */ +@Data +public class DataLesionSliceCreateDTO implements Serializable { + + private static final long serialVersionUID = 1L; + + @ApiModelProperty("病灶序号") + private Integer lesionOrder; + + @ApiModelProperty("层面信息") + private String sliceDesc; + + @ApiModelProperty("标注信息") + private List list; + +} diff --git a/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/domain/dto/DataLesionSliceDeleteDTO.java b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/domain/dto/DataLesionSliceDeleteDTO.java new file mode 100644 index 0000000..4fd1ad7 --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/domain/dto/DataLesionSliceDeleteDTO.java @@ -0,0 +1,37 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.dcm.domain.dto; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import javax.validation.constraints.NotNull; +import java.io.Serializable; + +/** + * @description 病灶信息删除DTO + * @date 2020-12-23 + */ +@Data +public class DataLesionSliceDeleteDTO implements Serializable { + + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "id", required = true) + @NotNull(message = "id不能为空") + private Long id; +} diff --git a/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/domain/dto/DataLesionSliceUpdateDTO.java b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/domain/dto/DataLesionSliceUpdateDTO.java new file mode 100644 index 0000000..6433d9e --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/domain/dto/DataLesionSliceUpdateDTO.java @@ -0,0 +1,49 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.dcm.domain.dto; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import javax.validation.constraints.NotNull; +import java.io.Serializable; +import java.util.List; + +/** + * @description 病灶层面信息UpdateDTO + * @date 2020-12-23 + */ +@Data +public class DataLesionSliceUpdateDTO implements Serializable { + + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "id", required = true) + @NotNull(message = "id不能为空") + private Long id; + + @ApiModelProperty(value = "lesionOrder", required = true) + @NotNull(message = "lesionOrder不能为空") + private Integer lesionOrder; + + @ApiModelProperty(value = "sliceDesc", required = true) + @NotNull(message = "sliceDesc不能为空") + private String sliceDesc; + + @ApiModelProperty("标注信息") + private List list; +} diff --git a/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/domain/dto/DataMedcineUpdateDTO.java b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/domain/dto/DataMedcineUpdateDTO.java new file mode 100644 index 0000000..c288b7d --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/domain/dto/DataMedcineUpdateDTO.java @@ -0,0 +1,42 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.dcm.domain.dto; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import javax.validation.constraints.NotBlank; +import java.io.Serializable; + +/** + * @description 医学数据集修改DTO + * @date 2020-11-26 + */ +@Data +public class DataMedcineUpdateDTO implements Serializable { + + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "名称") + @NotBlank(message = "名称不能为空") + private String name; + + @ApiModelProperty(value = "描述") + private String remark; + + +} diff --git a/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/domain/dto/DataMedicineCreateDTO.java b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/domain/dto/DataMedicineCreateDTO.java new file mode 100644 index 0000000..29b2ac6 --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/domain/dto/DataMedicineCreateDTO.java @@ -0,0 +1,78 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.dcm.domain.dto; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import org.dubhe.dcm.domain.entity.DataMedicine; + +import javax.validation.constraints.NotBlank; +import java.io.Serializable; + +/** + * @description 医学数据集创建DTO + * @date 2020-11-16 + */ +@Data +public class DataMedicineCreateDTO implements Serializable { + private static final long serialVersionUID = 1L; + + @ApiModelProperty("检查号") + @NotBlank(message = "检查号不能为空", groups = Create.class) + private String patientID; + + @ApiModelProperty("研究实例UID") + @NotBlank(message = "研究实例UID不能为空", groups = Create.class) + private String studyInstanceUID; + + @ApiModelProperty("序列实例UID") + @NotBlank(message = "序列实例UID不能为空", groups = Create.class) + private String seriesInstanceUID; + + @ApiModelProperty(value = "模式") + @NotBlank(message = "模式不能为空", groups = Create.class) + private String modality; + + @ApiModelProperty(value = "部位") + private String bodyPartExamined; + + @ApiModelProperty(value = "名称") + @NotBlank(message = "名称不能为空", groups = Create.class) + private String name; + + @ApiModelProperty(value = "描述") + private String remark; + + @ApiModelProperty(value = "标注类型") + private Integer annotateType; + + public @interface Create { + } + + /** + * 实体装换方法 + * + * @param dataMedicineCreateDTO 医学数据集创建DTO + * @param userId 用户ID + * @return 医学数据集实体 + */ + public static DataMedicine from(DataMedicineCreateDTO dataMedicineCreateDTO,Long userId) { + DataMedicine dataMedicine = new DataMedicine(dataMedicineCreateDTO,userId); + return dataMedicine; + } + +} diff --git a/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/domain/dto/DataMedicineDeleteDTO.java b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/domain/dto/DataMedicineDeleteDTO.java new file mode 100644 index 0000000..278b958 --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/domain/dto/DataMedicineDeleteDTO.java @@ -0,0 +1,37 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.dcm.domain.dto; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import javax.validation.constraints.NotNull; +import java.io.Serializable; + +/** + * @description 医学数据集删除DTO + * @date 2020-11-17 + */ +@Data +public class DataMedicineDeleteDTO implements Serializable { + + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "ids", required = true) + @NotNull(message = "id不能为空") + private Long[] ids; +} diff --git a/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/domain/dto/DataMedicineFileCreateDTO.java b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/domain/dto/DataMedicineFileCreateDTO.java new file mode 100644 index 0000000..abd0ed3 --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/domain/dto/DataMedicineFileCreateDTO.java @@ -0,0 +1,44 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.dcm.domain.dto; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import javax.validation.constraints.NotEmpty; +import java.io.Serializable; + +/** + * @description 医学数据集文件DTO + * @date 2020-12-11 + */ +@Data +public class DataMedicineFileCreateDTO implements Serializable { + + private static final long serialVersionUID = 1L; + + @ApiModelProperty("dcm文件路径") + @NotEmpty(message = "dcm文件路径不能为空") + private String url; + + @ApiModelProperty("SOPInstanceUID") + @NotEmpty(message = "SOPInstanceUID不能为空") + @JsonProperty(value="SOPInstanceUID") + private String SOPInstanceUID; + +} diff --git a/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/domain/dto/DataMedicineImportDTO.java b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/domain/dto/DataMedicineImportDTO.java new file mode 100644 index 0000000..53938da --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/domain/dto/DataMedicineImportDTO.java @@ -0,0 +1,43 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.dcm.domain.dto; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; +import java.io.Serializable; +import java.util.List; + +/** + * @description 医学数据集导入DTO + * @date 2020-11-16 + */ +@Data +public class DataMedicineImportDTO implements Serializable { + + private static final long serialVersionUID = 1L; + + @ApiModelProperty("dataMedicineFileList") + @NotEmpty(message = "dataMedicineFileList不能为空") + private List dataMedicineFileCreateList; + + @ApiModelProperty("医学数据集ID") + @NotNull(message = "医学数据集ID不能为空") + private Long id; +} diff --git a/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/domain/dto/DataMedicineQueryDTO.java b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/domain/dto/DataMedicineQueryDTO.java new file mode 100644 index 0000000..f84a3f2 --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/domain/dto/DataMedicineQueryDTO.java @@ -0,0 +1,78 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.dcm.domain.dto; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.dubhe.biz.db.annotation.Query; +import org.dubhe.biz.db.base.PageQueryBase; + +/** + * @description 数据集查询 + * @date 2020-04-10 + */ +@Data +@AllArgsConstructor +@NoArgsConstructor +@Builder +@ApiModel +public class DataMedicineQueryDTO extends PageQueryBase { + private static final long serialVersionUID = 1L; + + @ApiModelProperty("ID") + public String id; + + @ApiModelProperty("名称") + public String name; + + @ApiModelProperty("序列实例UID") + @Query(type = Query.Type.EQ, propName = "series_instance_uid") + public String seriesInstanceUID; + + @ApiModelProperty("检查号") + @Query(type = Query.Type.LIKE, propName = "patient_id") + public String patientID; + + @ApiModelProperty("研究实例UID") + @Query(type = Query.Type.EQ, propName = "study_instance_uid") + public String studyInstanceUID; + + @ApiModelProperty("状态") + @Query(type = Query.Type.EQ, propName = "status") + public Integer status; + + @ApiModelProperty("检查类型(模式)") + @Query(type = Query.Type.EQ, propName = "modality") + public String modality; + + @ApiModelProperty("检查身体部位") + @Query(type = Query.Type.EQ, propName = "body_part_examined") + public String bodyPartExamined; + + @ApiModelProperty(value = "类型 0: private 私有数据, 1:team 团队数据 2:public 公开数据") + @Query(type = Query.Type.EQ, propName = "type") + private Integer type; + + @ApiModelProperty(value = "标注类型: 1001.器官分割 2001.病灶检测之肺结节检测") + private Integer annotateType; + +} diff --git a/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/domain/dto/MedicineAnnotationDTO.java b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/domain/dto/MedicineAnnotationDTO.java new file mode 100644 index 0000000..5305385 --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/domain/dto/MedicineAnnotationDTO.java @@ -0,0 +1,60 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.dcm.domain.dto; + +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.dubhe.biz.base.constant.NumberConstant; + +import javax.validation.constraints.Max; +import javax.validation.constraints.Min; +import javax.validation.constraints.NotNull; +import java.io.Serializable; +import java.util.List; + +/** + * @description 医学自动标注DTO + * @date 2020-11-12 + */ +@Data +@Builder +@AllArgsConstructor +@NoArgsConstructor +public class MedicineAnnotationDTO implements Serializable { + + private static final long serialVersionUID = 1L; + + @ApiModelProperty("医学数据集ID") + @NotNull(message = "数据集ID不能为空") + private Long medicalId; + + @ApiModelProperty("标注信息") + @NotNull(message = "标注信息不能为空") + private String annotations; + + @ApiModelProperty("操作类型 0:保存 1:完成") + @NotNull(message = "操作类型不能为空") + @Min(value = NumberConstant.NUMBER_0) + @Max(value = NumberConstant.NUMBER_1) + private Integer type; + + @ApiModelProperty("要保存的dcm标注文件id") + private List medicalFiles; +} diff --git a/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/domain/dto/MedicineAutoAnnotationDTO.java b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/domain/dto/MedicineAutoAnnotationDTO.java new file mode 100644 index 0000000..d4e87d2 --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/domain/dto/MedicineAutoAnnotationDTO.java @@ -0,0 +1,44 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.dcm.domain.dto; + +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.validation.constraints.NotNull; +import java.io.Serializable; + +/** + * @description 医学自动标注DTO + * @date 2020-11-12 + */ +@Data +@Builder +@AllArgsConstructor +@NoArgsConstructor +public class MedicineAutoAnnotationDTO implements Serializable { + + private static final long serialVersionUID = 1L; + + @ApiModelProperty("医学数据集ID") + @NotNull(message = "自动标注的数据集不能为空") + private Long medicalId; + +} diff --git a/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/domain/entity/DataLesionSlice.java b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/domain/entity/DataLesionSlice.java new file mode 100644 index 0000000..571b7ad --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/domain/entity/DataLesionSlice.java @@ -0,0 +1,69 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.dcm.domain.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import lombok.RequiredArgsConstructor; +import org.dubhe.biz.db.entity.BaseEntity; + +import java.io.Serializable; + +/** + * @description 病灶层面信息 + * @date 2020-12-22 + */ +@Data +@RequiredArgsConstructor +@TableName("data_lesion_slice") +@ApiModel(value = "DataLesionSlice 对象", description = "病灶层面信息") +public class DataLesionSlice extends BaseEntity implements Serializable { + + private static final long serialVersionUID = 1L; + + @TableId(type = IdType.AUTO) + @TableField(value = "id") + private Long id; + + @ApiModelProperty("病灶序号") + private Integer lesionOrder; + + @ApiModelProperty("病灶层面") + private String sliceDesc; + + @ApiModelProperty("数据集ID") + private Long medicineId; + + @ApiModelProperty("标注信息") + private String drawInfo; + + @ApiModelProperty(value = "资源拥有人id") + private Long originUserId; + + public DataLesionSlice(Integer lesionOrder, String sliceDesc, Long medicalId, String drawInfo, Long originUserId) { + this.lesionOrder = lesionOrder; + this.sliceDesc = sliceDesc; + this.medicineId = medicalId; + this.drawInfo = drawInfo; + this.originUserId = originUserId; + } +} diff --git a/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/domain/entity/DataMedicine.java b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/domain/entity/DataMedicine.java new file mode 100644 index 0000000..7b0da8c --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/domain/entity/DataMedicine.java @@ -0,0 +1,101 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.dcm.domain.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import org.dubhe.biz.db.entity.BaseEntity; +import org.dubhe.data.machine.constant.DataStateCodeConstant; +import org.dubhe.dcm.domain.dto.DataMedicineCreateDTO; + +import java.io.Serializable; + +/** + * @description 医学数据集 + * @date 2020-11-11 + */ +@Data +@TableName("data_medicine") +@ApiModel(value = "DataMedicine 对象", description = "医学数据集") +public class DataMedicine extends BaseEntity implements Serializable { + + private static final long serialVersionUID = 1L; + + @TableId(type = IdType.AUTO) + @TableField(value = "id") + private Long id; + + @ApiModelProperty("检查号") + private String patientId; + + @ApiModelProperty("研究实例UID") + private String studyInstanceUid; + + @ApiModelProperty("序列实例UID") + private String seriesInstanceUid; + + @ApiModelProperty(value = "0:未标注,1:手动标注中,2:自动标注中,3:自动标注完成,4:标注完成") + private Integer status; + + @ApiModelProperty(value = "模式") + private String modality; + + @ApiModelProperty(value = "部位") + private String bodyPartExamined; + + @ApiModelProperty(value = "名称") + private String name; + + @ApiModelProperty(value = "描述") + private String remark; + + @ApiModelProperty("资源拥有人") + private Long originUserId; + + @ApiModelProperty(value = "类型 0: private 私有数据, 1:team 团队数据 2:public 公开数据") + private Integer type; + + @ApiModelProperty(value = "标注类型: 1001.器官分割 2001.病灶检测之肺结节检测") + private Integer annotateType; + + public DataMedicine() { + } + + /** + * 转换DataMedicine对象 + * + * @param dataMedicineCreateDTO 创建数据集所需参数 + * @param userId 用户ID + */ + public DataMedicine(DataMedicineCreateDTO dataMedicineCreateDTO, Long userId) { + this.patientId = dataMedicineCreateDTO.getPatientID(); + this.studyInstanceUid = dataMedicineCreateDTO.getStudyInstanceUID(); + this.seriesInstanceUid = dataMedicineCreateDTO.getSeriesInstanceUID(); + this.modality = dataMedicineCreateDTO.getModality(); + this.bodyPartExamined = dataMedicineCreateDTO.getBodyPartExamined(); + this.status = DataStateCodeConstant.NOT_ANNOTATION_STATE; + this.name = dataMedicineCreateDTO.getName(); + this.remark = dataMedicineCreateDTO.getRemark(); + this.originUserId = userId; + this.annotateType = dataMedicineCreateDTO.getAnnotateType(); + } +} diff --git a/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/domain/entity/DataMedicineFile.java b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/domain/entity/DataMedicineFile.java new file mode 100644 index 0000000..88bc77a --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/domain/entity/DataMedicineFile.java @@ -0,0 +1,70 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.dcm.domain.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import org.dubhe.biz.db.entity.BaseEntity; + +import java.io.Serializable; + +/** + * @description 医学数据文件 + * @date 2020-11-11 + */ +@Data +@TableName("data_medicine_file") +@ApiModel(value = "DataMedicineFile 对象", description = "医学数据文件") +public class DataMedicineFile extends BaseEntity implements Serializable { + + private static final long serialVersionUID = 1L; + + @TableId(type = IdType.AUTO) + private Long id; + + @ApiModelProperty("医学数据集ID") + private Long medicineId; + + @ApiModelProperty("医学数据集名称") + private String name; + + @ApiModelProperty("文件地址") + private String url; + + @ApiModelProperty("资源拥有人") + private Long originUserId; + + @ApiModelProperty("文件状态") + private Integer status; + + @ApiModelProperty("instanceNumber") + private Integer instanceNumber; + + @ApiModelProperty("sopInstanceUid") + private String sopInstanceUid; + + @ApiModelProperty("imagePositionPatient") + private Double imagePositionPatient; + + public DataMedicineFile() { + + } +} diff --git a/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/domain/vo/DataLesionSliceVO.java b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/domain/vo/DataLesionSliceVO.java new file mode 100644 index 0000000..80a9d0b --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/domain/vo/DataLesionSliceVO.java @@ -0,0 +1,49 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.dcm.domain.vo; + +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.io.Serializable; + +/** + * @description 数据病变切片 + * @date 2020-12-28 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class DataLesionSliceVO implements Serializable { + + private static final long serialVersionUID = 1L; + + private Long id; + + @ApiModelProperty("病灶序号") + private Integer lesionOrder; + + @ApiModelProperty("病灶层面") + private String sliceDesc; + + @ApiModelProperty("标注信息") + private String list; + +} diff --git a/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/domain/vo/DataMedicineCompleteAnnotationVO.java b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/domain/vo/DataMedicineCompleteAnnotationVO.java new file mode 100644 index 0000000..066332f --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/domain/vo/DataMedicineCompleteAnnotationVO.java @@ -0,0 +1,41 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.dcm.domain.vo; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.io.Serializable; + +/** + * @description 医学数据集完成标注文件VO + * @date 2020-11-17 + */ +@Data +public class DataMedicineCompleteAnnotationVO implements Serializable { + + private static final long serialVersionUID = 1L; + + @ApiModelProperty("序列实例UID") + private String StudyInstanceUID; + + @ApiModelProperty("研究实例UID") + private String SeriesInstanceUID; + + @ApiModelProperty("完成标注文件") + private String annotations; +} diff --git a/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/domain/vo/DataMedicineVO.java b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/domain/vo/DataMedicineVO.java new file mode 100644 index 0000000..68d26c1 --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/domain/vo/DataMedicineVO.java @@ -0,0 +1,93 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.dcm.domain.vo; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import org.dubhe.dcm.domain.entity.DataMedicine; + +import java.io.Serializable; +import java.sql.Timestamp; + +/** + * @description 医学数据集详情VO + * @date 2020-11-17 + */ +@Data +public class DataMedicineVO implements Serializable { + + private static final long serialVersionUID = 1L; + + @ApiModelProperty("医学数据集id") + private Long id; + + @ApiModelProperty(value = "0:未标注,1:手动标注中,2:自动标注中,3:自动标注完成,4:标注完成") + private Integer status; + + @ApiModelProperty("检查号") + private String patientID; + + @ApiModelProperty("研究实例UID") + private String studyInstanceUID; + + @ApiModelProperty("序列实例UID") + private String seriesInstanceUID; + + @ApiModelProperty(value = "模式") + private String modality; + + @ApiModelProperty(value = "部位") + private String bodyPartExamined; + + @ApiModelProperty(value = "创建时间") + private Timestamp createTime; + + @ApiModelProperty(value = "更新时间") + private Timestamp updateTime; + + @ApiModelProperty(value = "名称") + private String name; + + @ApiModelProperty(value = "描述") + private String remark; + + @ApiModelProperty(value = "标注类型") + private Integer annotateType; + + /** + * 医学数据集 转化 医学数据集详情VO 方法 + * + * @param dataMedicine 医学数据集实体 + * @return 医学数据集详情VO + */ + public static DataMedicineVO from(DataMedicine dataMedicine){ + DataMedicineVO dataMedicineVO = new DataMedicineVO(); + dataMedicineVO.setId(dataMedicine.getId()); + dataMedicineVO.setStatus(dataMedicine.getStatus()); + dataMedicineVO.setPatientID(dataMedicine.getPatientId()); + dataMedicineVO.setStudyInstanceUID(dataMedicine.getStudyInstanceUid()); + dataMedicineVO.setSeriesInstanceUID(dataMedicine.getSeriesInstanceUid()); + dataMedicineVO.setModality(dataMedicine.getModality()); + dataMedicineVO.setBodyPartExamined(dataMedicine.getBodyPartExamined()); + dataMedicineVO.setCreateTime(dataMedicine.getCreateTime()); + dataMedicineVO.setUpdateTime(dataMedicine.getUpdateTime()); + dataMedicineVO.setName(dataMedicine.getName()); + dataMedicineVO.setRemark(dataMedicine.getRemark()); + dataMedicineVO.setAnnotateType(dataMedicine.getAnnotateType()); + return dataMedicineVO; + } +} diff --git a/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/domain/vo/ScheduleVO.java b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/domain/vo/ScheduleVO.java new file mode 100644 index 0000000..f0755f0 --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/domain/vo/ScheduleVO.java @@ -0,0 +1,46 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.dcm.domain.vo; + +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * @description 医学数据集状态VO + * @date 2021-01-13 + */ +@NoArgsConstructor +@AllArgsConstructor +@Data +@Builder +public class ScheduleVO { + + @ApiModelProperty("未标注") + private Integer unfinished; + + @ApiModelProperty("标注完成") + private Integer finished; + + @ApiModelProperty("自动标注完成") + private Integer autoFinished; + + @ApiModelProperty("标注中") + private Integer manualAnnotating; +} diff --git a/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/constant/DcmDataStateCodeConstant.java b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/constant/DcmDataStateCodeConstant.java new file mode 100644 index 0000000..a324a06 --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/constant/DcmDataStateCodeConstant.java @@ -0,0 +1,49 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.dcm.machine.constant; + +/** + * @description 数据集状态码 + * @date 2020-09-03 + */ +public class DcmDataStateCodeConstant { + + private DcmDataStateCodeConstant() { + } + + /** + * 未标注 + */ + public static final Integer NOT_ANNOTATION_STATE = 101; + /** + * 标注中 + */ + public static final Integer ANNOTATION_DATA_STATE = 102; + /** + * 自动标注中 + */ + public static final Integer AUTOMATIC_LABELING_STATE = 103; + /** + * 自动标注完成 + */ + public static final Integer AUTO_ANNOTATION_COMPLETE_STATE = 104; + /** + * 标注完成 + */ + public static final Integer ANNOTATION_COMPLETE_STATE = 105; + +} diff --git a/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/constant/DcmDataStateMachineConstant.java b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/constant/DcmDataStateMachineConstant.java new file mode 100644 index 0000000..a142398 --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/constant/DcmDataStateMachineConstant.java @@ -0,0 +1,58 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.dcm.machine.constant; + +/** + * @description 状态机事件常量 + * @date 2020-08-27 + */ +public class DcmDataStateMachineConstant { + + private DcmDataStateMachineConstant() { + } + + /** + * 数据集状态 + */ + public static final String DCM_DATA_STATE_MACHINE = "dcmDataMedicineStateMachine"; + + /** + * 标注事件 标注中/自动标注完成/完成/未标注-->保存-->标注中 + */ + public static final String ANNOTATION_SAVE_EVENT = "annotationSaveEvent"; + + /** + * 标注事件 未标注-->自动标注-->自动标注中 + */ + public static final String AUTO_ANNOTATION_SAVE_EVENT = "autoAnnotationSaveEvent"; + + /** + * 标注事件 注中/自动标注完成/完成/未标注-->完成-->标注完成 + */ + public static final String ANNOTATION_COMPLETE_EVENT = "annotationCompleteEvent"; + + /** + * 标注事件 标注中-->自动标注-->自动标注中 + */ + public static final String AUTO_ANNOTATION_EVENT = "autoAnnotationEvent"; + + /** + * 标注事件 自动标注中-->自动标注-->自动标注完成 + */ + public static final String AUTO_ANNOTATION_COMPLETE_EVENT = "autoAnnotationCompleteEvent"; + +} \ No newline at end of file diff --git a/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/constant/DcmFileStateCodeConstant.java b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/constant/DcmFileStateCodeConstant.java new file mode 100644 index 0000000..3522a66 --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/constant/DcmFileStateCodeConstant.java @@ -0,0 +1,46 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.dcm.machine.constant; + +/** + * @description 数据集状态码 + * @date 2020-09-03 + */ +public class DcmFileStateCodeConstant { + + private DcmFileStateCodeConstant(){ + + } + + /** + * 未标注 + */ + public static final Integer NOT_ANNOTATION_FILE_STATE = 101; + /** + * 标注中 + */ + public static final Integer ANNOTATION_FILE_STATE = 102; + /** + * 自动标注完成 + */ + public static final Integer AUTO_ANNOTATION_COMPLETE_FILE_STATE = 103; + /** + * 标注完成 + */ + public static final Integer ANNOTATION_COMPLETE_FILE_STATE = 104; + +} \ No newline at end of file diff --git a/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/constant/DcmFileStateMachineConstant.java b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/constant/DcmFileStateMachineConstant.java new file mode 100644 index 0000000..cef3272 --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/constant/DcmFileStateMachineConstant.java @@ -0,0 +1,52 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.dcm.machine.constant; + +/** + * @description 文件状态事件常量 + * @date 2020-08-31 + */ +public class DcmFileStateMachineConstant { + + private DcmFileStateMachineConstant() { + } + + /** + * 文件状态 + */ + public static final String DCM_FILE_STATE_MACHINE = "dcmFileStateMachine"; + + /** + * 文件事件 标注中/自动标注完成/完成/未标注-->保存-->标注中 + */ + public static final String ANNOTATION_SAVE_EVENT = "annotationSaveEvent"; + + /** + * 文件事件 标注中/自动标注完成/完成/未标注-->完成-->标注完成 + */ + public static final String ANNOTATION_COMPLETE_EVENT = "annotationCompleteEvent"; + + /** + * 文件事件 未标注-->自动标注文件-->自动标注完成 + */ + public static final String AUTO_ANNOTATION_EVENT = "autoAnnotationEvent"; + /** + * 文件事件 未标注-->自动标注文件-->自动标注完成 + */ + public static final String AUTO_ANNOTATION_SAVE_EVENT = "autoAnnotationSaveEvent"; + +} \ No newline at end of file diff --git a/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/enums/DcmDataStateEnum.java b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/enums/DcmDataStateEnum.java new file mode 100644 index 0000000..669a075 --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/enums/DcmDataStateEnum.java @@ -0,0 +1,124 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.dcm.machine.enums; + +import org.dubhe.dcm.machine.constant.DcmDataStateCodeConstant; + +/** + * @description 数据集状态类 + * @date 2020-08-28 + */ +public enum DcmDataStateEnum { + /** + * 未标注 + */ + NOT_ANNOTATION_STATE(DcmDataStateCodeConstant.NOT_ANNOTATION_STATE, "notAnnotationDcmState","未标注"), + /** + * 标注中 + */ + ANNOTATION_DATA_STATE(DcmDataStateCodeConstant.ANNOTATION_DATA_STATE, "annotationDataState","标注中"), + /** + * 自动标注中 + */ + AUTOMATIC_LABELING_STATE(DcmDataStateCodeConstant.AUTOMATIC_LABELING_STATE, "automaticLabelingDcmState","自动标注中"), + /** + * 自动标注完成 + */ + AUTO_ANNOTATION_COMPLETE_STATE(DcmDataStateCodeConstant.AUTO_ANNOTATION_COMPLETE_STATE, "autoAnnotationCompleteDcmState","自动标注完成"), + /** + * 标注完成 + */ + ANNOTATION_COMPLETE_STATE(DcmDataStateCodeConstant.ANNOTATION_COMPLETE_STATE, "annotationCompleteDcmState","标注完成"); + + /** + * 编码 + */ + private Integer code; + /** + * 状态机 + */ + private String stateMachine; + /** + * 描述 + */ + private String description; + + public Integer getCode() { + return code; + } + + public void setCode(Integer code) { + this.code = code; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getStateMachine() { + return stateMachine; + } + + public void setStateMachine(String stateMachine) { + this.stateMachine = stateMachine; + } + + DcmDataStateEnum(Integer code, String stateMachine , String description) { + this.code = code; + this.stateMachine = stateMachine; + this.description = description; + } + + /** + * 根据CODE 获取 DESCRIPTION + * + * @param code 数据集状态编码 + * @return String + */ + public static String getStateMachine(Integer code) { + if (code != null) { + for (DcmDataStateEnum dcmDataStateEnum : DcmDataStateEnum.values()) { + if (dcmDataStateEnum.getCode().equals(code)) { + return dcmDataStateEnum.getStateMachine(); + } + } + } + return null; + } + + /** + * 根据CODE 获取 DataStateEnum + * + * @param code 数据集状态编码 + * @return String + */ + public static DcmDataStateEnum getState(Integer code) { + if (code != null) { + for (DcmDataStateEnum dcmDataStateEnum : DcmDataStateEnum.values()) { + if (dcmDataStateEnum.getCode().equals(code)) { + return dcmDataStateEnum; + } + } + } + return null; + } + +} diff --git a/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/enums/DcmFileStateEnum.java b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/enums/DcmFileStateEnum.java new file mode 100644 index 0000000..e657faa --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/enums/DcmFileStateEnum.java @@ -0,0 +1,138 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.dcm.machine.enums; + + +import org.dubhe.dcm.machine.constant.DcmFileStateCodeConstant; + +import java.util.HashSet; +import java.util.Set; + + +/** + * @description 文件状态枚举类 + * @date 2020-08-28 + */ +public enum DcmFileStateEnum { + + /** + * 未标注 + */ + NOT_ANNOTATION_FILE_STATE(DcmFileStateCodeConstant.NOT_ANNOTATION_FILE_STATE, "notAnnotationDcmFileState","未标注"), + /** + * 标注中 + */ + ANNOTATION_FILE_STATE(DcmFileStateCodeConstant.ANNOTATION_FILE_STATE, "annotationFileState","标注中"), + /** + * 自动标注完成 + */ + AUTO_ANNOTATION_COMPLETE_FILE_STATE(DcmFileStateCodeConstant.AUTO_ANNOTATION_COMPLETE_FILE_STATE, "autoAnnotationCompleteDcmFileState","自动标注完成"), + /** + * 标注完成 + */ + ANNOTATION_COMPLETE_FILE_STATE(DcmFileStateCodeConstant.ANNOTATION_COMPLETE_FILE_STATE, "annotationCompleteDcmFileState","标注完成"); + /** + * 编码 + */ + private Integer code; + /** + * 状态机 + */ + private String stateMachine; + /** + * 描述 + */ + private String description; + + public Integer getCode() { + return code; + } + + public void setCode(Integer code) { + this.code = code; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getStateMachine() { + return stateMachine; + } + + public void setStateMachine(String stateMachine) { + this.stateMachine = stateMachine; + } + + DcmFileStateEnum(Integer code, String stateMachine , String description) { + this.code = code; + this.stateMachine = stateMachine; + this.description = description; + } + + /** + * 根据CODE 获取 DESCRIPTION + * + * @param code 文件状态编码 + * @return String + */ + public static String getStateMachine(Integer code) { + if (code != null) { + for (DcmFileStateEnum dcmFileStateEnum : DcmFileStateEnum.values()) { + if (dcmFileStateEnum.getCode().equals(code)) { + return dcmFileStateEnum.getStateMachine(); + } + } + } + return null; + } + + /** + * 获取所有文件状态值 + * + * @return + */ + public static Set getAllValue() { + Set allValues = new HashSet<>(); + for (DcmFileStateEnum fileStatusEnum : DcmFileStateEnum.values()) { + allValues.add(fileStatusEnum.code); + } + return allValues; + } + + /** + * 根据CODE 获取 状态 + * + * @param code 文件状态编码 + * @return String + */ + public static DcmFileStateEnum getState(Integer code) { + if (code != null) { + for (DcmFileStateEnum dcmFileStateEnum : DcmFileStateEnum.values()) { + if (dcmFileStateEnum.getCode().equals(code)) { + return dcmFileStateEnum; + } + } + } + return null; + } + +} diff --git a/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/proxy/DcmStateMachineProxy.java b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/proxy/DcmStateMachineProxy.java new file mode 100644 index 0000000..be979e4 --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/proxy/DcmStateMachineProxy.java @@ -0,0 +1,61 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.dcm.machine.proxy; + +import org.dubhe.biz.base.utils.SpringContextHolder; +import org.dubhe.biz.statemachine.dto.StateChangeDTO; +import org.dubhe.biz.statemachine.utils.StateMachineProxyUtil; +import org.dubhe.dcm.machine.statemachine.DcmGlobalStateMachine; +import org.springframework.stereotype.Component; + +import java.util.List; + +/** + * @description 代理执行状态机 + * @date 2020-08-27 + */ +@Component +public class DcmStateMachineProxy { + + /** + * 获取全局状态机Bean + * + * @return Object + */ + public static Object getGlobalStateMachine() { + return SpringContextHolder.getBean(DcmGlobalStateMachine.class); + } + + /** + * 代理执行单个状态机的状态切换 + * + * @param stateChangeDTO 数据集状态切换信息 + */ + public static void proxyExecutionSingleState(StateChangeDTO stateChangeDTO) { + StateMachineProxyUtil.proxyExecutionSingleState(stateChangeDTO,getGlobalStateMachine()); + } + + /** + * 代理执行多个状态机的状态切换 + * + * @param stateChangeDTOList 多个状态机切换信息 + */ + public static void proxyExecutionRelationState(List stateChangeDTOList) { + StateMachineProxyUtil.proxyExecutionRelationState(stateChangeDTOList,getGlobalStateMachine()); + } + +} diff --git a/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/state/AbstractDataMedicineState.java b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/state/AbstractDataMedicineState.java new file mode 100644 index 0000000..839d91c --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/state/AbstractDataMedicineState.java @@ -0,0 +1,71 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.dcm.machine.state; + + +import org.dubhe.dcm.domain.entity.DataMedicine; + +/** + * @description 数据集状态类 + * @date 2020-08-27 + */ +public abstract class AbstractDataMedicineState { + + /** + * 数据集事件 未标注-->标注数据集-->标注中 + * + * @param medical 医学数据集对象 + */ + public void annotationSaveEvent(DataMedicine medical) { + } + + /** + * 数据集事件 未标注-->自动标注-->自动标注中 + * + * @param medical 医学数据集对象 + */ + public void autoAnnotationSaveEvent(DataMedicine medical) { + } + + /** + * 数据集事件 标注中-->自动标注-->自动标注中 + * + * @param primaryKeyId 业务ID + */ + public void autoAnnotationEvent(Long primaryKeyId) { + } + + /** + * 数据集事件 自动标注中-->自动标注-->自动标注完成 + * + * @param primaryKeyId 业务ID + */ + public void autoAnnotationCompleteEvent(Long primaryKeyId) { + } + + /** + * 数据集事件 自动标注完成-->标注-->标注完成 + * + * @param medical 医学数据集对象 + */ + public void annotationCompleteEvent(DataMedicine medical) { + } + + + + +} \ No newline at end of file diff --git a/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/state/AbstractDcmFileState.java b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/state/AbstractDcmFileState.java new file mode 100644 index 0000000..c53526f --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/state/AbstractDcmFileState.java @@ -0,0 +1,67 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.dcm.machine.state; + + +import java.util.List; + +/** + * @description 文件抽象类 + * @date 2020-08-27 + */ +public abstract class AbstractDcmFileState { + + /** + * 文件事件 未标注-->自动标注文件-->标注中 + * + * @param fileIds 文件ID + */ + public void annotationEvent(List fileIds) { + } + + /** + * 文件事件 未标注-->自动标注文件-->自动标注完成 + * + * @param fileIds 文件ID + */ + public void autoAnnotationSaveEvent(List fileIds) { + } + + /** + * 文件事件 标注中-->自动标注文件-->自动标注完成 + * + * @param fileIds 文件ID + */ + public void autoAnnotationEvent(List fileIds) { + } + + /** + * 文件事件 标注中/自动标注完成/完成/未标注-->保存-->标注中 + * + * @param fileIds 医学数据集文件ID + */ + public void annotationSaveEvent(List fileIds){ + } + + /** + * 文件事件 标注中/自动标注完成/完成/未标注-->完成-->标注完成 + * + * @param fileIds 医学数据集文件ID + */ + public void annotationCompleteEvent(List fileIds){ + } +} diff --git a/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/state/specific/datamedicine/AnnotationCompleteDcmState.java b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/state/specific/datamedicine/AnnotationCompleteDcmState.java new file mode 100644 index 0000000..e343f1f --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/state/specific/datamedicine/AnnotationCompleteDcmState.java @@ -0,0 +1,73 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.dcm.machine.state.specific.datamedicine; + +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.dubhe.dcm.dao.DataMedicineMapper; +import org.dubhe.dcm.domain.entity.DataMedicine; +import org.dubhe.dcm.machine.enums.DcmDataStateEnum; +import org.dubhe.dcm.machine.state.AbstractDataMedicineState; +import org.dubhe.dcm.machine.statemachine.DcmDataMedicineStateMachine; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Lazy; +import org.springframework.stereotype.Component; + +/** + * @description 标注完成状态类 + * @date 2020-08-27 + */ +@Component +public class AnnotationCompleteDcmState extends AbstractDataMedicineState { + + + @Autowired + @Lazy + private DcmDataMedicineStateMachine dcmDataMedicineStateMachine; + + @Autowired + private DataMedicineMapper dataMedicineMapper; + + /** + * 数据集 标注完成-->标注-->标注中 + * + * @param medical 医学数据集对象 + */ + @Override + public void annotationSaveEvent(DataMedicine medical) { + LogUtil.debug(LogEnum.STATE_MACHINE, " 【标注完成】 执行事件前内存中状态机的状态 :{} ", dcmDataMedicineStateMachine.getMemoryDataMedicineState()); + LogUtil.debug(LogEnum.STATE_MACHINE, " 接受参数: {} ", medical); + dataMedicineMapper.updateStatus(medical.getId(), DcmDataStateEnum.ANNOTATION_DATA_STATE.getCode()); + dcmDataMedicineStateMachine.setMemoryDataMedicineState(dcmDataMedicineStateMachine.getAnnotationDataState()); + LogUtil.debug(LogEnum.STATE_MACHINE, " 【标注完成】 执行事件后内存状态机的切换: {}", dcmDataMedicineStateMachine.getMemoryDataMedicineState()); + } + + + /** + * 数据集 标注完成-->完成-->标注完成 + * + * @param medical 医学数据集对象 + */ + @Override + public void annotationCompleteEvent(DataMedicine medical) { + LogUtil.debug(LogEnum.STATE_MACHINE, " 【标注完成】 执行事件前内存中状态机的状态 :{} ", dcmDataMedicineStateMachine.getMemoryDataMedicineState()); + LogUtil.debug(LogEnum.STATE_MACHINE, " 接受参数: {} ", medical); + dcmDataMedicineStateMachine.setMemoryDataMedicineState(dcmDataMedicineStateMachine.getAnnotationCompleteDcmState()); + LogUtil.debug(LogEnum.STATE_MACHINE, " 【标注完成】 执行事件后内存状态机的切换: {}", dcmDataMedicineStateMachine.getMemoryDataMedicineState()); + } + +} \ No newline at end of file diff --git a/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/state/specific/datamedicine/AnnotationDataState.java b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/state/specific/datamedicine/AnnotationDataState.java new file mode 100644 index 0000000..5eecf99 --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/state/specific/datamedicine/AnnotationDataState.java @@ -0,0 +1,86 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.dcm.machine.state.specific.datamedicine; + +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.dubhe.dcm.dao.DataMedicineMapper; +import org.dubhe.dcm.domain.entity.DataMedicine; +import org.dubhe.dcm.machine.enums.DcmDataStateEnum; +import org.dubhe.dcm.machine.state.AbstractDataMedicineState; +import org.dubhe.dcm.machine.statemachine.DcmDataMedicineStateMachine; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Lazy; +import org.springframework.stereotype.Service; + +/** + * @description 标注中 + * @date 2020-11-17 + */ +@Service +public class AnnotationDataState extends AbstractDataMedicineState { + + @Autowired + @Lazy + private DcmDataMedicineStateMachine dcmDataMedicineStateMachine; + + @Autowired + private DataMedicineMapper dataMedicineMapper; + + + /** + * 数据集 标注中-->自动标注-->自动标注中 + * + * @param primaryKeyId 业务ID + */ + @Override + public void autoAnnotationEvent(Long primaryKeyId) { + LogUtil.debug(LogEnum.STATE_MACHINE, " 【标注中】 执行事件前内存中状态机的状态 :{} ", dcmDataMedicineStateMachine.getMemoryDataMedicineState()); + LogUtil.debug(LogEnum.STATE_MACHINE, " 接受参数: {} ", primaryKeyId); + dataMedicineMapper.updateStatus(primaryKeyId, DcmDataStateEnum.AUTOMATIC_LABELING_STATE.getCode()); + dcmDataMedicineStateMachine.setMemoryDataMedicineState(dcmDataMedicineStateMachine.getAutomaticLabelingDcmState()); + LogUtil.debug(LogEnum.STATE_MACHINE, " 【标注中】 执行事件后内存状态机的切换: {}", dcmDataMedicineStateMachine.getMemoryDataMedicineState()); + } + + /** + * 数据集 标注中-->标注-->标注中 + * + * @param medical 医学数据集对象 + */ + @Override + public void annotationSaveEvent(DataMedicine medical) { + LogUtil.debug(LogEnum.STATE_MACHINE, " 【标注中】 执行事件前内存中状态机的状态 :{} ", dcmDataMedicineStateMachine.getMemoryDataMedicineState()); + LogUtil.debug(LogEnum.STATE_MACHINE, " 接受参数: {} ", medical); + dcmDataMedicineStateMachine.setMemoryDataMedicineState(dcmDataMedicineStateMachine.getAnnotationDataState()); + LogUtil.debug(LogEnum.STATE_MACHINE, " 【标注中】 执行事件后内存状态机的切换: {}", dcmDataMedicineStateMachine.getMemoryDataMedicineState()); + } + + /** + * 数据集 标注中-->完成-->标注完成 + * + * @param medical 医学数据集对象 + */ + @Override + public void annotationCompleteEvent(DataMedicine medical) { + LogUtil.debug(LogEnum.STATE_MACHINE, " 【标注中】 执行事件前内存中状态机的状态 :{} ", dcmDataMedicineStateMachine.getMemoryDataMedicineState()); + LogUtil.debug(LogEnum.STATE_MACHINE, " 接受参数: {} ", medical); + dataMedicineMapper.updateStatus(medical.getId(), DcmDataStateEnum.ANNOTATION_COMPLETE_STATE.getCode()); + dcmDataMedicineStateMachine.setMemoryDataMedicineState(dcmDataMedicineStateMachine.getAnnotationCompleteDcmState()); + LogUtil.debug(LogEnum.STATE_MACHINE, " 【标注中】 执行事件后内存状态机的切换: {}", dcmDataMedicineStateMachine.getMemoryDataMedicineState()); + } + +} diff --git a/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/state/specific/datamedicine/AutoAnnotationCompleteDcmState.java b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/state/specific/datamedicine/AutoAnnotationCompleteDcmState.java new file mode 100644 index 0000000..dde76ca --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/state/specific/datamedicine/AutoAnnotationCompleteDcmState.java @@ -0,0 +1,72 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.dcm.machine.state.specific.datamedicine; + +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.dubhe.dcm.dao.DataMedicineMapper; +import org.dubhe.dcm.domain.entity.DataMedicine; +import org.dubhe.dcm.machine.enums.DcmDataStateEnum; +import org.dubhe.dcm.machine.state.AbstractDataMedicineState; +import org.dubhe.dcm.machine.statemachine.DcmDataMedicineStateMachine; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Lazy; +import org.springframework.stereotype.Component; + +/** + * @description 自动标注完成状态类 + * @date 2020-08-27 + */ +@Component +public class AutoAnnotationCompleteDcmState extends AbstractDataMedicineState { + + @Autowired + @Lazy + private DcmDataMedicineStateMachine dcmDataMedicineStateMachine; + + @Autowired + private DataMedicineMapper dataMedicineMapper; + + /** + * 数据集 自动标注完成-->标注-->标注中 + * + * @param medical 医学数据集对象 + */ + @Override + public void annotationSaveEvent(DataMedicine medical) { + LogUtil.debug(LogEnum.STATE_MACHINE, " 【自动标注完成】 执行事件前内存中状态机的状态 :{} ", dcmDataMedicineStateMachine.getMemoryDataMedicineState()); + LogUtil.debug(LogEnum.STATE_MACHINE, " 接受参数: {} ", medical); + dataMedicineMapper.updateStatus(medical.getId(), DcmDataStateEnum.ANNOTATION_DATA_STATE.getCode()); + dcmDataMedicineStateMachine.setMemoryDataMedicineState(dcmDataMedicineStateMachine.getAnnotationDataState()); + LogUtil.debug(LogEnum.STATE_MACHINE, " 【自动标注完成】 执行事件后内存状态机的切换: {}", dcmDataMedicineStateMachine.getMemoryDataMedicineState()); + } + + /** + * 数据集 自动标注完成-->完成-->标注完成 + * + * @param medical 医学数据集对象 + */ + @Override + public void annotationCompleteEvent(DataMedicine medical) { + LogUtil.debug(LogEnum.STATE_MACHINE, " 【自动标注完成】 执行事件前内存中状态机的状态 :{} ", dcmDataMedicineStateMachine.getMemoryDataMedicineState()); + LogUtil.debug(LogEnum.STATE_MACHINE, " 接受参数: {} ", medical); + dataMedicineMapper.updateStatus(medical.getId(), DcmDataStateEnum.ANNOTATION_COMPLETE_STATE.getCode()); + dcmDataMedicineStateMachine.setMemoryDataMedicineState(dcmDataMedicineStateMachine.getAnnotationCompleteDcmState()); + LogUtil.debug(LogEnum.STATE_MACHINE, " 【自动标注完成】 执行事件后内存状态机的切换: {}", dcmDataMedicineStateMachine.getMemoryDataMedicineState()); + } + +} \ No newline at end of file diff --git a/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/state/specific/datamedicine/AutomaticLabelingDcmState.java b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/state/specific/datamedicine/AutomaticLabelingDcmState.java new file mode 100644 index 0000000..9d6f2c8 --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/state/specific/datamedicine/AutomaticLabelingDcmState.java @@ -0,0 +1,57 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.dcm.machine.state.specific.datamedicine; + +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.dubhe.dcm.dao.DataMedicineMapper; +import org.dubhe.dcm.machine.enums.DcmDataStateEnum; +import org.dubhe.dcm.machine.state.AbstractDataMedicineState; +import org.dubhe.dcm.machine.statemachine.DcmDataMedicineStateMachine; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Lazy; +import org.springframework.stereotype.Component; + +/** + * @description 自动标注中状态类 + * @date 2020-08-27 + */ +@Component +public class AutomaticLabelingDcmState extends AbstractDataMedicineState { + + @Autowired + @Lazy + private DcmDataMedicineStateMachine dcmDataMedicineStateMachine; + + @Autowired + private DataMedicineMapper dataMedicineMapper; + + /** + * 自动标注中 自动标注中-->自动标注->自动标注完成 + * + * @param primaryKeyId 业务ID + */ + @Override + public void autoAnnotationCompleteEvent(Long primaryKeyId) { + LogUtil.debug(LogEnum.STATE_MACHINE, " 【自动标注中】 执行事件前内存中状态机的状态 :{} ", dcmDataMedicineStateMachine.getMemoryDataMedicineState()); + LogUtil.debug(LogEnum.STATE_MACHINE, " 接受参数: {} ", primaryKeyId); + dataMedicineMapper.updateStatus(primaryKeyId, DcmDataStateEnum.AUTO_ANNOTATION_COMPLETE_STATE.getCode()); + dcmDataMedicineStateMachine.setMemoryDataMedicineState(dcmDataMedicineStateMachine.getAutoAnnotationCompleteDcmState()); + LogUtil.debug(LogEnum.STATE_MACHINE, " 【自动标注中】 执行事件后内存状态机的切换: {}", dcmDataMedicineStateMachine.getMemoryDataMedicineState()); + } + +} \ No newline at end of file diff --git a/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/state/specific/datamedicine/NotAnnotationDcmState.java b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/state/specific/datamedicine/NotAnnotationDcmState.java new file mode 100644 index 0000000..4499a2b --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/state/specific/datamedicine/NotAnnotationDcmState.java @@ -0,0 +1,85 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.dcm.machine.state.specific.datamedicine; + +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.dubhe.dcm.dao.DataMedicineMapper; +import org.dubhe.dcm.domain.entity.DataMedicine; +import org.dubhe.dcm.machine.enums.DcmDataStateEnum; +import org.dubhe.dcm.machine.state.AbstractDataMedicineState; +import org.dubhe.dcm.machine.statemachine.DcmDataMedicineStateMachine; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Lazy; +import org.springframework.stereotype.Component; + +/** + * @description 未标注状态类 + * @date 2020-08-27 + */ +@Component +public class NotAnnotationDcmState extends AbstractDataMedicineState { + + @Autowired + @Lazy + private DcmDataMedicineStateMachine dcmDataMedicineStateMachine; + + @Autowired + private DataMedicineMapper dataMedicineMapper; + + /** + * 数据集 未标注-->标注-->标注中 + * + * @param medical 医学数据集对象 + */ + @Override + public void annotationSaveEvent(DataMedicine medical) { + LogUtil.debug(LogEnum.STATE_MACHINE, " 【未标注】 执行事件前内存中状态机的状态 :{} ", dcmDataMedicineStateMachine.getMemoryDataMedicineState()); + LogUtil.debug(LogEnum.STATE_MACHINE, " 接受参数: {} ", medical); + dataMedicineMapper.updateStatus(medical.getId(), DcmDataStateEnum.ANNOTATION_DATA_STATE.getCode()); + dcmDataMedicineStateMachine.setMemoryDataMedicineState(dcmDataMedicineStateMachine.getAnnotationDataState()); + LogUtil.debug(LogEnum.STATE_MACHINE, " 【未标注】 执行事件后内存状态机的切换: {}", dcmDataMedicineStateMachine.getMemoryDataMedicineState()); + } + /** + * 数据集 未标注-->自动标注-->自动标注中 + * + * @param medical 医学数据集对象 + */ + @Override + public void autoAnnotationSaveEvent(DataMedicine medical) { + LogUtil.debug(LogEnum.STATE_MACHINE, " 【未标注】 执行事件前内存中状态机的状态 :{} ", dcmDataMedicineStateMachine.getMemoryDataMedicineState()); + LogUtil.debug(LogEnum.STATE_MACHINE, " 接受参数: {} ", medical); + dataMedicineMapper.updateStatus(medical.getId(), DcmDataStateEnum.AUTOMATIC_LABELING_STATE.getCode()); + dcmDataMedicineStateMachine.setMemoryDataMedicineState(dcmDataMedicineStateMachine.getAutomaticLabelingDcmState()); + LogUtil.debug(LogEnum.STATE_MACHINE, " 【未标注】 执行事件后内存状态机的切换: {}", dcmDataMedicineStateMachine.getMemoryDataMedicineState()); + } + + /** + * 数据集 未标注-->完成-->标注完成 + * + * @param medical 医学数据集对象 + */ + @Override + public void annotationCompleteEvent(DataMedicine medical) { + LogUtil.debug(LogEnum.STATE_MACHINE, " 【未标注】 执行事件前内存中状态机的状态 :{} ", dcmDataMedicineStateMachine.getMemoryDataMedicineState()); + LogUtil.debug(LogEnum.STATE_MACHINE, " 接受参数: {} ", medical); + dataMedicineMapper.updateStatus(medical.getId(), DcmDataStateEnum.ANNOTATION_COMPLETE_STATE.getCode()); + dcmDataMedicineStateMachine.setMemoryDataMedicineState(dcmDataMedicineStateMachine.getAnnotationCompleteDcmState()); + LogUtil.debug(LogEnum.STATE_MACHINE, " 【未标注】 执行事件后内存状态机的切换: {}", dcmDataMedicineStateMachine.getMemoryDataMedicineState()); + } + +} \ No newline at end of file diff --git a/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/state/specific/file/AnnotationCompleteDcmFileState.java b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/state/specific/file/AnnotationCompleteDcmFileState.java new file mode 100644 index 0000000..c396f6a --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/state/specific/file/AnnotationCompleteDcmFileState.java @@ -0,0 +1,72 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.dcm.machine.state.specific.file; + +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.dubhe.dcm.dao.DataMedicineFileMapper; +import org.dubhe.dcm.machine.enums.DcmFileStateEnum; +import org.dubhe.dcm.machine.state.AbstractDcmFileState; +import org.dubhe.dcm.machine.statemachine.DcmFileStateMachine; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Lazy; +import org.springframework.stereotype.Component; + +import java.util.List; + + +/** + * @description 标注完成状态类 + * @date 2020-08-27 + */ +@Component +public class AnnotationCompleteDcmFileState extends AbstractDcmFileState { + + @Autowired + @Lazy + private DcmFileStateMachine dcmFileStateMachine; + + @Autowired + private DataMedicineFileMapper dataMedicineFileMapper; + + /** + * 文件事件 标注完成-->保存-->标注中 + * + * @param fileIds 医学数据集文件ID + */ + @Override + public void annotationSaveEvent(List fileIds){ + LogUtil.debug(LogEnum.STATE_MACHINE, " 【标注完成】 执行事件前内存中状态机的状态 :{} ", dcmFileStateMachine.getMemoryFileState()); + LogUtil.debug(LogEnum.STATE_MACHINE, " 接受参数: {} ", fileIds); + dataMedicineFileMapper.updateStatusByIds(fileIds, DcmFileStateEnum.ANNOTATION_FILE_STATE.getCode()); + dcmFileStateMachine.setMemoryFileState(dcmFileStateMachine.getAnnotationFileState()); + LogUtil.debug(LogEnum.STATE_MACHINE, " 【标注完成】 执行事件后内存状态机的切换: {}", dcmFileStateMachine.getMemoryFileState()); + } + + /** + * 文件 标注完成-->标注-->标注完成 + * + * @param fileIds 医学数据集文件ID + */ + @Override + public void annotationCompleteEvent(List fileIds) { + LogUtil.debug(LogEnum.STATE_MACHINE, " 【标注完成】 执行事件前内存中状态机的状态 :{} ", dcmFileStateMachine.getMemoryFileState()); + LogUtil.debug(LogEnum.STATE_MACHINE, " 接受参数: {} ", fileIds); + dcmFileStateMachine.setMemoryFileState(dcmFileStateMachine.getAnnotationCompleteDcmFileState()); + LogUtil.debug(LogEnum.STATE_MACHINE, " 【标注完成】 执行事件后内存状态机的切换: {}", dcmFileStateMachine.getMemoryFileState()); + } +} \ No newline at end of file diff --git a/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/state/specific/file/AnnotationFileState.java b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/state/specific/file/AnnotationFileState.java new file mode 100644 index 0000000..748e246 --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/state/specific/file/AnnotationFileState.java @@ -0,0 +1,87 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.dcm.machine.state.specific.file; + +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.dubhe.dcm.dao.DataMedicineFileMapper; +import org.dubhe.dcm.machine.enums.DcmFileStateEnum; +import org.dubhe.dcm.machine.state.AbstractDcmFileState; +import org.dubhe.dcm.machine.statemachine.DcmFileStateMachine; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Lazy; +import org.springframework.stereotype.Service; + +import java.util.List; + +/** + * @description 标注中 + * @date 2020-11-17 + */ +@Service +public class AnnotationFileState extends AbstractDcmFileState { + + @Autowired + @Lazy + private DcmFileStateMachine dcmFileStateMachine; + + @Autowired + private DataMedicineFileMapper dataMedicineFileMapper; + + /** + * 文件 标注中-->自动标注文件-->自动标注完成 + * + * @param fileIds 文件ID + */ + @Override + public void autoAnnotationEvent(List fileIds) { + LogUtil.debug(LogEnum.STATE_MACHINE, " 【标注中】 执行事件前内存中状态机的状态 :{} ", dcmFileStateMachine.getMemoryFileState()); + LogUtil.debug(LogEnum.STATE_MACHINE, " 接受参数: {} ", fileIds); + dataMedicineFileMapper.updateStatusByIds(fileIds, DcmFileStateEnum.ANNOTATION_COMPLETE_FILE_STATE.getCode()); + dcmFileStateMachine.setMemoryFileState(dcmFileStateMachine.getAnnotationCompleteDcmFileState()); + LogUtil.debug(LogEnum.STATE_MACHINE, " 【标注中】 执行事件后内存状态机的切换: {}", dcmFileStateMachine.getMemoryFileState()); + } + + /** + * 文件事件 标注中-->保存-->标注中 + * + * @param fileIds 医学数据集文件ID + */ + @Override + public void annotationSaveEvent(List fileIds){ + LogUtil.debug(LogEnum.STATE_MACHINE, " 【标注中】 执行事件前内存中状态机的状态 :{} ", dcmFileStateMachine.getMemoryFileState()); + LogUtil.debug(LogEnum.STATE_MACHINE, " 接受参数: {} ", fileIds); + dcmFileStateMachine.setMemoryFileState(dcmFileStateMachine.getAnnotationFileState()); + LogUtil.debug(LogEnum.STATE_MACHINE, " 【标注中】 执行事件后内存状态机的切换: {}", dcmFileStateMachine.getMemoryFileState()); + } + + /** + * 文件 标注中-->标注-->标注完成 + * + * @param fileIds 医学数据集文件ID + */ + @Override + public void annotationCompleteEvent(List fileIds) { + LogUtil.debug(LogEnum.STATE_MACHINE, " 【标注中】 执行事件前内存中状态机的状态 :{} ", dcmFileStateMachine.getMemoryFileState()); + LogUtil.debug(LogEnum.STATE_MACHINE, " 接受参数: {} ", fileIds); + dataMedicineFileMapper.updateStatusByIds(fileIds, DcmFileStateEnum.ANNOTATION_COMPLETE_FILE_STATE.getCode()); + dcmFileStateMachine.setMemoryFileState(dcmFileStateMachine.getAnnotationCompleteDcmFileState()); + LogUtil.debug(LogEnum.STATE_MACHINE, " 【标注中】 执行事件后内存状态机的切换: {}", dcmFileStateMachine.getMemoryFileState()); + } + + +} diff --git a/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/state/specific/file/AutoAnnotationCompleteDcmFileState.java b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/state/specific/file/AutoAnnotationCompleteDcmFileState.java new file mode 100644 index 0000000..6acdf12 --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/state/specific/file/AutoAnnotationCompleteDcmFileState.java @@ -0,0 +1,74 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.dcm.machine.state.specific.file; + +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.dubhe.dcm.dao.DataMedicineFileMapper; +import org.dubhe.dcm.machine.enums.DcmFileStateEnum; +import org.dubhe.dcm.machine.state.AbstractDcmFileState; +import org.dubhe.dcm.machine.statemachine.DcmFileStateMachine; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Lazy; +import org.springframework.stereotype.Component; + +import java.util.List; + + +/** + * @description 自动标注完成 + * @date 2020-08-27 + */ +@Component +public class AutoAnnotationCompleteDcmFileState extends AbstractDcmFileState { + + @Autowired + @Lazy + private DcmFileStateMachine dcmFileStateMachine; + + @Autowired + private DataMedicineFileMapper dataMedicineFileMapper; + + /** + * 文件 自动标注完成-->标注-->标注完成 + * + * @param fileIds 医学数据集文件ID + */ + @Override + public void annotationCompleteEvent(List fileIds) { + LogUtil.debug(LogEnum.STATE_MACHINE, " 【自动标注完成】 执行事件前内存中状态机的状态 :{} ", dcmFileStateMachine.getMemoryFileState()); + LogUtil.debug(LogEnum.STATE_MACHINE, " 接受参数: {} ", fileIds); + dataMedicineFileMapper.updateStatusByIds(fileIds, DcmFileStateEnum.ANNOTATION_COMPLETE_FILE_STATE.getCode()); + dcmFileStateMachine.setMemoryFileState(dcmFileStateMachine.getAnnotationCompleteDcmFileState()); + LogUtil.debug(LogEnum.STATE_MACHINE, " 【自动标注完成】 执行事件后内存状态机的切换: {}", dcmFileStateMachine.getMemoryFileState()); + } + + /** + * 文件事件 自动标注完成-->保存-->标注中 + * + * @param fileIds 医学数据集文件ID + */ + @Override + public void annotationSaveEvent(List fileIds){ + LogUtil.debug(LogEnum.STATE_MACHINE, " 【自动标注完成】 执行事件前内存中状态机的状态 :{} ", dcmFileStateMachine.getMemoryFileState()); + LogUtil.debug(LogEnum.STATE_MACHINE, " 接受参数: {} ", fileIds); + dataMedicineFileMapper.updateStatusByIds(fileIds, DcmFileStateEnum.ANNOTATION_FILE_STATE.getCode()); + dcmFileStateMachine.setMemoryFileState(dcmFileStateMachine.getAnnotationFileState()); + LogUtil.debug(LogEnum.STATE_MACHINE, " 【自动标注完成】 执行事件后内存状态机的切换: {}", dcmFileStateMachine.getMemoryFileState()); + } + +} \ No newline at end of file diff --git a/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/state/specific/file/NotAnnotationDcmFileState.java b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/state/specific/file/NotAnnotationDcmFileState.java new file mode 100644 index 0000000..2f4943b --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/state/specific/file/NotAnnotationDcmFileState.java @@ -0,0 +1,102 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.dcm.machine.state.specific.file; + + +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.dubhe.dcm.dao.DataMedicineFileMapper; +import org.dubhe.dcm.machine.enums.DcmFileStateEnum; +import org.dubhe.dcm.machine.state.AbstractDcmFileState; +import org.dubhe.dcm.machine.statemachine.DcmFileStateMachine; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Lazy; +import org.springframework.stereotype.Component; + +import java.util.List; + + +/** + * @description 未标注状态类 + * @date 2020-08-27 + */ +@Component +public class NotAnnotationDcmFileState extends AbstractDcmFileState { + + @Autowired + @Lazy + private DcmFileStateMachine dcmFileStateMachine; + + @Autowired + private DataMedicineFileMapper dataMedicineFileMapper; + + /** + * 文件事件 未标注-->自动标注文件-->标注中 + * + * @param fileIds 文件ID + */ + @Override + public void annotationEvent(List fileIds) { + LogUtil.debug(LogEnum.STATE_MACHINE, " 【未标注】 执行事件前内存中状态机的状态 :{} ", dcmFileStateMachine.getMemoryFileState()); + LogUtil.debug(LogEnum.STATE_MACHINE, " 接受参数: {} ", fileIds); + dataMedicineFileMapper.updateStatusByIds(fileIds, DcmFileStateEnum.ANNOTATION_FILE_STATE.getCode()); + dcmFileStateMachine.setMemoryFileState(dcmFileStateMachine.getAutoAnnotationCompleteDcmFileState()); + LogUtil.debug(LogEnum.STATE_MACHINE, " 【未标注】 执行事件后内存状态机的切换: {}", dcmFileStateMachine.getMemoryFileState()); + } + /** + * 文件事件 未标注-->自动标注文件-->自动标注完成 + * + * @param fileIds 文件ID + */ + @Override + public void autoAnnotationSaveEvent(List fileIds) { + LogUtil.debug(LogEnum.STATE_MACHINE, " 【未标注】 执行事件前内存中状态机的状态 :{} ", dcmFileStateMachine.getMemoryFileState()); + LogUtil.debug(LogEnum.STATE_MACHINE, " 接受参数: {} ", fileIds); + dataMedicineFileMapper.updateStatusByIds(fileIds, DcmFileStateEnum.AUTO_ANNOTATION_COMPLETE_FILE_STATE.getCode()); + dcmFileStateMachine.setMemoryFileState(dcmFileStateMachine.getAutoAnnotationCompleteDcmFileState()); + LogUtil.debug(LogEnum.STATE_MACHINE, " 【未标注】 执行事件后内存状态机的切换: {}", dcmFileStateMachine.getMemoryFileState()); + } + + /** + * 文件事件 未标注-->保存-->标注中 + * + * @param fileIds 医学数据集文件ID + */ + @Override + public void annotationSaveEvent(List fileIds){ + LogUtil.debug(LogEnum.STATE_MACHINE, " 【未标注】 执行事件前内存中状态机的状态 :{} ", dcmFileStateMachine.getMemoryFileState()); + LogUtil.debug(LogEnum.STATE_MACHINE, " 接受参数: {} ", fileIds); + dataMedicineFileMapper.updateStatusByIds(fileIds, DcmFileStateEnum.ANNOTATION_FILE_STATE.getCode()); + dcmFileStateMachine.setMemoryFileState(dcmFileStateMachine.getAnnotationFileState()); + LogUtil.debug(LogEnum.STATE_MACHINE, " 【未标注】 执行事件后内存状态机的切换: {}", dcmFileStateMachine.getMemoryFileState()); + } + /** + * 文件 未标注-->标注-->标注完成 + * + * @param fileIds 医学数据集文件ID + */ + @Override + public void annotationCompleteEvent(List fileIds) { + LogUtil.debug(LogEnum.STATE_MACHINE, " 【未标注】 执行事件前内存中状态机的状态 :{} ", dcmFileStateMachine.getMemoryFileState()); + LogUtil.debug(LogEnum.STATE_MACHINE, " 接受参数: {} ", fileIds); + dataMedicineFileMapper.updateStatusByIds(fileIds, DcmFileStateEnum.ANNOTATION_COMPLETE_FILE_STATE.getCode()); + dcmFileStateMachine.setMemoryFileState(dcmFileStateMachine.getAnnotationCompleteDcmFileState()); + LogUtil.debug(LogEnum.STATE_MACHINE, " 【未标注】 执行事件后内存状态机的切换: {}", dcmFileStateMachine.getMemoryFileState()); + } + + +} \ No newline at end of file diff --git a/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/statemachine/DcmDataMedicineStateMachine.java b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/statemachine/DcmDataMedicineStateMachine.java new file mode 100644 index 0000000..b1c8d8e --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/statemachine/DcmDataMedicineStateMachine.java @@ -0,0 +1,196 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.dcm.machine.statemachine; + +import lombok.Data; +import org.dubhe.biz.base.utils.SpringContextHolder; +import org.dubhe.biz.statemachine.exception.StateMachineException; +import org.dubhe.data.machine.constant.ErrorMessageConstant; +import org.dubhe.dcm.dao.DataMedicineMapper; +import org.dubhe.dcm.domain.entity.DataMedicine; +import org.dubhe.dcm.machine.enums.DcmDataStateEnum; +import org.dubhe.dcm.machine.state.AbstractDataMedicineState; +import org.dubhe.dcm.machine.state.specific.datamedicine.*; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.io.Serializable; + +/** + * @description 数据状态机 + * @date 2020-08-27 + */ +@Data +@Component +public class DcmDataMedicineStateMachine extends AbstractDataMedicineState implements Serializable { + + /** + * 未标注 + */ + @Autowired + private NotAnnotationDcmState notAnnotationDcmState; + + /** + * 标注中 + */ + @Autowired + private AnnotationDataState annotationDataState; + + /** + * 自动标注中 + */ + @Autowired + private AutomaticLabelingDcmState automaticLabelingDcmState; + + /** + * 自动标注完成 + */ + @Autowired + private AutoAnnotationCompleteDcmState autoAnnotationCompleteDcmState; + + /** + * 标注完成 + */ + @Autowired + private AnnotationCompleteDcmState annotationCompleteDcmState; + + + /** + * 内存中的状态机 + */ + private AbstractDataMedicineState memoryDataMedicineState; + + @Autowired + private DataMedicineMapper dataMedicineMapper; + + + /** + * 初始化状态机的状态 + * + * @param primaryKeyId 业务ID + * @return dataMedicine 状态机实体 + */ + public DataMedicine initMemoryDataState(Long primaryKeyId) { + if (primaryKeyId == null) { + throw new StateMachineException("未找到业务ID"); + } + DataMedicine dataMedicine = dataMedicineMapper.selectById(primaryKeyId); + if (dataMedicine == null || dataMedicine.getStatus() == null) { + throw new StateMachineException("未找到业务数据"); + } + memoryDataMedicineState = SpringContextHolder.getBean(DcmDataStateEnum.getStateMachine(dataMedicine.getStatus())); + return dataMedicine; + } + + /** + * 初始化状态机的状态 + * + * @param medical 医学数据集对象 + * @return dataMedicine 状态机实体 + */ + public DataMedicine initMemoryDataState(DataMedicine medical) { + if (medical == null) { + throw new StateMachineException("医学影像服务状态机参数对象为空"); + } + if (medical.getStatus() == null) { + throw new StateMachineException("未找到业务数据"); + } + memoryDataMedicineState = SpringContextHolder.getBean(DcmDataStateEnum.getStateMachine(medical.getStatus())); + return medical; + } + + /** + * 标注事件 标注中/自动标注完成/完成/未标注-->保存-->标注中 + * + * @param medical 医学数据集对象 + */ + @Override + public void annotationSaveEvent(DataMedicine medical) { + initMemoryDataState(medical); + if (memoryDataMedicineState != notAnnotationDcmState && + memoryDataMedicineState != annotationDataState && + memoryDataMedicineState != autoAnnotationCompleteDcmState && + memoryDataMedicineState != annotationCompleteDcmState + ) { + + throw new StateMachineException(ErrorMessageConstant.DATASET_CHANGE_ERR_MESSAGE); + } + memoryDataMedicineState.annotationSaveEvent(medical); + } + /** + * 标注事件 未标注-->自动标注-->自动标注中 + * + * @param medical 业务对象 + */ + @Override + public void autoAnnotationSaveEvent(DataMedicine medical) { + initMemoryDataState(medical); + if (memoryDataMedicineState != notAnnotationDcmState) { + + throw new StateMachineException(ErrorMessageConstant.DATASET_CHANGE_ERR_MESSAGE); + } + memoryDataMedicineState.autoAnnotationSaveEvent(medical); + } + + /** + * 标注事件 注中/自动标注完成/完成/未标注-->完成-->标注完成 + * + * @param medical 业务对象 + */ + @Override + public void annotationCompleteEvent(DataMedicine medical) { + initMemoryDataState(medical.getId()); + if (memoryDataMedicineState != notAnnotationDcmState && + memoryDataMedicineState != annotationDataState && + memoryDataMedicineState != autoAnnotationCompleteDcmState && + memoryDataMedicineState != annotationCompleteDcmState + ) { + throw new StateMachineException(ErrorMessageConstant.DATASET_CHANGE_ERR_MESSAGE); + } + memoryDataMedicineState.annotationCompleteEvent(medical); + } + + /** + * 标注事件 标注中-->自动标注-->自动标注中 + * + * @param primaryKeyId 业务ID + */ + @Override + public void autoAnnotationEvent(Long primaryKeyId) { + initMemoryDataState(primaryKeyId); + if (memoryDataMedicineState != annotationDataState) { + throw new StateMachineException(ErrorMessageConstant.DATASET_CHANGE_ERR_MESSAGE); + } + memoryDataMedicineState.autoAnnotationEvent(primaryKeyId); + } + + /** + * 标注事件 自动标注中-->自动标注-->自动标注完成 + * + * @param primaryKeyId 业务ID + */ + @Override + public void autoAnnotationCompleteEvent(Long primaryKeyId) { + initMemoryDataState(primaryKeyId); + if (memoryDataMedicineState != automaticLabelingDcmState) { + throw new StateMachineException(ErrorMessageConstant.DATASET_CHANGE_ERR_MESSAGE); + } + memoryDataMedicineState.autoAnnotationCompleteEvent(primaryKeyId); + } + + +} diff --git a/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/statemachine/DcmFileStateMachine.java b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/statemachine/DcmFileStateMachine.java new file mode 100644 index 0000000..b384301 --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/statemachine/DcmFileStateMachine.java @@ -0,0 +1,191 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.dcm.machine.statemachine; + +import lombok.Data; +import org.dubhe.biz.base.constant.MagicNumConstant; +import org.dubhe.biz.base.utils.SpringContextHolder; +import org.dubhe.biz.statemachine.exception.StateMachineException; +import org.dubhe.data.machine.constant.ErrorMessageConstant; +import org.dubhe.dcm.dao.DataMedicineFileMapper; +import org.dubhe.dcm.domain.entity.DataMedicineFile; +import org.dubhe.dcm.machine.enums.DcmFileStateEnum; +import org.dubhe.dcm.machine.state.AbstractDcmFileState; +import org.dubhe.dcm.machine.state.specific.file.AnnotationCompleteDcmFileState; +import org.dubhe.dcm.machine.state.specific.file.AnnotationFileState; +import org.dubhe.dcm.machine.state.specific.file.AutoAnnotationCompleteDcmFileState; +import org.dubhe.dcm.machine.state.specific.file.NotAnnotationDcmFileState; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.util.CollectionUtils; + +import java.io.Serializable; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * @description 文件状态机 + * @date 2020-08-27 + */ +@Data +@Component +public class DcmFileStateMachine extends AbstractDcmFileState implements Serializable { + + @Autowired + private NotAnnotationDcmFileState notAnnotationFileState; + + @Autowired + private AnnotationFileState annotationFileState; + + @Autowired + private AutoAnnotationCompleteDcmFileState autoAnnotationCompleteDcmFileState; + + @Autowired + private AnnotationCompleteDcmFileState annotationCompleteDcmFileState; + + /** + * 内存中的状态机 + */ + private AbstractDcmFileState memoryFileState; + + + @Autowired + private DataMedicineFileMapper dataMedicineFileMapper; + + + /** + * 初始化状态机的状态 + * + * @param fileIds 文件ID列表 + */ + public void initMemoryFileState(List fileIds) { + if (CollectionUtils.isEmpty(fileIds)) { + throw new StateMachineException("未找到文件ID"); + } + List dataMedicineFileList = dataMedicineFileMapper.selectByIds(fileIds); + Map> dataMedicineFileMap = dataMedicineFileList.stream().collect(Collectors.groupingBy(DataMedicineFile::getStatus)); + if (dataMedicineFileMap.size() > MagicNumConstant.ONE) { + throw new StateMachineException(" 文件中存在状态不一致:【" + dataMedicineFileMap.entrySet() + "】"); + } + memoryFileState = SpringContextHolder.getBean(DcmFileStateEnum.getStateMachine(dataMedicineFileList.get(MagicNumConstant.ZERO).getStatus())); + } + + /** + * 初始化状态机的状态 + * + * @param fileIds 文件ID列表 + */ + public Map> getFileStateGroup(List fileIds) { + if (CollectionUtils.isEmpty(fileIds)) { + throw new StateMachineException("未找到文件ID"); + } + List dataMedicineFileList = dataMedicineFileMapper.selectByIds(fileIds); + return dataMedicineFileList.stream().collect(Collectors.groupingBy(DataMedicineFile::getStatus)); + } + + /** + * 文件事件 未标注-->自动标注文件-->标注中 + * + * @param fileIds 文件ID列表 + */ + @Override + public void annotationEvent(List fileIds) { + initMemoryFileState(fileIds); + if (memoryFileState != notAnnotationFileState) { + throw new StateMachineException(ErrorMessageConstant.FILE_CHANGE_ERR_MESSAGE); + } + memoryFileState.annotationEvent(fileIds); + } + + /** + * 文件事件 未标注-->自动标注文件-->标注中 + * + * @param fileIds 文件ID列表 + */ + @Override + public void autoAnnotationSaveEvent(List fileIds) { + initMemoryFileState(fileIds); + if (memoryFileState != notAnnotationFileState) { + throw new StateMachineException(ErrorMessageConstant.FILE_CHANGE_ERR_MESSAGE); + } + memoryFileState.autoAnnotationSaveEvent(fileIds); + } + + /** + * 文件事件 标注中/自动标注完成/完成/未标注-->保存-->标注中 + * + * @param fileIds 医学数据集文件ID + */ + @Override + public void annotationSaveEvent(List fileIds) { + getFileStateGroup(fileIds).keySet().forEach(k -> { + memoryFileState = SpringContextHolder.getBean(DcmFileStateEnum.getStateMachine(k)); + if (memoryFileState != notAnnotationFileState && + memoryFileState != annotationFileState && + memoryFileState != autoAnnotationCompleteDcmFileState && + memoryFileState != annotationCompleteDcmFileState + ) { + throw new StateMachineException(ErrorMessageConstant.FILE_CHANGE_ERR_MESSAGE); + } + }); + getFileStateGroup(fileIds).keySet().forEach(k -> { + memoryFileState = SpringContextHolder.getBean(DcmFileStateEnum.getStateMachine(k)); + memoryFileState.annotationSaveEvent(fileIds); + }); + } + + + /** + * 文件事件 标注中/自动标注完成/完成/未标注-->完成-->标注完成 + * + * @param fileIds 医学数据集文件ID + */ + @Override + public void annotationCompleteEvent(List fileIds) { + getFileStateGroup(fileIds).keySet().forEach(k -> { + memoryFileState = SpringContextHolder.getBean(DcmFileStateEnum.getStateMachine(k)); + if (memoryFileState != notAnnotationFileState && + memoryFileState != annotationFileState && + memoryFileState != autoAnnotationCompleteDcmFileState && + memoryFileState != annotationCompleteDcmFileState + ) { + throw new StateMachineException(ErrorMessageConstant.FILE_CHANGE_ERR_MESSAGE); + } + }); + getFileStateGroup(fileIds).keySet().forEach(k -> { + memoryFileState = SpringContextHolder.getBean(DcmFileStateEnum.getStateMachine(k)); + memoryFileState.annotationCompleteEvent(fileIds); + }); + } + + /** + * 文件事件 标注中-->自动标注文件-->自动标注完成 + * + * @param fileIds 文件ID列表 + */ + @Override + public void autoAnnotationEvent(List fileIds) { + initMemoryFileState(fileIds); + if (memoryFileState != notAnnotationFileState) { + throw new StateMachineException(ErrorMessageConstant.FILE_CHANGE_ERR_MESSAGE); + } + memoryFileState.autoAnnotationEvent(fileIds); + } + + +} diff --git a/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/statemachine/DcmGlobalStateMachine.java b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/statemachine/DcmGlobalStateMachine.java new file mode 100644 index 0000000..6500532 --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/statemachine/DcmGlobalStateMachine.java @@ -0,0 +1,40 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.dcm.machine.statemachine; + +import lombok.Data; +import org.springframework.stereotype.Component; + +/** + * @description 全局状态机 + * @date 2020-08-27 + */ +@Data +@Component +public class DcmGlobalStateMachine { + + /** + * 数据状态机 + */ + private DcmDataMedicineStateMachine dcmDataMedicineStateMachine; + + /** + * 文件状态机 + */ + private DcmFileStateMachine dcmFileStateMachine; + +} diff --git a/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/utils/DcmStateMachineUtil.java b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/utils/DcmStateMachineUtil.java new file mode 100644 index 0000000..ce3c12d --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/machine/utils/DcmStateMachineUtil.java @@ -0,0 +1,49 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.dcm.machine.utils; + + +import org.dubhe.biz.statemachine.dto.StateChangeDTO; +import org.dubhe.dcm.machine.proxy.DcmStateMachineProxy; + +import java.util.List; + +/** + * @description 状态机工具类 业务层注入此类调用代理方法 + * @date 2020-08-27 + */ +public class DcmStateMachineUtil { + + /** + * 执行单个状态机的状态切换 + * + * @param stateChangeDTO 状态切换信息 + */ + public static void stateChange(StateChangeDTO stateChangeDTO) { + DcmStateMachineProxy.proxyExecutionSingleState(stateChangeDTO); + } + + /** + * 执行关联状态机的状态切换 + * + * @param stateChangeDTOList 状态切换信息 + */ + public static void stateChange(List stateChangeDTOList) { + DcmStateMachineProxy.proxyExecutionRelationState(stateChangeDTOList); + } + +} diff --git a/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/rest/DataLesionSliceController.java b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/rest/DataLesionSliceController.java new file mode 100644 index 0000000..d7f24f5 --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/rest/DataLesionSliceController.java @@ -0,0 +1,75 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.dcm.rest; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.dubhe.biz.base.constant.Permissions; +import org.dubhe.biz.base.vo.DataResponseBody; +import org.dubhe.dcm.constant.DcmConstant; +import org.dubhe.dcm.domain.dto.DataLesionSliceCreateDTO; +import org.dubhe.dcm.domain.dto.DataLesionSliceDeleteDTO; +import org.dubhe.dcm.domain.dto.DataLesionSliceUpdateDTO; +import org.dubhe.dcm.service.DataLesionSliceService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +/** + * @description 病灶信息管理 + * @date 2020-12-23 + */ +@Api(tags = "医学数据处理:病灶信息管理") +@RestController +@RequestMapping(DcmConstant.MODULE_URL_PREFIX + "/datasets/medical/lesion") +public class DataLesionSliceController { + + @Autowired + private DataLesionSliceService dataLesionSliceService; + + @ApiOperation(value = "病灶信息保存") + @PostMapping("/{medicalId}") + @PreAuthorize(Permissions.DATA) + public DataResponseBody save(@Validated @RequestBody List dataLesionSliceCreateDTOS + , @PathVariable(name = "medicalId") Long medicineId) { + return new DataResponseBody(dataLesionSliceService.save(dataLesionSliceCreateDTOS,medicineId)); + } + + @ApiOperation(value = "病灶信息查询") + @GetMapping("/{medicalId}") + @PreAuthorize(Permissions.DATA) + public DataResponseBody query(@PathVariable(name = "medicalId") Long medicineId) { + return new DataResponseBody(dataLesionSliceService.get(medicineId)); + } + + @ApiOperation(value = "病灶信息删除") + @DeleteMapping + @PreAuthorize(Permissions.DATA) + public DataResponseBody delete(@Validated @RequestBody DataLesionSliceDeleteDTO dataLesionSliceDeleteDTO) { + return new DataResponseBody(dataLesionSliceService.delete(dataLesionSliceDeleteDTO)); + } + + @ApiOperation(value = "病灶信息修改") + @PutMapping + @PreAuthorize(Permissions.DATA) + public DataResponseBody update(@Validated @RequestBody DataLesionSliceUpdateDTO dataLesionSliceUpdateDTO) { + return new DataResponseBody(dataLesionSliceService.update(dataLesionSliceUpdateDTO)); + } +} diff --git a/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/rest/DataMedicineController.java b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/rest/DataMedicineController.java new file mode 100644 index 0000000..93234ee --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/rest/DataMedicineController.java @@ -0,0 +1,99 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.dcm.rest; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.dubhe.biz.base.constant.Permissions; +import org.dubhe.biz.base.vo.DataResponseBody; +import org.dubhe.dcm.constant.DcmConstant; +import org.dubhe.dcm.domain.dto.*; +import org.dubhe.dcm.service.DataMedicineService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +/** + * @description 医学数据集管理 + * @date 2020-11-11 + */ +@Api(tags = "医学数据处理:医学数据集管理") +@RestController +@RequestMapping(DcmConstant.MODULE_URL_PREFIX + "/datasets/medical") +public class DataMedicineController { + + @Autowired + private DataMedicineService dataMedicineService; + + @ApiOperation(value = "导入医学数据集") + @PostMapping(value = "/files") + @PreAuthorize(Permissions.DATA) + public DataResponseBody importDataMedicine(@Validated @RequestBody DataMedicineImportDTO dataMedicineImportDTO) { + return new DataResponseBody(dataMedicineService.importDataMedicine(dataMedicineImportDTO)); + } + + @ApiOperation(value = "医学数据集创建") + @PostMapping + @PreAuthorize(Permissions.DATA) + public DataResponseBody create(@Validated(DataMedicineCreateDTO.Create.class) @RequestBody DataMedicineCreateDTO dataMedicineCreateDTO) { + return new DataResponseBody(dataMedicineService.create(dataMedicineCreateDTO)); + } + + @ApiOperation(value = "医学数据集查询") + @GetMapping + @PreAuthorize(Permissions.DATA) + public DataResponseBody query(DataMedicineQueryDTO dataMedicineQueryDTO) { + return new DataResponseBody(dataMedicineService.listVO(dataMedicineQueryDTO)); + } + + @ApiOperation(value = "医学数据集删除") + @DeleteMapping + @PreAuthorize(Permissions.DATA) + public DataResponseBody delete(@Validated @RequestBody DataMedicineDeleteDTO dataMedicineDeleteDTO) { + return new DataResponseBody(dataMedicineService.delete(dataMedicineDeleteDTO)); + } + + @ApiOperation(value = "数据集修改") + @PutMapping(value = "/{medicalId}") + @PreAuthorize(Permissions.DATA) + public DataResponseBody update(@PathVariable(name = "medicalId") Long medicineId, + @Validated @RequestBody DataMedcineUpdateDTO dataMedcineUpdateDTO) { + return new DataResponseBody(dataMedicineService.update(dataMedcineUpdateDTO, medicineId)); + } + + @ApiOperation(value = "医学数据集详情") + @GetMapping("/detail/{medicalId}") + @PreAuthorize(Permissions.DATA) + public DataResponseBody get(@PathVariable(name = "medicalId") Long medicalId) { + return new DataResponseBody(dataMedicineService.get(medicalId)); + } + + @ApiOperation(value = "获取完成标注文件") + @GetMapping("/getFinished/{medicalId}") + @PreAuthorize(Permissions.DATA) + public DataResponseBody getFinished(@PathVariable(name = "medicalId") Long medicalId) { + return new DataResponseBody(dataMedicineService.getFinished(medicalId)); + } + + @ApiOperation(value = "获取自动标注文件") + @GetMapping("/getAuto/{medicalId}") + @PreAuthorize(Permissions.DATA) + public DataResponseBody getAuto(@PathVariable(name = "medicalId") Long medicalId) { + return new DataResponseBody(dataMedicineService.getAuto(medicalId)); + } +} diff --git a/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/rest/MedicineAnnotationController.java b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/rest/MedicineAnnotationController.java new file mode 100644 index 0000000..b2ff56d --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/rest/MedicineAnnotationController.java @@ -0,0 +1,69 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.dcm.rest; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.dubhe.biz.base.constant.Permissions; +import org.dubhe.biz.base.vo.DataResponseBody; +import org.dubhe.dcm.constant.DcmConstant; +import org.dubhe.dcm.domain.dto.MedicineAnnotationDTO; +import org.dubhe.dcm.domain.dto.MedicineAutoAnnotationDTO; +import org.dubhe.dcm.service.MedicineAnnotationService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + + +/** + * @description 医学标注管理 + * @date 2020-11-16 + */ +@Api(tags = "医学数据处理:标注") +@RestController +@RequestMapping(DcmConstant.MODULE_URL_PREFIX + "/datasets/medical/annotation") +public class MedicineAnnotationController { + + @Autowired + private MedicineAnnotationService medicalAnnotationService; + + @ApiOperation(value = "医学数据自动标注") + @PostMapping("/auto") + @PreAuthorize(Permissions.DATA) + public DataResponseBody auto(@Validated @RequestBody MedicineAutoAnnotationDTO medicineAutoAnnotationDTO) { + medicalAnnotationService.auto(medicineAutoAnnotationDTO); + return new DataResponseBody(); + } + + @ApiOperation(value = "标注保存") + @PostMapping(value = "/save") + @PreAuthorize(Permissions.DATA) + public DataResponseBody save(@Validated @RequestBody MedicineAnnotationDTO medicineAnnotationDTO) { + return new DataResponseBody(medicalAnnotationService.save(medicineAnnotationDTO)); + } + + @ApiOperation(value = "标注进度") + @GetMapping(value = "/schedule") + @PreAuthorize(Permissions.DATA) + public DataResponseBody schedule(@RequestParam(value = "ids") List ids) { + return new DataResponseBody(medicalAnnotationService.schedule(ids)); + } + +} diff --git a/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/service/DataLesionSliceService.java b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/service/DataLesionSliceService.java new file mode 100644 index 0000000..235918b --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/service/DataLesionSliceService.java @@ -0,0 +1,81 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.dcm.service; + +import org.dubhe.dcm.domain.dto.DataLesionSliceCreateDTO; +import org.dubhe.dcm.domain.dto.DataLesionSliceDeleteDTO; +import org.dubhe.dcm.domain.dto.DataLesionSliceUpdateDTO; +import org.dubhe.dcm.domain.entity.DataLesionSlice; +import org.dubhe.dcm.domain.vo.DataLesionSliceVO; + +import java.util.List; + +/** + * @description 病灶信息文件服务类 + * @date 2020-12-22 + */ +public interface DataLesionSliceService { + + /** + * 保存病灶信息 + * + * @param dataLesionSliceCreateDTOS 病灶层面信息列表 + * @param medicineId 数据集ID + * @return boolean 数据是否插入成功 + */ + boolean save(List dataLesionSliceCreateDTOS,Long medicineId); + + /** + * 批量插入病灶信息 + * + * @param dataLesionSliceList 病灶信息list + * @return boolean 数据是否插入成功 + */ + boolean insetDataLesionSliceBatch(List dataLesionSliceList); + + /** + * 获取病灶信息 + * + * @param medicineId 数据集ID + * @return List 病灶信息list + */ + List get(Long medicineId); + + /** + * 删除病灶信息 + * + * @param dataLesionSliceDeleteDTO 病灶信息删除DTO + * @return boolean 是否删除成功 + */ + boolean delete(DataLesionSliceDeleteDTO dataLesionSliceDeleteDTO); + + /** + * 修改病灶信息 + * + * @param dataLesionSliceUpdateDTO 病灶信息更新DTO + * @return boolean 是否修改成功 + */ + boolean update(DataLesionSliceUpdateDTO dataLesionSliceUpdateDTO); + + /** + * 保存时根据数据集Id清空病灶信息 + * + * @param medicineId 数据集ID + * @return boolean 是否删除成功 + */ + boolean deleteByMedicineId(Long medicineId); +} diff --git a/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/service/DataMedicineFileService.java b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/service/DataMedicineFileService.java new file mode 100644 index 0000000..7cecf21 --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/service/DataMedicineFileService.java @@ -0,0 +1,87 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.dcm.service; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import org.dubhe.dcm.domain.dto.DataMedicineFileCreateDTO; +import org.dubhe.dcm.domain.entity.DataMedicine; +import org.dubhe.dcm.domain.entity.DataMedicineFile; + +import java.util.List; + +/** + * @description 医学数据集文件服务类 + * @date 2020-11-12 + */ +public interface DataMedicineFileService { + + /** + * 根据条件获取医学文件数量 + * + * @param queryWrapper 医学文件查询条件 + * @return 医学文件数量 + */ + Integer getCountByMedicineId(QueryWrapper queryWrapper); + + /** + * 插入医学数据集相关文件数据 + * + * @param dataMedicineFileList 文件路径 + * @param dataMedicine 医学数据集 + */ + void save(List dataMedicineFileList, DataMedicine dataMedicine); + + /** + * 获取医学文件列表 + * + * @param wrapper 查询条件 + * @return + */ + List listFile(QueryWrapper wrapper); + + + /** + * 补充文件详情后进行排序 + * + * @param dataMedicineFiles 医学文件列表 + * @param medicineId 医学数据集ID + * @return List 排序后的医学文件列表 + */ + List insertInstanceAndSort(List dataMedicineFiles,Long medicineId); + + /** + * 更新修改人ID + * + * @param medicineId 医学数据集id + */ + void updateUserIdByMedicineId(Long medicineId); + + /** + * 根据医学数据集Id修改文件状态 + * + * @param id 医学数据集Id + * @param deleteFlag 删除标识 + */ + void updateStatusById(Long id, Boolean deleteFlag); + + /** + * 根据医学数据集Id删除数据 + * + * @param datasetId 医学数据集Id + */ + void deleteByDatasetId(Long datasetId); +} diff --git a/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/service/DataMedicineService.java b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/service/DataMedicineService.java new file mode 100644 index 0000000..411abbd --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/service/DataMedicineService.java @@ -0,0 +1,149 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.dcm.service; + + +import com.alibaba.fastjson.JSONObject; +import org.dubhe.biz.base.enums.OperationTypeEnum; +import org.dubhe.dcm.domain.dto.*; +import org.dubhe.dcm.domain.entity.DataMedicine; +import org.dubhe.dcm.domain.vo.DataMedicineCompleteAnnotationVO; +import org.dubhe.dcm.domain.vo.DataMedicineVO; +import org.dubhe.recycle.domain.dto.RecycleCreateDTO; + +import java.util.Map; + +/** + * @description 医学数据集服务类 + * @date 2020-11-11 + */ +public interface DataMedicineService { + + + /** + * 根据医学数据集ID获取数据集 + * + * @param medicineId 医学数据集ID + * @return 医学数据集实体 + */ + DataMedicine getDataMedicineById(Long medicineId); + + /** + * 导入医学数据集 + * + * @param dataMedicineImportDTO 导入医学数据集参数 + * @return boolean 导入是否成功 + */ + boolean importDataMedicine(DataMedicineImportDTO dataMedicineImportDTO); + + /** + * 创建医学数据集 + * + * @param dataMedicineCreateDTO 创建医学数据集参数 + * @return Long 医学数据集ID + */ + Long create(DataMedicineCreateDTO dataMedicineCreateDTO); + + /** + * 更新医学数据集 + * + * @param dataMedicine 医学数据集 + */ + void updateByMedicineId(DataMedicine dataMedicine); + + /** + * 删除数据集 + * + * @param dataMedicineDeleteDTO 删除数据集参数 + * @return boolean 是否删除成功 + */ + boolean delete(DataMedicineDeleteDTO dataMedicineDeleteDTO); + + /** + * 医学数据集查询 + * + * @param dataMedicineQueryDTO 查询条件 + * @return MapMap 查询出对应的数据集 + */ + Map listVO(DataMedicineQueryDTO dataMedicineQueryDTO); + + /** + * 医学数据集详情 + * + * @param medicalId 医学数据集ID + * @return DataMedicineVO 医学数据集VO + */ + DataMedicineVO get(Long medicalId); + + /** + * 根据医学数据集Id获取完成标注文件 + * + * @param medicalId 医学数据集ID + * @return JSONObject 标注文件 + */ + JSONObject getFinished(Long medicalId); + + /** + * 根据医学数据集Id获取自动标注文件 + * + * @param medicalId 医学数据集ID + * @return DataMedicineCompleteAnnotationVO 标注文件 + */ + DataMedicineCompleteAnnotationVO getAuto(Long medicalId); + + /** + * 根据医学数据集Id修改数据集 + * + * @param dataMedcineUpdateDTO 医学数据集修改DTO + * @param medicineId 医学数据集Id + * @return boolean 修改是否成功 + */ + boolean update(DataMedcineUpdateDTO dataMedcineUpdateDTO, Long medicineId); + + /** + * 检测是否为公共数据集 + * + * @param id 数据集ID + * @param type 校验类型 + * @return Boolean 更新结果 + */ + Boolean checkPublic(Long id, OperationTypeEnum type); + + /** + * 检测是否为公共数据集 + * + * @param dataMedicine 数据集 + * @param type 操作类型枚举 + * @return Boolean 更新结果 + */ + Boolean checkPublic(DataMedicine dataMedicine, OperationTypeEnum type); + + /** + * 数据集还原 + * + * @param dto 数据清理参数 + */ + void allRollback(RecycleCreateDTO dto); + + + /** + * 根据医学数据集Id删除数据 + * + * @param datasetId 医学数据集Id + */ + void deleteByDatasetId(Long datasetId); +} diff --git a/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/service/MedicineAnnotationService.java b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/service/MedicineAnnotationService.java new file mode 100644 index 0000000..84c7a5e --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/service/MedicineAnnotationService.java @@ -0,0 +1,71 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.dcm.service; + + +import org.dubhe.dcm.domain.dto.MedicineAnnotationDTO; +import org.dubhe.dcm.domain.dto.MedicineAutoAnnotationDTO; +import org.dubhe.dcm.domain.entity.DataMedicineFile; +import org.dubhe.dcm.domain.vo.ScheduleVO; + +import java.util.List; +import java.util.Map; + +/** + * @description 医学标注服务 + * @date 2020-11-16 + */ +public interface MedicineAnnotationService { + + /** + * 医学自动标注 + * + * @param medicineAutoAnnotationDTO 医学自动标注DTO + */ + void auto(MedicineAutoAnnotationDTO medicineAutoAnnotationDTO); + + /** + * 医学自动标注完成 + * + * @return boolean 是否有任务 + */ + boolean finishAuto(); + + /** + * 标注保存 + * + * @param medicineAnnotationDTO 医学标注DTO + * @return 保存是否成功 + */ + boolean save(MedicineAnnotationDTO medicineAnnotationDTO); + + /** + * 查询数据集标注的进度 + * + * @param ids 要查询的数据集ID + * @return 进度 + */ + Map schedule(List ids); + + /** + * 合并自动标注后的JSON文件 + * + * @param medicineId 医学数据集ID + * @param dataMedicineFiles 医学数据集文件列表 + */ + void mergeAnnotation(Long medicineId, List dataMedicineFiles); +} diff --git a/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/service/impl/DataLesionSliceServiceImpl.java b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/service/impl/DataLesionSliceServiceImpl.java new file mode 100644 index 0000000..2542389 --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/service/impl/DataLesionSliceServiceImpl.java @@ -0,0 +1,163 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.dcm.service.impl; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import org.dubhe.biz.permission.annotation.DataPermissionMethod; +import org.dubhe.biz.base.enums.DatasetTypeEnum; +import org.dubhe.cloud.authconfig.utils.JwtUtils; +import org.dubhe.dcm.dao.DataLesionSliceMapper; +import org.dubhe.dcm.domain.dto.DataLesionSliceCreateDTO; +import org.dubhe.dcm.domain.dto.DataLesionSliceDeleteDTO; +import org.dubhe.dcm.domain.dto.DataLesionSliceUpdateDTO; +import org.dubhe.dcm.domain.entity.DataLesionSlice; +import org.dubhe.dcm.domain.vo.DataLesionSliceVO; +import org.dubhe.dcm.service.DataLesionSliceService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.CollectionUtils; + +import java.util.ArrayList; +import java.util.List; + + + +/** + * @description 病灶信息服务实现类 + * @date 2020-12-22 + */ +@Service +public class DataLesionSliceServiceImpl extends ServiceImpl implements DataLesionSliceService { + + @Autowired + private DataLesionSliceMapper dataLesionSliceMapper; + + @Override + public boolean save(List dataLesionSliceCreateDTOS, Long medicineId) { + if (!CollectionUtils.isEmpty(dataLesionSliceCreateDTOS)) { + deleteByMedicineId(medicineId); + List dataLesionSliceList = new ArrayList<>(); + dataLesionSliceCreateDTOS.forEach(dataLesionSliceCreateDTO -> { + JSONArray jsonArray = new JSONArray(); + dataLesionSliceCreateDTO.getList().forEach(dataLesionDrawInfoDTO -> { + JSONObject jsonObject = new JSONObject(); + jsonObject.put("drawId", dataLesionDrawInfoDTO.getDrawId()); + jsonObject.put("sliceNumber", dataLesionDrawInfoDTO.getSliceNumber()); + jsonArray.add(jsonObject); + }); + DataLesionSlice dataLesionSlice = new DataLesionSlice(dataLesionSliceCreateDTO.getLesionOrder() + , dataLesionSliceCreateDTO.getSliceDesc(), medicineId, jsonArray.toJSONString(), JwtUtils.getCurUserId()); + dataLesionSliceList.add(dataLesionSlice); + }); + insetDataLesionSliceBatch(dataLesionSliceList); + } else { + deleteByMedicineId(medicineId); + } + return true; + } + + /** + * 批量插入病灶信息 + * + * @param dataLesionSliceList 病灶信息list + * @return boolean 数据是否插入成功 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public boolean insetDataLesionSliceBatch(List dataLesionSliceList) { + return saveBatch(dataLesionSliceList, dataLesionSliceList.size()); + } + + + /** + * 获取病灶信息 + * + * @param medicineId 数据集ID + * @return List 病灶信息list + */ + @Override + @DataPermissionMethod(dataType = DatasetTypeEnum.PUBLIC) + public List get(Long medicineId) { + QueryWrapper dataLesionSliceQueryWrapper = new QueryWrapper<>(); + dataLesionSliceQueryWrapper.lambda().eq(DataLesionSlice::getMedicineId, medicineId); + List dataLesionSlices = baseMapper.selectList(dataLesionSliceQueryWrapper); + List dataLesionSliceVOS = new ArrayList<>(); + dataLesionSlices.forEach(dataLesionSlice -> { + DataLesionSliceVO dataLesionSliceVO = new DataLesionSliceVO(); + dataLesionSliceVO.setId(dataLesionSlice.getId()); + dataLesionSliceVO.setLesionOrder(dataLesionSlice.getLesionOrder()); + dataLesionSliceVO.setSliceDesc(dataLesionSlice.getSliceDesc()); + dataLesionSliceVO.setList(dataLesionSlice.getDrawInfo()); + dataLesionSliceVOS.add(dataLesionSliceVO); + }); + return dataLesionSliceVOS; + } + + /** + * 删除病灶信息 + * + * @param dataLesionSliceDeleteDTO 病灶信息删除DTO + * @return boolean 是否删除成功 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public boolean delete(DataLesionSliceDeleteDTO dataLesionSliceDeleteDTO) { + dataLesionSliceMapper.deleteByMedicineIdAndOrder(dataLesionSliceDeleteDTO.getId()); + return true; + } + + /** + * 修改病灶信息 + * + * @param dataLesionSliceUpdateDTO 病灶信息更新DTO + * @return boolean 是否修改成功 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public boolean update(DataLesionSliceUpdateDTO dataLesionSliceUpdateDTO) { + DataLesionSlice dataLesionSlice = baseMapper.selectById(dataLesionSliceUpdateDTO.getId()); + dataLesionSlice.setLesionOrder(dataLesionSliceUpdateDTO.getLesionOrder()); + dataLesionSlice.setSliceDesc(dataLesionSliceUpdateDTO.getSliceDesc()); + JSONArray jsonArray = new JSONArray(); + dataLesionSliceUpdateDTO.getList().forEach(dataLesionDrawInfoDTO -> { + JSONObject jsonObject = new JSONObject(); + jsonObject.put("drawId", dataLesionDrawInfoDTO.getDrawId()); + jsonObject.put("sliceNumber", dataLesionDrawInfoDTO.getSliceNumber()); + jsonArray.add(jsonObject); + }); + dataLesionSlice.setDrawInfo(jsonArray.toJSONString()); + baseMapper.updateById(dataLesionSlice); + return true; + } + + /** + * 保存时根据数据集Id清空病灶信息 + * + * @param medicineId 数据集ID + * @return boolean 是否删除成功 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public boolean deleteByMedicineId(Long medicineId) { + dataLesionSliceMapper.deleteByMedicineId(medicineId); + return true; + } +} diff --git a/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/service/impl/DataMedicineFileServiceImpl.java b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/service/impl/DataMedicineFileServiceImpl.java new file mode 100644 index 0000000..26ab532 --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/service/impl/DataMedicineFileServiceImpl.java @@ -0,0 +1,202 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.dcm.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import org.apache.commons.lang3.StringUtils; +import org.dcm4che3.data.Attributes; +import org.dcm4che3.data.Tag; +import org.dcm4che3.io.DicomInputStream; +import org.dubhe.biz.base.constant.MagicNumConstant; +import org.dubhe.biz.file.utils.MinioUtil; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.dubhe.cloud.authconfig.utils.JwtUtils; +import org.dubhe.data.machine.constant.DataStateCodeConstant; +import org.dubhe.dcm.constant.DcmConstant; +import org.dubhe.dcm.dao.DataMedicineFileMapper; +import org.dubhe.dcm.domain.dto.DataMedicineFileCreateDTO; +import org.dubhe.dcm.domain.entity.DataMedicine; +import org.dubhe.dcm.domain.entity.DataMedicineFile; +import org.dubhe.dcm.service.DataMedicineFileService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.atomic.AtomicBoolean; + + +/** + * @description 医学数据集文件服务实现类 + * @date 2020-11-12 + */ +@Service +public class DataMedicineFileServiceImpl extends ServiceImpl implements DataMedicineFileService { + + @Autowired + private MinioUtil minioUtil; + + @Value("${minio.bucketName}") + private String bucketName; + + /** + * 插入医学数据集相关文件数据 + * + * @param dataMedicineFileCreateDTO 文件路径 + * @param dataMedicine 医学数据集 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public void save(List dataMedicineFileCreateDTO, DataMedicine dataMedicine) { + List dataMedicineFiles = new ArrayList<>(); + for (DataMedicineFileCreateDTO dataMedicineFileCreate : dataMedicineFileCreateDTO) { + DataMedicineFile dataMedicineFile = new DataMedicineFile(); + String urlname = dataMedicineFileCreate.getUrl().substring(dataMedicineFileCreate.getUrl().lastIndexOf(DcmConstant.DCM_FILE_SEPARATOR) + MagicNumConstant.ONE); + String name = urlname.substring(MagicNumConstant.ZERO, urlname.indexOf(".")); + dataMedicineFile.setName(name); + dataMedicineFile.setStatus(DataStateCodeConstant.NOT_ANNOTATION_STATE); + dataMedicineFile.setMedicineId(dataMedicine.getId()); + dataMedicineFile.setUrl(dataMedicineFileCreate.getUrl()); + dataMedicineFile.setOriginUserId(dataMedicine.getCreateUserId()); + dataMedicineFile.setCreateUserId(dataMedicine.getCreateUserId()); + dataMedicineFile.setUpdateUserId(dataMedicine.getCreateUserId()); + dataMedicineFile.setSopInstanceUid(dataMedicineFileCreate.getSOPInstanceUID()); + dataMedicineFiles.add(dataMedicineFile); + } + baseMapper.saveBatch(dataMedicineFiles); + } + + /** + * 获取医学文件列表 + * + * @param wrapper 查询条件 + * @return List 医学文件列表 + */ + @Override + public List listFile(QueryWrapper wrapper) { + return list(wrapper); + } + + + /** + * 获取医学数据集文件数量 + * + * @param queryWrapper + * @return Integer 医学数据集文件数量 + */ + @Override + public Integer getCountByMedicineId(QueryWrapper queryWrapper) { + return baseMapper.selectCount(queryWrapper); + } + + /** + * 补充文件详情后进行排序 + * + * @param dataMedicineFiles 医学文件列表 + * @param medicineId 医学数据集ID + * @return List 排序后的医学文件列表 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public List insertInstanceAndSort(List dataMedicineFiles, Long medicineId) { + AtomicBoolean positionFlag = new AtomicBoolean(false); + dataMedicineFiles.forEach(dataMedicineFile -> { + Attributes attributes = null; + DicomInputStream dicomInputStream = null; + InputStream inputStream = null; + String targetPath = StringUtils.substringAfter(dataMedicineFile.getUrl(), "/"); + try { + inputStream = minioUtil.getObjectInputStream(bucketName, targetPath); + dicomInputStream = new DicomInputStream(inputStream); + attributes = dicomInputStream.readDataset(-1, -1); + int instanceNumber = Integer.parseInt(attributes.getString(Tag.InstanceNumber)); + String sopInstanceUid = attributes.getString(Tag.SOPInstanceUID); + if (attributes.getString(Tag.ImagePositionPatient) != null) { + String imagePositionPatientString = attributes.getString(Tag.ImagePositionPatient, 2); + double imagePositionPatient = Double.parseDouble(imagePositionPatientString); + dataMedicineFile.setImagePositionPatient(imagePositionPatient); + positionFlag.set(true); + } + dataMedicineFile.setInstanceNumber(instanceNumber); + dataMedicineFile.setSopInstanceUid(sopInstanceUid); + baseMapper.updateById(dataMedicineFile); + } catch (Exception e) { + LogUtil.error(LogEnum.BIZ_DATASET, "get dicomInputStream failed, {}", e); + } finally { + try { + if(!Objects.isNull(dicomInputStream)){ + dicomInputStream.close(); + } + if(!Objects.isNull(inputStream)){ + inputStream.close(); + } + } catch (IOException e) { + LogUtil.error(LogEnum.BIZ_DATASET, "close inputStream failed, {}", e); + } + } + }); + QueryWrapper wrapper = new QueryWrapper<>(); + if (positionFlag.get()) { + wrapper.lambda().eq(DataMedicineFile::getMedicineId, medicineId) + .orderByAsc(DataMedicineFile::getImagePositionPatient); + } else { + wrapper.lambda().eq(DataMedicineFile::getMedicineId, medicineId) + .orderByAsc(DataMedicineFile::getInstanceNumber); + } + return listFile(wrapper); + } + + /** + * 更新修改人ID + * + * @param medicineId 医学数据集id + */ + @Override + public void updateUserIdByMedicineId(Long medicineId) { + baseMapper.updateUserIdByMedicineId(medicineId,JwtUtils.getCurUserId()); + } + + /** + * 根据医学数据集Id删除文件 + * + * @param id 医学数据集Id + * @param deleteFlag 删除标识 + */ + @Override + public void updateStatusById(Long id, Boolean deleteFlag) { + baseMapper.updateStatusById(id,deleteFlag); + } + + /** + * 根据医学数据集Id删除数据 + * + * @param datasetId 医学数据集Id + */ + @Override + public void deleteByDatasetId(Long datasetId) { + baseMapper.deleteByDatasetId(datasetId); + } + + +} diff --git a/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/service/impl/DataMedicineServiceImpl.java b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/service/impl/DataMedicineServiceImpl.java new file mode 100644 index 0000000..3a5ce1f --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/service/impl/DataMedicineServiceImpl.java @@ -0,0 +1,537 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.dcm.service.impl; + +import cn.hutool.core.collection.CollectionUtil; +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import org.dubhe.biz.permission.annotation.DataPermissionMethod; +import org.dubhe.biz.base.constant.MagicNumConstant; +import org.dubhe.biz.base.constant.NumberConstant; +import org.dubhe.biz.base.context.DataContext; +import org.dubhe.biz.base.dto.CommonPermissionDataDTO; +import org.dubhe.biz.base.enums.DatasetTypeEnum; +import org.dubhe.biz.base.enums.OperationTypeEnum; +import org.dubhe.biz.base.exception.BusinessException; +import org.dubhe.biz.base.utils.StringUtils; +import org.dubhe.biz.permission.base.BaseService; +import org.dubhe.biz.db.utils.PageUtil; +import org.dubhe.biz.db.utils.WrapperHelp; +import org.dubhe.biz.file.utils.MinioUtil; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.dubhe.cloud.authconfig.utils.JwtUtils; +import org.dubhe.data.constant.ErrorEnum; +import org.dubhe.data.machine.constant.DataStateCodeConstant; +import org.dubhe.dcm.constant.DcmConstant; +import org.dubhe.dcm.dao.DataMedicineMapper; +import org.dubhe.dcm.domain.dto.*; +import org.dubhe.dcm.domain.entity.DataMedicine; +import org.dubhe.dcm.domain.vo.DataMedicineCompleteAnnotationVO; +import org.dubhe.dcm.domain.vo.DataMedicineVO; +import org.dubhe.dcm.service.DataMedicineFileService; +import org.dubhe.dcm.service.DataMedicineService; +import org.dubhe.recycle.domain.dto.RecycleCreateDTO; +import org.dubhe.recycle.domain.dto.RecycleDetailCreateDTO; +import org.dubhe.recycle.enums.RecycleModuleEnum; +import org.dubhe.recycle.enums.RecycleResourceEnum; +import org.dubhe.recycle.enums.RecycleTypeEnum; +import org.dubhe.recycle.service.RecycleService; +import org.dubhe.recycle.utils.RecycleTool; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.dao.DuplicateKeyException; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.CollectionUtils; + +import java.io.File; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.stream.Collectors; + +import static org.dubhe.data.constant.ErrorEnum.DATASET_PUBLIC_LIMIT_ERROR; + + +/** + * @description 医学数据集服务实现类 + * @date 2020-11-11 + */ +@Service +public class DataMedicineServiceImpl extends ServiceImpl implements DataMedicineService { + + /** + * 医学数据集文件服务 + */ + @Autowired + private DataMedicineFileService dataMedicineFileService; + + @Autowired + private DataMedicineMapper dataMedicineMapper; + + /** + * 数据回收服务 + */ + @Autowired + private RecycleService recycleService; + + @Autowired + private MinioUtil minioUtil; + + @Value("${minio.bucketName}") + private String bucketName; + + /** + * 路径名前缀 + */ + @Value("${storage.file-store-root-path:/nfs/}") + private String prefixPath; + + /** + * dcm服务器地址 + */ + @Value("${dcm.host}") + private String dcmHost; + + /** + * dcm服务端口 + */ + @Value("${dcm.port}") + private String dcmPort; + + /** + * nfs服务器地址 + */ + @Value("${storage.file-store}") + private String nfsHost; + + /** + * 文件服务器账号地址 需要免密 + */ + @Value("${data.server.userName}") + private String dataServerUserName; + + /** + * 获取DataMedicine中所有属性 + */ + private final Field[] fields = DataMedicine.class.getDeclaredFields(); + + /** + * 医学自动标注 + * + * @param medicineId 医学数据集ID + */ + + @Override + public DataMedicine getDataMedicineById(Long medicineId) { + return getById(medicineId); + } + + /** + * 检测是否为公共数据集 + * + * @param id 数据集id + * @return Boolean 是否为公共数据集 + */ + @Override + public Boolean checkPublic(Long id, OperationTypeEnum type) { + DataMedicine dataMedicine = baseMapper.selectById(id); + return checkPublic(dataMedicine, type); + } + + /** + * 检测是否为公共数据集 + * + * @param dataMedicine 数据集 + */ + @Override + public Boolean checkPublic(DataMedicine dataMedicine, OperationTypeEnum type) { + if (Objects.isNull(dataMedicine)) { + return false; + } + if (DatasetTypeEnum.PUBLIC.getValue().equals(dataMedicine.getType())) { + //操作类型校验公共数据集 + if (OperationTypeEnum.UPDATE.equals(type)) { + BaseService.checkAdminPermission(); + //操作类型校验公共数据集 + } else if (OperationTypeEnum.LIMIT.equals(type)) { + throw new BusinessException(DATASET_PUBLIC_LIMIT_ERROR); + } else { + return true; + } + + } + return false; + } + + + /** + * 数据还原 + * + * @param dto 数据清理参数 + */ + @Override + public void allRollback(RecycleCreateDTO dto) { + List detailList = dto.getDetailList(); + if (CollectionUtil.isNotEmpty(detailList)) { + for (RecycleDetailCreateDTO recycleDetailCreateDTO : detailList) { + if (!Objects.isNull(recycleDetailCreateDTO) && + RecycleTypeEnum.TABLE_DATA.getCode().compareTo(recycleDetailCreateDTO.getRecycleType()) == 0) { + Long datasetId = Long.valueOf(recycleDetailCreateDTO.getRecycleCondition()); + DataMedicine dataMedicine = baseMapper.findDataMedicineByIdAndDeleteIsFalse(datasetId); + DataMedicine dataMedicineBySeriesUid = baseMapper.findDataMedicineBySeriesUid(dataMedicine.getSeriesInstanceUid()); + if(dataMedicineBySeriesUid != null){ + throw new BusinessException(ErrorEnum.MEDICINE_MEDICAL_ALREADY_EXISTS_RESTORE); + } + //还原数据集状态 + baseMapper.updateStatusById(datasetId, false); + //还原数据集文件状态 + dataMedicineFileService.updateStatusById(datasetId, false); + return; + } + } + + } + } + + + /** + * 根据医学数据集Id删除数据 + * + * @param datasetId 医学数据集Id + */ + @Override + public void deleteByDatasetId(Long datasetId) { + baseMapper.deleteByDatasetId(datasetId); + } + + /** + * 导入医学数据集 + * + * @param dataMedicineImportDTO 导入医学数据集参数 + * @return boolean 导入是否成功 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public boolean importDataMedicine(DataMedicineImportDTO dataMedicineImportDTO) { + DataMedicine dataMedicineUpdate = baseMapper.selectById(dataMedicineImportDTO.getId()); + baseMapper.updateById(dataMedicineUpdate); + dataMedicineFileService.save(dataMedicineImportDTO.getDataMedicineFileCreateList(), dataMedicineUpdate); + //上传dcm文件到dcm服务器 + String command = String.format(DcmConstant.DCM_UPLOAD, dataServerUserName, nfsHost, prefixPath, dcmHost, dcmPort, + prefixPath + File.separator + bucketName + File.separator + "dataset" + File.separator + "dcm" + File.separator + dataMedicineImportDTO.getId() + File.separator + "origin"); + try { + Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", command}); + } catch (Exception e) { + LogUtil.error(LogEnum.BIZ_DATASET, "org.dubhe.dcm file upload fail"); + throw new BusinessException("dcm文件上传失败"); + } + return true; + } + + /** + * 创建医学数据集 + * + * @param dataMedicineCreateDTO 创建医学数据集参数 + * @return Long 医学数据集ID + */ + @Override + @Transactional(rollbackFor = Exception.class) + public Long create(DataMedicineCreateDTO dataMedicineCreateDTO) { + Long originUserId = JwtUtils.getCurUserId(); + DataMedicine dataMedicine = dataMedicineMapper.findBySeriesUidAndNotId(dataMedicineCreateDTO.getSeriesInstanceUID(), originUserId); + if (dataMedicine != null) { + throw new BusinessException(ErrorEnum.MEDICINE_MEDICAL_ALREADY_EXISTS); + } + QueryWrapper dataMedicineQueryWrapper = new QueryWrapper<>(); + dataMedicineQueryWrapper.eq("name", dataMedicineCreateDTO.getName()); + int count = baseMapper.selectCount(dataMedicineQueryWrapper); + if (count > MagicNumConstant.ZERO) { + throw new BusinessException(ErrorEnum.MEDICINE_NAME_ERROR); + } + + DataMedicine dataMedicineCreate = DataMedicineCreateDTO.from(dataMedicineCreateDTO, JwtUtils.getCurUserId()); + save(dataMedicineCreate); + return dataMedicineCreate.getId(); + } + + /** + * 更新医学数据集 + * + * @param dataMedicine 医学数据集 + */ + @Override + public void updateByMedicineId(DataMedicine dataMedicine) { + baseMapper.updateById(dataMedicine); + } + + /** + * 删除数据集 + * + * @param dataMedicineDeleteDTO 删除数据集参数 + * @return boolean 是否删除成功 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public boolean delete(DataMedicineDeleteDTO dataMedicineDeleteDTO) { + for (Long id : dataMedicineDeleteDTO.getIds()) { + deleteDataMedicine(id); + } + return true; + } + + /** + * 删除数据集 + * + * @return boolean 是否删除成功 + */ + @Transactional(rollbackFor = Exception.class) + @DataPermissionMethod(dataType = DatasetTypeEnum.PUBLIC) + public boolean deleteDataMedicine(Long id) { + DataMedicine dataMedicine = baseMapper.selectById(id); + if (dataMedicine == null) { + throw new BusinessException(ErrorEnum.DATAMEDICINE_ABSENT); + } + checkPublic(dataMedicine, OperationTypeEnum.UPDATE); + if (dataMedicine.getStatus().equals(DataStateCodeConstant.AUTOMATIC_LABELING_STATE)) { + throw new BusinessException(ErrorEnum.DATAMEDICINE_AUTOMATIC); + } + baseMapper.updateStatusById(id, true); + dataMedicineFileService.updateStatusById(id, true); + addRecycleDataByDeleteDataset(id); + return true; + } + + /** + * 添加医学数据集删除回收数据 + * + * @param id 医学数据集ID + */ + @Transactional(rollbackFor = Exception.class) + public void addRecycleDataByDeleteDataset(Long id) { + //删除MinIO文件 + try { + //落地回收详情数据文件回收信息 + List detailList = new ArrayList<>(); + detailList.add(RecycleDetailCreateDTO.builder() + .recycleCondition(id.toString()) + .recycleType(RecycleTypeEnum.TABLE_DATA.getCode()) + .recycleNote(RecycleTool.generateRecycleNote("落地 数据集DB 数据文件回收", id)) + .build()); + //落地回收详情minio 数据文件回收信息 + detailList.add(RecycleDetailCreateDTO.builder() + .recycleCondition(prefixPath + bucketName + DcmConstant.DCM_FILE_SEPARATOR + DcmConstant.DCM_ANNOTATION_PATH + id) + .recycleType(RecycleTypeEnum.FILE.getCode()) + .recycleNote(RecycleTool.generateRecycleNote("落地 minio 数据文件回收", id)) + .build()); + + //落地回收信息 + RecycleCreateDTO recycleCreateDTO = RecycleCreateDTO.builder() + .recycleModule(RecycleModuleEnum.BIZ_DATAMEDICINE.getValue()) + .recycleCustom(RecycleResourceEnum.DATAMEDICINE_RECYCLE_FILE.getClassName()) + .restoreCustom(RecycleResourceEnum.DATAMEDICINE_RECYCLE_FILE.getClassName()) + .recycleDelayDate(NumberConstant.NUMBER_1) + .recycleNote(RecycleTool.generateRecycleNote("删除医学数据集相关信息", id)) + .detailList(detailList) + .build(); + recycleService.createRecycleTask(recycleCreateDTO); + } catch (Exception e) { + LogUtil.error(LogEnum.BIZ_DATASET, "DataMedicineServiceImpl addRecycleDataByDeleteDataset error {}", e); + } + + } + + /** + * 医学数据集查询 + * + * @param dataMedicineQueryDTO 查询条件 + * @return MapMap 查询出对应的数据集 + */ + @Override + @DataPermissionMethod(dataType = DatasetTypeEnum.PUBLIC) + public Map listVO(DataMedicineQueryDTO dataMedicineQueryDTO) { + if (dataMedicineQueryDTO.getCurrent() == null || dataMedicineQueryDTO.getSize() == null) { + throw new BusinessException(ErrorEnum.PARAM_ERROR); + } + QueryWrapper wrapper = WrapperHelp.getWrapper(dataMedicineQueryDTO); + if (dataMedicineQueryDTO.getAnnotateType() != null) { + if (dataMedicineQueryDTO.getAnnotateType() % MagicNumConstant.ONE_THOUSAND == MagicNumConstant.ZERO) { + wrapper.between("annotate_type", dataMedicineQueryDTO.getAnnotateType() + , dataMedicineQueryDTO.getAnnotateType() + MagicNumConstant.ONE_THOUSAND); + } else { + wrapper.eq("annotate_type", dataMedicineQueryDTO.getAnnotateType()); + } + } + wrapper.eq("deleted", MagicNumConstant.ZERO) + .eq("type", dataMedicineQueryDTO.getType()); + //预置数据集类型校验 + if (!Objects.isNull(dataMedicineQueryDTO.getType()) && dataMedicineQueryDTO.getType().compareTo(DatasetTypeEnum.PUBLIC.getValue()) == 0) { + DataContext.set(CommonPermissionDataDTO.builder().id(null).type(true).build()); + } + if (StringUtils.isNotBlank(dataMedicineQueryDTO.getName())) { + wrapper.lambda().and(w -> + w.eq(DataMedicine::getId, dataMedicineQueryDTO.getName()) + .or() + .like(DataMedicine::getName, dataMedicineQueryDTO.getName()) + ); + } + if (StringUtils.isNotBlank(dataMedicineQueryDTO.getSort())) { + for (Field field : fields) { + if (field.getName().equals(dataMedicineQueryDTO.getSort())) { + field.setAccessible(true); + TableField annotation = field.getAnnotation(TableField.class); + if (annotation == null) { + continue; + } + if ("desc".equals(dataMedicineQueryDTO.getOrder())) { + wrapper.orderByDesc(annotation.value()); + } else if ("asc".equals(dataMedicineQueryDTO.getOrder())) { + wrapper.orderByAsc(annotation.value()); + } + } + } + } else { + wrapper.lambda().orderByDesc(DataMedicine::getUpdateTime); + } + Page pages = new Page() {{ + setCurrent(dataMedicineQueryDTO.getCurrent()); + setSize(dataMedicineQueryDTO.getSize()); + setTotal(baseMapper.selectCount(wrapper)); + List collect = baseMapper.selectList( + wrapper + .last(" limit " + (dataMedicineQueryDTO.getCurrent() - NumberConstant.NUMBER_1) * dataMedicineQueryDTO.getSize() + ", " + dataMedicineQueryDTO.getSize()) + ).stream().map(DataMedicineVO::from).collect(Collectors.toList()); + if (!CollectionUtils.isEmpty(collect)) { + setRecords(collect); + } + }}; + return PageUtil.toPage(pages); + } + + /** + * 医学数据集详情 + * + * @param medicalId 医学数据集ID + * @return DataMedicineVO 医学数据集VO + */ + @Override + @DataPermissionMethod(dataType = DatasetTypeEnum.PUBLIC) + public DataMedicineVO get(Long medicalId) { + DataMedicine dataMedicine = baseMapper.selectById(medicalId); + if (dataMedicine == null) { + throw new BusinessException(ErrorEnum.DATAMEDICINE_ABSENT); + } else if (dataMedicine.getStatus().equals(DataStateCodeConstant.AUTOMATIC_LABELING_STATE)) { + throw new BusinessException(ErrorEnum.DATAMEDICINE_AUTOMATIC); + } + if (checkPublic(medicalId, OperationTypeEnum.SELECT)) { + DataContext.set(CommonPermissionDataDTO.builder().id(medicalId).type(true).build()); + } + DataMedicineVO dataMedicineVO = DataMedicineVO.from(dataMedicine); + return dataMedicineVO; + } + + /** + * 根据医学数据集Id获取完成标注文件 + * + * @param medicalId 医学数据集ID + * @return JSONObject 完成标注文件 + */ + @Override + @DataPermissionMethod(dataType = DatasetTypeEnum.PUBLIC) + public JSONObject getFinished(Long medicalId) { + DataMedicine dataMedicine = baseMapper.selectById(medicalId); + if (dataMedicine == null) { + throw new BusinessException(ErrorEnum.DATAMEDICINE_ABSENT); + } + try { + String finishedFilePath = DcmConstant.DCM_ANNOTATION_PATH + medicalId + DcmConstant.DCM_ANNOTATION; + String annotation = minioUtil.readString(bucketName, finishedFilePath); + JSONObject jsonObject = JSONObject.parseObject(annotation); + return jsonObject; + } catch (Exception e) { + LogUtil.error(LogEnum.BIZ_DATASET, "MinIO read the dataMedicine file error", e); + } + return null; + } + + /** + * 根据医学数据集Id获取自动标注文件 + * + * @param medicalId 医学数据集ID + * @return DataMedicineCompleteAnnotationVO 标注文件 + */ + @Override + @DataPermissionMethod(dataType = DatasetTypeEnum.PUBLIC) + public DataMedicineCompleteAnnotationVO getAuto(Long medicalId) { + DataMedicine dataMedicine = baseMapper.selectById(medicalId); + if (dataMedicine == null) { + throw new BusinessException(ErrorEnum.DATAMEDICINE_ABSENT); + } + DataMedicineCompleteAnnotationVO dataMedicineCompleteAnnotationVO = new DataMedicineCompleteAnnotationVO(); + try { + String autoFilePath = DcmConstant.DCM_ANNOTATION_PATH + medicalId + DcmConstant.DCM_MERGE_ANNOTATION; + String annotation = minioUtil.readString(bucketName, autoFilePath); + JSONObject jsonObject = JSONObject.parseObject(annotation); + dataMedicineCompleteAnnotationVO.setSeriesInstanceUID(jsonObject.getString(DcmConstant.SERIES_INSTABCE_UID)); + dataMedicineCompleteAnnotationVO.setStudyInstanceUID(jsonObject.getString(DcmConstant.STUDY_INSTANCE_UID)); + dataMedicineCompleteAnnotationVO.setAnnotations(jsonObject.getString(DcmConstant.ANNOTATION)); + } catch (Exception e) { + LogUtil.error(LogEnum.BIZ_DATASET, "MinIO read the dataMedicine file error {}", e); + } + return dataMedicineCompleteAnnotationVO; + } + + /** + * 根据医学数据集Id修改数据集 + * + * @param dataMedcineUpdateDTO 医学数据集修改DTO + * @param medicineId 医学数据集Id + * @return boolean 修改是否成功 + */ + @Override + @Transactional(rollbackFor = Exception.class) + @DataPermissionMethod(dataType = DatasetTypeEnum.PUBLIC) + public boolean update(DataMedcineUpdateDTO dataMedcineUpdateDTO, Long medicineId) { + DataMedicine dataMedicine = baseMapper.selectById(medicineId); + if (dataMedicine == null) { + throw new BusinessException(ErrorEnum.DATAMEDICINE_ABSENT); + } + checkPublic(dataMedicine, OperationTypeEnum.UPDATE); + dataMedicine.setName(dataMedcineUpdateDTO.getName()); + dataMedicine.setUpdateUserId(JwtUtils.getCurUserId()); + if (dataMedcineUpdateDTO.getRemark() != null) { + dataMedicine.setRemark(dataMedcineUpdateDTO.getRemark()); + } + + int count; + try { + count = baseMapper.updateById(dataMedicine); + } catch (DuplicateKeyException e) { + throw new BusinessException(ErrorEnum.DATASET_NAME_DUPLICATED_ERROR, null, e); + } + if (count == MagicNumConstant.ZERO) { + throw new BusinessException(ErrorEnum.DATA_ABSENT_OR_NO_AUTH); + } + return true; + } +} diff --git a/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/service/impl/MedicineAnnotationServiceImpl.java b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/service/impl/MedicineAnnotationServiceImpl.java new file mode 100644 index 0000000..ddf494b --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/service/impl/MedicineAnnotationServiceImpl.java @@ -0,0 +1,380 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.dcm.service.impl; + +import cn.hutool.core.util.ObjectUtil; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.commons.lang3.StringUtils; +import org.dubhe.biz.permission.annotation.DataPermissionMethod; +import org.dubhe.biz.base.constant.NumberConstant; +import org.dubhe.biz.base.enums.DatasetTypeEnum; +import org.dubhe.biz.base.enums.OperationTypeEnum; +import org.dubhe.biz.base.exception.BusinessException; +import org.dubhe.biz.file.utils.MinioUtil; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.dubhe.biz.redis.utils.RedisUtils; +import org.dubhe.biz.statemachine.dto.StateChangeDTO; +import org.dubhe.cloud.authconfig.utils.JwtUtils; +import org.dubhe.data.constant.DataTaskTypeEnum; +import org.dubhe.data.constant.ErrorEnum; +import org.dubhe.data.constant.TaskStatusEnum; +import org.dubhe.data.domain.entity.Task; +import org.dubhe.data.machine.constant.DataStateCodeConstant; +import org.dubhe.data.machine.enums.DataStateEnum; +import org.dubhe.data.service.TaskService; +import org.dubhe.dcm.constant.DcmConstant; +import org.dubhe.dcm.dao.DataMedicineFileMapper; +import org.dubhe.dcm.domain.dto.MedicineAnnotationDTO; +import org.dubhe.dcm.domain.dto.MedicineAutoAnnotationDTO; +import org.dubhe.dcm.domain.entity.DataMedicine; +import org.dubhe.dcm.domain.entity.DataMedicineFile; +import org.dubhe.dcm.domain.vo.ScheduleVO; +import org.dubhe.dcm.machine.constant.DcmDataStateMachineConstant; +import org.dubhe.dcm.machine.constant.DcmFileStateCodeConstant; +import org.dubhe.dcm.machine.constant.DcmFileStateMachineConstant; +import org.dubhe.dcm.machine.enums.DcmDataStateEnum; +import org.dubhe.dcm.machine.utils.DcmStateMachineUtil; +import org.dubhe.dcm.service.DataLesionSliceService; +import org.dubhe.dcm.service.DataMedicineFileService; +import org.dubhe.dcm.service.DataMedicineService; +import org.dubhe.dcm.service.MedicineAnnotationService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.CollectionUtils; + +import java.io.IOException; +import java.io.InputStream; +import java.util.*; +import java.util.stream.Collectors; + + +/** + * @description 医学标注服务实现类 + * @date 2020-11-16 + */ +@Service +public class MedicineAnnotationServiceImpl implements MedicineAnnotationService { + + /** + * 任务服务 + */ + @Autowired + private TaskService taskService; + + @Autowired + private DataMedicineFileMapper dataMedicineFileMapper; + + /** + * 医学数据集服务 + */ + @Autowired + private DataMedicineService dataMedicineService; + + /** + * 医学数据集文件服务 + */ + @Autowired + private DataMedicineFileService dataMedicineFileService; + + @Autowired + private MinioUtil minioUtil; + + @Autowired + private RedisUtils redisUtils; + + @Autowired + private DataLesionSliceService dataLesionSliceService; + + /** + * bucketName + */ + @Value("${minio.bucketName}") + private String bucketName; + + + /** + * 医学标注算法处理中任务队列 + */ + private static final String MEDICINE_START_QUEUE = "dcm_processing_queue"; + /** + * 医学标注算法已完成任务队列 + */ + private static final String MEDICINE_FINISHED_QUEUE = "dcm_finished_queue"; + + /** + * 医学自动标注 + * + * @param medicineAutoAnnotationDTO 医学自动标注DTO + */ + @Override + @Transactional(rollbackFor = Exception.class) + @DataPermissionMethod(dataType = DatasetTypeEnum.PUBLIC) + public void auto(MedicineAutoAnnotationDTO medicineAutoAnnotationDTO) { + if (medicineAutoAnnotationDTO.getMedicalId() == null) { + return; + } + dataMedicineService.checkPublic(medicineAutoAnnotationDTO.getMedicalId(), OperationTypeEnum.UPDATE); + Long medicineId = medicineAutoAnnotationDTO.getMedicalId(); + DataMedicine dataMedicine = dataMedicineService.getDataMedicineById(medicineId); + if (!dataMedicine.getStatus().equals(DataStateCodeConstant.NOT_ANNOTATION_STATE)) { + throw new BusinessException(ErrorEnum.MEDICINE_AUTO_DATASET_ERROR); + } + QueryWrapper queryWrapper = new QueryWrapper<>(); + queryWrapper.lambda().eq(DataMedicineFile::getMedicineId, medicineId).eq(DataMedicineFile::getStatus, + DataStateEnum.NOT_ANNOTATION_STATE.getCode()); + Integer medicineFilesCount = dataMedicineFileService.getCountByMedicineId(queryWrapper); + Task task = Task.builder() + .status(TaskStatusEnum.INIT.getValue()) + .datasetId(medicineId) + .total(medicineFilesCount) + .type(DataTaskTypeEnum.MEDICINE_ANNOTATION.getValue()) + .labels("") + .build(); + taskService.createTask(task); + DcmStateMachineUtil.stateChange(new StateChangeDTO() {{ + setObjectParam(new Object[]{dataMedicine}); + setStateMachineType(DcmDataStateMachineConstant.DCM_DATA_STATE_MACHINE); + setEventMethodName(DcmDataStateMachineConstant.AUTO_ANNOTATION_SAVE_EVENT); + }}); + modifyUpdataUserId(medicineAutoAnnotationDTO.getMedicalId()); + } + + /** + * 医学自动标注完成 + * + * @return boolean 是否有任务 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public boolean finishAuto() { + Object object = redisUtils.lpop(MEDICINE_FINISHED_QUEUE); + if (ObjectUtil.isNotNull(object)) { + JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(redisUtils.get(object.toString()))); + String detailId = jsonObject.getString("reTaskId"); + JSONObject jsonDetail = JSON.parseObject(JSON.toJSONString(redisUtils.get(detailId))); + Long taskId = jsonDetail.getLong("taskId"); + JSONArray dcmsArray = jsonDetail.getJSONArray("dcms"); + String[] dcms = dcmsArray.toArray(new String[dcmsArray.size()]); + QueryWrapper taskQueryWrapper = new QueryWrapper<>(); + taskQueryWrapper.lambda().eq(Task::getId, taskId); + Task task = taskService.selectOne(taskQueryWrapper); + List medicineFileIds = JSON.parseObject(jsonDetail.getString("medicineFileIds"), ArrayList.class); + DcmStateMachineUtil.stateChange(new StateChangeDTO() {{ + setObjectParam(new Object[]{medicineFileIds}); + setStateMachineType(DcmFileStateMachineConstant.DCM_FILE_STATE_MACHINE); + setEventMethodName(DcmFileStateMachineConstant.AUTO_ANNOTATION_SAVE_EVENT); + }}); + int finished = task.getFinished() + dcmsArray.size(); + if (task.getFinished() + dcmsArray.size() >= task.getTotal()) { + QueryWrapper wrapper = new QueryWrapper<>(); + wrapper.lambda().eq(DataMedicineFile::getMedicineId, task.getDatasetId()); + List dataMedicineFiles = dataMedicineFileService.listFile(wrapper); + List dataMedicineFilesOrderByAsc = dataMedicineFileService + .insertInstanceAndSort(dataMedicineFiles, task.getDatasetId()); + mergeAnnotation(task.getDatasetId(), dataMedicineFilesOrderByAsc); + DataMedicine dataMedicine = dataMedicineService.getDataMedicineById(task.getDatasetId()); + DcmStateMachineUtil.stateChange(new StateChangeDTO() {{ + setObjectParam(new Object[]{dataMedicine.getId()}); + setStateMachineType(DcmDataStateMachineConstant.DCM_DATA_STATE_MACHINE); + setEventMethodName(DcmDataStateMachineConstant.AUTO_ANNOTATION_COMPLETE_EVENT); + }}); + } + task.setFinished(finished); + taskService.updateByTaskId(task); + } + return ObjectUtil.isNotNull(object); + } + + /** + * 标注保存 + * + * @param medicineAnnotationDTO 医学标注DTO + * @return 保存是否成功 + */ + @Override + @Transactional(rollbackFor = Exception.class) + @DataPermissionMethod(dataType = DatasetTypeEnum.PUBLIC) + public boolean save(MedicineAnnotationDTO medicineAnnotationDTO) { + //判断保存时是否传fileID + if (medicineAnnotationDTO.getType().equals(NumberConstant.NUMBER_0)&&CollectionUtils.isEmpty(medicineAnnotationDTO.getMedicalFiles())){ + return true; + } + //判断是否为空,是否删除,是否是自动标注中状态 + DataMedicine medical = dataMedicineService.getDataMedicineById(medicineAnnotationDTO.getMedicalId()); + if (medical == null || medical.getDeleted()) { + throw new BusinessException(ErrorEnum.DATAMEDICINE_ABSENT); + } else if (DcmDataStateEnum.AUTOMATIC_LABELING_STATE.getCode().equals(medical.getStatus())) { + throw new BusinessException(ErrorEnum.DATAMEDICINE_AUTOMATIC); + } + dataMedicineService.checkPublic(medicineAnnotationDTO.getMedicalId(),OperationTypeEnum.UPDATE); + //保存标注 + try { + minioUtil.writeString(bucketName, DcmConstant.DCM_ANNOTATION_PATH + medical.getId() + DcmConstant.DCM_ANNOTATION, medicineAnnotationDTO.getAnnotations()); + } catch (Exception e) { + LogUtil.error(LogEnum.BIZ_DATASET, "Medicine annotation is failed" + e.getMessage()); + return false; + } + //改变数据集的状态为标注完成或标注中 + DcmStateMachineUtil.stateChange(new StateChangeDTO() {{ + setObjectParam(new Object[]{medical}); + setStateMachineType(DcmDataStateMachineConstant.DCM_DATA_STATE_MACHINE); + setEventMethodName(NumberConstant.NUMBER_1 == medicineAnnotationDTO.getType() ? + DcmDataStateMachineConstant.ANNOTATION_COMPLETE_EVENT : DcmDataStateMachineConstant.ANNOTATION_SAVE_EVENT); + }}); + //改变数据集文件的状态为标注完成或标注中 + DcmStateMachineUtil.stateChange(new StateChangeDTO() {{ + setObjectParam(new Object[]{ + NumberConstant.NUMBER_1 == medicineAnnotationDTO.getType() ? + dataMedicineFileMapper.selectList(new LambdaQueryWrapper() {{ + eq(DataMedicineFile::getMedicineId, medical.getId()); + }}).stream().map(DataMedicineFile::getId).collect(Collectors.toList()) : + dataMedicineFileMapper.selectList(new LambdaQueryWrapper() {{ + in(DataMedicineFile::getSopInstanceUid, medicineAnnotationDTO.getMedicalFiles()); + }}).stream().map(DataMedicineFile::getId).collect(Collectors.toList()) + }); + setStateMachineType(DcmFileStateMachineConstant.DCM_FILE_STATE_MACHINE); + setEventMethodName(NumberConstant.NUMBER_1 == medicineAnnotationDTO.getType() ? + DcmFileStateMachineConstant.ANNOTATION_COMPLETE_EVENT : DcmFileStateMachineConstant.ANNOTATION_SAVE_EVENT); + }}); + modifyUpdataUserId(medicineAnnotationDTO.getMedicalId()); + return true; + } + + /** + * 查询数据集标注的进度 + * + * @param ids 要查询的数据集ID + * @return 进度 + */ + @Override + @DataPermissionMethod(dataType = DatasetTypeEnum.PUBLIC) + public Map schedule(List ids) { + if (ids.isEmpty()) { + throw new BusinessException(ErrorEnum.PARAM_ERROR); + } + List> fileStatusCount = dataMedicineFileMapper.getFileStatusCount(ids); + if (fileStatusCount.isEmpty()){ + return new HashMap(ids.size()) {{ + ids.forEach(v -> { + ScheduleVO scheduleVO = new ScheduleVO(NumberConstant.NUMBER_0, NumberConstant.NUMBER_0, NumberConstant.NUMBER_0, NumberConstant.NUMBER_0); + //初始化进度值 + put(String.valueOf(v), scheduleVO); + }); + + }}; + } + return new HashMap(ids.size()) {{ + ids.forEach(v -> { + ScheduleVO scheduleVO = new ScheduleVO(NumberConstant.NUMBER_0, NumberConstant.NUMBER_0, NumberConstant.NUMBER_0, NumberConstant.NUMBER_0); + //初始化进度值 + put(String.valueOf(v), scheduleVO); + fileStatusCount.forEach(val -> { + if (v.equals(val.get(DcmConstant.MEDICINE_ID)) || v.equals(val.get(DcmConstant.MEDICINE_ID.toLowerCase()))) { + Integer count = Integer.valueOf(val.get(DcmConstant.COUNT).toString()); + Object status = val.get(DcmConstant.STATUS); + if (status.equals(DcmFileStateCodeConstant.NOT_ANNOTATION_FILE_STATE)) { + scheduleVO.setUnfinished(count); + } else if (status.equals(DcmFileStateCodeConstant.ANNOTATION_COMPLETE_FILE_STATE)) { + scheduleVO.setFinished(count); + } else if (status.equals(DcmFileStateCodeConstant.AUTO_ANNOTATION_COMPLETE_FILE_STATE)) { + scheduleVO.setAutoFinished(count); + } else if (status.equals(DcmFileStateCodeConstant.ANNOTATION_FILE_STATE)) { + scheduleVO.setManualAnnotating(count); + } + } + }); + }); + + }}; + } + + /** + * 合并自动标注后的JSON文件 + * + * @param medicineId 医学数据集ID + * @param dataMedicineFiles 医学数据集文件列表 + */ + @Override + public void mergeAnnotation(Long medicineId, List dataMedicineFiles) { + DataMedicine dataMedicine = dataMedicineService.getDataMedicineById(medicineId); + String studyInstanceUID = dataMedicine.getStudyInstanceUid(); + String seriesInstanceUID = dataMedicine.getSeriesInstanceUid(); + JSONObject mergeJSONObject = new JSONObject(); + mergeJSONObject.put("StudyInstanceUID", studyInstanceUID); + mergeJSONObject.put("seriesInstanceUID", seriesInstanceUID); + JSONArray jsonArrayMerge = new JSONArray(); + dataMedicineFiles.forEach(dataMedicineFile -> { + String targrtPath = StringUtils.substringBeforeLast(StringUtils.substringAfter(dataMedicineFile.getUrl(), + "/"), ".").replace("origin", "annotation") + ".json"; + InputStream inputStream = null; + try { + inputStream = minioUtil.getObjectInputStream(bucketName, targrtPath); + ObjectMapper objectMapper = new ObjectMapper(); + JsonNode jsonNode = objectMapper.readTree(inputStream); + Iterator elements = jsonNode.elements(); + JSONArray jsonArray = new JSONArray(); + while (elements.hasNext()) { + JsonNode next = elements.next(); + jsonArray.add(next.get("annotation").toString()); + } + jsonArrayMerge.add(jsonArray); + } catch (Exception e) { + LogUtil.error(LogEnum.BIZ_DATASET, "get medicine annotation json failed, {}", e); + } finally { + try { + inputStream.close(); + } catch (IOException e) { + LogUtil.error(LogEnum.BIZ_DATASET, "close inputStream failed, {}", e); + } + } + }); + JSONObject jsonObjectTemp = new JSONObject(); + jsonObjectTemp.put("annotation", jsonArrayMerge); + String mergePointsString = jsonObjectTemp.getString("annotation").replace("\"", ""); + mergeJSONObject.put("annotation", mergePointsString); + String mergePath = StringUtils.substringBeforeLast(StringUtils.substringAfter(dataMedicineFiles.get(0).getUrl() + , "/"), "/").replace("origin", "annotation") + "/merge_annotation.json"; + try { + minioUtil.writeString(bucketName, mergePath, mergeJSONObject.toJSONString()); + } catch (Exception e) { + LogUtil.error(LogEnum.BIZ_DATASET, "write merge_annotation failed, {}", e); + } + } + + /** + * 修改医学数据集和文件表中的修改人ID + * + * @param medicineId 医学数据集ID + */ + @Transactional(rollbackFor = Exception.class) + public void modifyUpdataUserId(Long medicineId){ + DataMedicine dataMedicine = dataMedicineService.getDataMedicineById(medicineId); + dataMedicine.setUpdateUserId(JwtUtils.getCurUserId()); + dataMedicineService.updateByMedicineId(dataMedicine); + dataMedicineFileService.updateUserIdByMedicineId(dataMedicine.getId()); + } + +} diff --git a/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/service/task/DataMedicineRecycleFile.java b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/service/task/DataMedicineRecycleFile.java new file mode 100644 index 0000000..4372bfa --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/java/org/dubhe/dcm/service/task/DataMedicineRecycleFile.java @@ -0,0 +1,114 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.dcm.service.task; + +import com.alibaba.fastjson.JSONObject; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.dubhe.data.dao.DatasetLabelMapper; +import org.dubhe.data.dao.DatasetVersionFileMapper; +import org.dubhe.data.dao.FileMapper; +import org.dubhe.data.service.DatasetService; +import org.dubhe.dcm.service.DataMedicineFileService; +import org.dubhe.dcm.service.DataMedicineService; +import org.dubhe.recycle.domain.dto.RecycleCreateDTO; +import org.dubhe.recycle.domain.dto.RecycleDetailCreateDTO; +import org.dubhe.recycle.enums.RecycleTypeEnum; +import org.dubhe.recycle.global.AbstractGlobalRecycle; +import org.dubhe.recycle.utils.RecycleTool; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.cloud.context.config.annotation.RefreshScope; +import org.springframework.stereotype.Component; + +import javax.annotation.Resource; +import java.util.Objects; +import java.util.concurrent.TimeUnit; + +import static org.dubhe.data.constant.Constant.LIMIT_NUMBER; + +/** + * @description 数据集文件删除类 + * @date 2021-03-03 + */ +@RefreshScope +@Component(value = "dataMedicineRecycleFile") +public class DataMedicineRecycleFile extends AbstractGlobalRecycle { + + @Value("${recycle.over-second.file}") + private long overSecond; + + + /** + * 数据集 service + */ + @Resource + private DataMedicineService dataMedicineService; + + /** + * 数据集 service + */ + @Resource + private DataMedicineFileService dataMedicineFileService; + + + @Autowired + private RecycleTool recycleTool; + + /** + * 根据数据集Id删除数据文件 + * + * @param detail 数据清理详情参数 + * @param dto 资源回收创建对象 + * @return true 继续执行,false 中断任务详情回收(本次无法执行完毕,创建新任务到下次执行) + */ + @Override + protected boolean clearDetail(RecycleDetailCreateDTO detail, RecycleCreateDTO dto) { + LogUtil.info(LogEnum.BIZ_DATASET, "DataMedicineRecycleFile.clear() , param:{}", JSONObject.toJSONString(detail)); + if (!Objects.isNull(detail.getRecycleCondition()) && RecycleTypeEnum.TABLE_DATA.getCode().compareTo(detail.getRecycleType()) == 0) { + //清理DB数据 + Long datasetId = Long.valueOf(detail.getRecycleCondition()); + dataMedicineService.deleteByDatasetId(datasetId); + dataMedicineFileService.deleteByDatasetId(datasetId); + }else { + //清理mino数据 + String recycleCondition = detail.getRecycleCondition(); + recycleTool.delTempInvalidResources(recycleCondition); + } + return true; + } + + + /** + * 数据还原 + * + * @param dto 数据清理参数 + */ + @Override + protected void rollback(RecycleCreateDTO dto) { + dataMedicineService.allRollback(dto); + } + + /** + * 覆盖数据集文件删除超时时间 + * @return 自定义超时秒 + */ + @Override + public long getRecycleOverSecond() { + return overSecond; + } +} diff --git a/dubhe-server/dubhe-data-dcm/src/main/resources/banner.txt b/dubhe-server/dubhe-data-dcm/src/main/resources/banner.txt new file mode 100644 index 0000000..6da4bbd --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/resources/banner.txt @@ -0,0 +1,8 @@ + _ _ _ _ + | | | | | | | | + __| |_ _| |__ | |__ ___ __| | ___ _ __ ___ + / _` | | | | '_ \| '_ \ / _ \ / _` |/ __| '_ ` _ \ +| (_| | |_| | |_) | | | | __/ | (_| | (__| | | | | | + \__,_|\__,_|_.__/|_| |_|\___| \__,_|\___|_| |_| |_| + + :: Dubhe org.dubhe.dcm :: 0.0.1-SNAPSHOT diff --git a/dubhe-server/dubhe-data-dcm/src/main/resources/bootstrap.yml b/dubhe-server/dubhe-data-dcm/src/main/resources/bootstrap.yml new file mode 100644 index 0000000..46b2f81 --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/resources/bootstrap.yml @@ -0,0 +1,50 @@ +server: + port: 8011 + # rest API 版本号 + rest-version: v1 + + +spring: + application: + name: dubhe-data-dcm + profiles: + active: dev + cloud: + nacos: + config: + enabled: true + server-addr: 127.0.0.1:8848 + namespace: dubhe-server-cloud-prod + shared-configs[0]: + data-id: common-biz.yaml + group: dubhe + refresh: true # 是否动态刷新,默认为false + shared-configs[1]: + data-id: common-recycle.yaml + group: dubhe + refresh: true + shared-configs[2]: + data-id: common-shardingjdbc.yaml + group: dubhe + refresh: true + shared-configs[3]: + data-id: dubhe-data.yaml + group: dubhe + refresh: true + shared-configs[4]: + data-id: common-k8s.yaml + group: dubhe + refresh: true + shared-configs[5]: + data-id: dubhe-data-dcm.yaml + group: dubhe + refresh: true + + discovery: + enabled: true + namespace: dubhe-server-cloud-prod + group: dubhe + server-addr: 127.0.0.1:8848 + # 配置允许后面的Bean覆盖前面名称重复的Bean + main: + allow-bean-definition-overriding: true \ No newline at end of file diff --git a/dubhe-server/dubhe-data-dcm/src/main/resources/mapper/DataMedicineFileMapper.xml b/dubhe-server/dubhe-data-dcm/src/main/resources/mapper/DataMedicineFileMapper.xml new file mode 100644 index 0000000..28d8c61 --- /dev/null +++ b/dubhe-server/dubhe-data-dcm/src/main/resources/mapper/DataMedicineFileMapper.xml @@ -0,0 +1,35 @@ + + + + + + + + + INSERT INTO data_medicine_file + ( + create_user_id, + update_user_id, + name, + status, + medicine_id, + url, + origin_user_id, + sop_instance_uid + ) + VALUES + + (#{item.createUserId}, #{item.updateUserId}, + #{item.name}, #{item.status}, #{item.medicineId}, + #{item.url}, #{item.originUserId}, #{item.sopInstanceUid}) + + + + \ No newline at end of file diff --git a/dubhe-server/dubhe-data-task/pom.xml b/dubhe-server/dubhe-data-task/pom.xml new file mode 100644 index 0000000..07ded47 --- /dev/null +++ b/dubhe-server/dubhe-data-task/pom.xml @@ -0,0 +1,146 @@ + + + 4.0.0 + + org.dubhe + server + 0.0.1-SNAPSHOT + + org.dubhe + dubhe-data-task + 0.0.1-SNAPSHOT + jar + Task 数据集定时任务 + 数据集定时任务模块 + + + + + org.dubhe.biz + base + ${org.dubhe.biz.base.version} + + + org.dubhe.biz + file + ${org.dubhe.biz.file.version} + + + org.dubhe.biz + data-permission + ${org.dubhe.biz.data-permission.version} + + + org.dubhe.biz + redis + ${org.dubhe.biz.redis.version} + + + + org.dubhe.cloud + registration + ${org.dubhe.cloud.registration.version} + + + + org.dubhe.cloud + configuration + ${org.dubhe.cloud.configuration.version} + + + + org.dubhe.cloud + remote-call + ${org.dubhe.cloud.remote-call.version} + + + + org.dubhe.biz + log + ${org.dubhe.biz.log.version} + + + org.springframework.boot + spring-boot-starter-web + + + + + org.springframework.boot + spring-boot-starter-mail + + + + + org.mapstruct + mapstruct-jdk8 + ${mapstruct.version} + + + org.mapstruct + mapstruct-processor + ${mapstruct.version} + provided + + + + org.bytedeco + javacv + + + org.bytedeco.javacpp-presets + ffmpeg-platform + + + + org.apache.shardingsphere + sharding-jdbc-spring-boot-starter + ${sharding-jdbc} + + + org.dubhe + dubhe-data + ${org.dubhe.dubhe-data.version} + + + org.dubhe + dubhe-data-dcm + ${org.dubhe.dubhe-data-dcm.version} + + + com.alibaba + easyexcel + ${easyexcel} + + + net.sourceforge.javacsv + javacsv + ${javacsv} + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + false + true + exec + true + + + + + org.apache.maven.plugins + maven-surefire-plugin + + true + + + + + + diff --git a/dubhe-server/dubhe-data-task/src/main/java/org/dubhe/task/DubheDataTaskApplication.java b/dubhe-server/dubhe-data-task/src/main/java/org/dubhe/task/DubheDataTaskApplication.java new file mode 100644 index 0000000..c659b9e --- /dev/null +++ b/dubhe-server/dubhe-data-task/src/main/java/org/dubhe/task/DubheDataTaskApplication.java @@ -0,0 +1,39 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.task; + +import org.mybatis.spring.annotation.MapperScan; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.scheduling.annotation.EnableScheduling; + +/** + * @description 定时任务管理 + * @date 2020-12-18 + */ +@SpringBootApplication(scanBasePackages = "org.dubhe") +@MapperScan(basePackages = {"org.dubhe.**.dao"}) +@EnableScheduling +public class DubheDataTaskApplication { + + public static void main(String[] args) { + System.setProperty("es.set.netty.runtime.available.processors", "false"); + SpringApplication.run(DubheDataTaskApplication.class, args); + } + +} diff --git a/dubhe-server/dubhe-data-task/src/main/java/org/dubhe/task/data/AnnotationCopySchedule.java b/dubhe-server/dubhe-data-task/src/main/java/org/dubhe/task/data/AnnotationCopySchedule.java new file mode 100644 index 0000000..cbc35a6 --- /dev/null +++ b/dubhe-server/dubhe-data-task/src/main/java/org/dubhe/task/data/AnnotationCopySchedule.java @@ -0,0 +1,50 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.task.data; + +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.handler.ScheduleTaskHandler; +import org.dubhe.biz.log.utils.LogUtil; +import org.dubhe.data.service.DatasetVersionService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +/** + * @description 标注文件复制 + * @date 2020-12-20 + */ +@Component +public class AnnotationCopySchedule { + + @Autowired + private DatasetVersionService datasetVersionService; + + /** + * 标注文件复制 + */ + @Scheduled(fixedDelay = 15000) + public void annotationFileCopy() { + ScheduleTaskHandler.process(() -> { + LogUtil.info(LogEnum.BIZ_DATASET, "annotation file copy and roll back --- > start"); + datasetVersionService.annotationFileCopy(); + LogUtil.info(LogEnum.BIZ_DATASET, "annotation file copy and roll back --- > end"); + }); + } + +} diff --git a/dubhe-server/dubhe-data-task/src/main/java/org/dubhe/task/data/AnnotationQueueExecuteThread.java b/dubhe-server/dubhe-data-task/src/main/java/org/dubhe/task/data/AnnotationQueueExecuteThread.java new file mode 100644 index 0000000..bcc3a90 --- /dev/null +++ b/dubhe-server/dubhe-data-task/src/main/java/org/dubhe/task/data/AnnotationQueueExecuteThread.java @@ -0,0 +1,124 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.task.data; + +import cn.hutool.core.util.ObjectUtil; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import lombok.extern.slf4j.Slf4j; +import org.dubhe.biz.base.constant.MagicNumConstant; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.dubhe.biz.redis.utils.RedisUtils; +import org.dubhe.data.domain.bo.TaskSplitBO; +import org.dubhe.data.domain.dto.AnnotationInfoCreateDTO; +import org.dubhe.data.domain.dto.BatchAnnotationInfoCreateDTO; +import org.dubhe.data.service.AnnotationService; +import org.dubhe.data.util.TaskUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeUnit; + +/** + * @description 自动标注完成队列处理 + * @date 2020-08-28 + */ +@Slf4j +@Component +public class AnnotationQueueExecuteThread implements Runnable { + + @Autowired + private RedisUtils redisUtils; + @Autowired + private AnnotationService annotationService; + @Autowired + private TaskUtils taskUtils; + + /** + * 标注算法执行中任务队列 + */ + private static final String ANNOTATION_START_QUEUE = "annotation_processing_queue"; + /** + * 标注算法未执行任务队列 + */ + private static final String ANNOTATION_PENDING_QUEUE = "annotation_task_queue"; + /** + * 标注算法已完成任务队列 + */ + private static final String ANNOTATION_FINISHED_QUEUE = "annotation_finished_queue"; + + /** + * 启动标注任务处理线程 + */ + @PostConstruct + public void start() { + Thread thread = new Thread(this, "自动标注完成任务处理队列"); + thread.start(); + } + + /** + * 标注任务处理方法 + */ + @Override + public void run() { + while (true) { + try { + Object object = redisUtils.lpop(ANNOTATION_FINISHED_QUEUE); + if (ObjectUtil.isNotNull(object)) { + Long start = System.currentTimeMillis(); + JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(redisUtils.get(object.toString()))); + String detailId = jsonObject.getString("reTaskId"); + JSONObject taskDetail = JSON.parseObject(JSON.toJSONString(redisUtils.get(detailId))); + // 得到一个任务的拆分 包括多个file + TaskSplitBO taskSplitBO = JSON.parseObject(JSON.toJSONString(taskDetail), TaskSplitBO.class); + JSONArray jsonArray = jsonObject.getJSONArray("annotations"); + + List list = new ArrayList<>(); + for (int i = 0; i < jsonArray.size(); i++) { + list.add(JSON.toJavaObject(jsonArray.getJSONObject(i), AnnotationInfoCreateDTO.class)); + } + BatchAnnotationInfoCreateDTO batchAnnotationInfoCreateDTO = new BatchAnnotationInfoCreateDTO(); + batchAnnotationInfoCreateDTO.setAnnotations(list); + annotationService.doFinishAuto(taskSplitBO, batchAnnotationInfoCreateDTO.toMap()); + redisUtils.del(detailId); + LogUtil.info(LogEnum.BIZ_DATASET, "the time it takes to perform a task is {} second", (System.currentTimeMillis() - start)); + TimeUnit.MILLISECONDS.sleep(MagicNumConstant.TEN); + } else { + TimeUnit.MILLISECONDS.sleep(MagicNumConstant.THREE_THOUSAND); + } + } catch (Exception exception) { + LogUtil.error(LogEnum.BIZ_DATASET, "annotation exception:{}", exception); + } + } + } + + /** + * annotation任务是否过期 + */ + @Scheduled(cron = "*/15 * * * * ?") + public void expireAnnotationTask() { + taskUtils.restartTask(ANNOTATION_START_QUEUE, ANNOTATION_PENDING_QUEUE); + } + +} diff --git a/dubhe-server/dubhe-data-task/src/main/java/org/dubhe/task/data/DataTaskExecuteThread.java b/dubhe-server/dubhe-data-task/src/main/java/org/dubhe/task/data/DataTaskExecuteThread.java new file mode 100644 index 0000000..c017a3e --- /dev/null +++ b/dubhe-server/dubhe-data-task/src/main/java/org/dubhe/task/data/DataTaskExecuteThread.java @@ -0,0 +1,632 @@ +/** + * Copyright 2020 Tianshu AI Platform. All Rights Reserved. + * + * Licensed 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 org.dubhe.task.data; + +import cn.hutool.core.collection.CollectionUtil; +import cn.hutool.core.util.ObjectUtil; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import lombok.SneakyThrows; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.ListUtils; +import org.bytedeco.javacv.FFmpegFrameGrabber; +import org.dubhe.biz.base.constant.DataStateCodeConstant; +import org.dubhe.biz.base.constant.MagicNumConstant; +import org.dubhe.biz.base.constant.NumberConstant; +import org.dubhe.biz.base.utils.StringUtils; +import org.dubhe.biz.log.enums.LogEnum; +import org.dubhe.biz.log.utils.LogUtil; +import org.dubhe.biz.redis.utils.RedisUtils; +import org.dubhe.biz.statemachine.dto.StateChangeDTO; +import org.dubhe.data.constant.Constant; +import org.dubhe.data.constant.DatasetLabelEnum; +import org.dubhe.data.domain.bo.TaskSplitBO; +import org.dubhe.data.domain.dto.DatasetEnhanceRequestDTO; +import org.dubhe.data.domain.dto.FileCreateDTO; +import org.dubhe.data.domain.dto.OfRecordTaskDto; +import org.dubhe.data.domain.entity.*; +import org.dubhe.biz.base.vo.DatasetVO; +import org.dubhe.data.machine.constant.DataStateMachineConstant; +import org.dubhe.data.machine.utils.StateMachineUtil; +import org.dubhe.data.pool.BasePool; +import org.dubhe.data.service.*; +import org.dubhe.data.util.TaskUtils; +import org.dubhe.dcm.domain.entity.DataMedicineFile; +import org.dubhe.dcm.service.DataMedicineFileService; +import org.dubhe.task.util.TableDataUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.dao.DataAccessException; +import org.springframework.data.redis.connection.RedisConnection; +import org.springframework.data.redis.core.RedisCallback; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; + +import javax.annotation.PostConstruct; +import javax.annotation.Resource; +import java.util.*; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Collectors; + +/** + * @description 数据集任务处理方法(主要进行任务的拆解和分发) + * @date 2020-08-27 + */ +@Slf4j +@Component +public class DataTaskExecuteThread implements Runnable { + + @Autowired + private TaskService taskService; + @Autowired + private FileService fileService; + @Autowired + private DatasetService datasetService; + @Autowired + private RedisTemplate redisTemplate; + @Autowired + private RedisUtils redisUtils; + @Autowired + private DatasetLabelService datasetLabelService; + @Autowired + private DatasetVersionService datasetVersionService; + @Autowired + private DatasetVersionFileService datasetVersionFileService; + @Autowired + private AnnotationService annotationService; + @Autowired + private DatasetEnhanceService datasetEnhanceService; + @Autowired + private DataMedicineFileService dataMedicineFileService; + + @Resource + private TaskUtils taskUtils; + + @Value("${minio.bucketName}") + private String bucketName; + + @Value("${storage.file-store-root-path}") + private String nfsRootPath; + + @Autowired + private TableDataUtil tableDataUtil; + + /** + * 线程池 + */ + @Autowired + private BasePool pool; + + /** + * 路径名前缀 + */ + @Value("${storage.file-store-root-path:/nfs/}") + private String prefixPath; + /** + * 标注任务一次查询的数量 + */ + private static final Integer ANNOTATION_BATCH_SIZE = MagicNumConstant.SIXTEEN * MagicNumConstant.TEN_THOUSAND; + + /** + * 文本分类算法待处理任务队列 + */ + private static final String TC_TASK_QUEUE = "text_classification_task_queue"; + /** + * 标注算法待处理任务队列 + */ + private static final String ANNOTATION_TASK_QUEUE = "annotation_task_queue"; + /** + * ImageNet算法待处理任务队列 + */ + private static final String IMAGENET_TASK_QUEUE = "imagenet_task_queue"; + /** + * ofRecord算法待处理任务队列 + */ + private static final String OFRECORD_TASK_QUEUE = "ofrecord_task_queue"; + /** + * 目标跟踪算法待处理任务队列 + */ + private static final String TRACK_TASK_QUEUE = "track_task_queue"; + /** + * 医学标注算法待处理任务队列 + */ + private static final String MEDICINE_PENDING_QUEUE = "dcm_task_queue"; + + /** + * 启动生成任务线程 + */ + @PostConstruct + public void start() { + Thread thread = new Thread(this, "数据集任务生成"); + thread.start(); + } + + /** + * 生成任务run方法 + */ + @Override + public void run() { + while (true) { + try { + work(); + TimeUnit.MILLISECONDS.sleep(MagicNumConstant.ONE_THOUSAND); + } catch (Exception e) { + LogUtil.error(LogEnum.BIZ_DATASET, "get algorithm task failed:{}", e); + } + } + } + + /** + * 单个任务处理 + */ + public void work() { + // 获取一个待处理任务 + Task task = taskService.getOnePendingTask(); + if (ObjectUtil.isNotNull(task)) { + // 执行任务 + execute(task); + } + } + + /** + * 执行任务 + * + * @param task 任务详情 + */ + public void execute(Task task) { + // 任务加锁 + int count = taskService.updateTaskStatus(task.getId(), MagicNumConstant.ZERO, MagicNumConstant.ONE); + if (count != 0) { + switch (task.getType()) { + case MagicNumConstant.ZERO: + annotationExecute(NumberConstant.NUMBER_0,task); + break; + case MagicNumConstant.ONE: + ofRecordExecute(task); + break; + case MagicNumConstant.FOUR: + trackExecute(task); + break; + case MagicNumConstant.THREE: + enhanceExecute(task); + break; + case MagicNumConstant.FIVE: + videoSampleExecute(task); + break; + case MagicNumConstant.SIX: + medicineExecute(task); + break; + case MagicNumConstant.SEVEN: + textClassificationExecute(task); + break; + case MagicNumConstant.EIGHT: + annotationService.deleteAnnotating(task.getDatasetId()); + annotationExecute(NumberConstant.NUMBER_0,task); + break; + case MagicNumConstant.TEN: + csvImport(task); + break; + case MagicNumConstant.ELEVEN: + convertPreDataset(task); + default: + LogUtil.info(LogEnum.BIZ_DATASET, "未识别任务"); + break; + } + taskService.updateTaskStatus(task.getId(), MagicNumConstant.ONE, MagicNumConstant.TWO); + } + } + + /** + * 跟踪任务 + * + * @param task 任务详情 + */ + public void trackExecute(Task task) { + Dataset dataset = datasetService.getOneById(task.getDatasetId()); + Map> fileMap = annotationService.queryFileAccordingToCurrentVersionAndStatus(dataset); + List fileList = datasetVersionFileService.getFileListByVersionFileList(fileMap.get(task.getDatasetId())); + JSONObject jsonObject = new JSONObject(); + jsonObject.put("path", nfsRootPath + bucketName + java.io.File.separator + dataset.getUri() + + (dataset.getCurrentVersionName() != null ? "/versionFile/" + dataset.getCurrentVersionName() : "")); + String taskId = UUID.randomUUID().toString(); + jsonObject.put("id", task.getId().toString()); + List images = new ArrayList<>(); + fileList.stream().forEach(file -> { + images.add(file.getUrl().substring(file.getUrl().lastIndexOf("/") + 1, file.getUrl().length())); + }); + jsonObject.put("images", images); + redisUtils.set(taskId, jsonObject); + redisUtils.zSet(TRACK_TASK_QUEUE, -1, taskId); + } + + + /** + * 标注任务处理 + * + * @param task 任务信息 + */ + public void textClassificationExecute(Task task) { + int offset = 0; + while (true) { + if (!generateTextClassificationTask(offset, task)) { + break; + } + } + } + + /** + * ofRecord转换任务处理 + * + * @param task 任务信息 + */ + public void ofRecordExecute(Task task) { + List